@firecms/user_management 3.0.0-canary.17 → 3.0.0-canary.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.es.js +312 -305
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/types/user_management.d.ts +7 -2
- package/package.json +5 -5
- package/src/hooks/useBuildFirestoreUserManagement.tsx +35 -4
- package/src/types/user_management.tsx +8 -2
package/dist/index.umd.js
CHANGED
@@ -1,2 +1,2 @@
|
|
1
|
-
(function(i,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("react"),require("firebase/firestore"),require("react/jsx-runtime"),require("@firecms/ui"),require("yup"),require("@firecms/core"),require("@firecms/formex"),require("date-fns"),require("date-fns/locale")):typeof define=="function"&&define.amd?define(["exports","react","firebase/firestore","react/jsx-runtime","@firecms/ui","yup","@firecms/core","@firecms/formex","date-fns","date-fns/locale"],c):(i=typeof globalThis<"u"?globalThis:i||self,c(i.FireCMS={},i.React,i.firestore,i.jsxRuntime,i.ui,i.Yup,i.core,i.formex,i.dateFns,i.locales))})(this,function(i,c,N,e,l,se,S,P,re,ne){"use strict";function z(s){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const o in s)if(o!=="default"){const d=Object.getOwnPropertyDescriptor(s,o);Object.defineProperty(r,o,d.get?d:{enumerable:!0,get:()=>s[o]})}}return r.default=s,Object.freeze(r)}const B=z(se),ae=z(ne),te=["Admin"],ie={read:!1,edit:!1,create:!1,delete:!1};function J({collection:s,user:r}){const o=r?.roles;if(o){if(s.ownerId===r?.uid)return{read:!0,create:!0,edit:!0,delete:!0};{const d={read:!1,create:!1,edit:!1,delete:!1};return o.map(n=>ce(n,s.id)).reduce(Y,d)}}else return ie}function ce(s,r){const o={read:s.isAdmin||s.defaultPermissions?.read,create:s.isAdmin||s.defaultPermissions?.create,edit:s.isAdmin||s.defaultPermissions?.edit,delete:s.isAdmin||s.defaultPermissions?.delete};return s.collectionPermissions&&s.collectionPermissions[r]?Y(s.collectionPermissions[r],o):s.defaultPermissions?Y(s.defaultPermissions,o):o}const Y=(s,r)=>({read:s.read||r.read,create:s.create||r.create,edit:s.edit||r.edit,delete:s.delete||r.delete});function de(s,r){return s?r.roles?r.roles.map(o=>s.find(d=>d.id===o.id)).filter(Boolean):[]:void 0}const H=(s,r)=>{const o=s.map(n=>n.id),d=r.map(n=>n.id);return o.length===r.length&&o.every(n=>d.includes(n))};function he(s,r){if(!r)return;const o=Ce(r),d=new Date(o.exp*1e3);localStorage.setItem(`auth_token::${s}`,JSON.stringify({token:r,expiry:d}))}function fe(s){const r=localStorage.getItem(`auth_token::${s}`);if(r){const o=JSON.parse(r);if(o.expiry=new Date(o.expiry),o.expiry>new Date)return o.token}}function ge(){for(let s=0;s<localStorage.length;s++){const r=localStorage.key(s);r?.startsWith("auth_token::")&&localStorage.removeItem(r)}}function Ce(s){if(!s)throw new Error("No JWT token");const o=s.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),d=decodeURIComponent(window.atob(o).split("").map(function(n){return"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(d)}function pe(s,r=10){if(!/^#([0-9A-Fa-f]{3}){1,2}$/.test(s))throw new Error("Invalid color format");let o=s.substring(1).split("");o.length===3&&(o=[o[0],o[0],o[1],o[1],o[2],o[2]]);let d=parseInt(o[0]+o[1],16),n=parseInt(o[2]+o[3],16),g=parseInt(o[4]+o[5],16);return d=Math.floor(d*(1-r/100)),n=Math.floor(n*(1-r/100)),g=Math.floor(g*(1-r/100)),"#"+(d<16?"0":"")+d.toString(16)+(n<16?"0":"")+n.toString(16)+(g<16?"0":"")+g.toString(16)}function me(s,r=10){if(!/^#([0-9A-Fa-f]{3}){1,2}$/.test(s))throw new Error("Invalid color format");let o=s.substring(1).split("");o.length===3&&(o=[o[0],o[0],o[1],o[1],o[2],o[2]]);const d=parseInt(o[0]+o[1],16),n=parseInt(o[2]+o[3],16),g=parseInt(o[4]+o[5],16),u=r/100;return`rgba(${d}, ${n}, ${g}, ${u})`}function be({firebaseApp:s,usersPath:r="__FIRECMS/config/users",rolesPath:o="__FIRECMS/config/roles",usersLimit:d,canEditRoles:n=!0,allowDefaultRolesCreation:g,includeCollectionConfigPermissions:u}){const C=c.useRef(),[U,v]=c.useState(!0),[h,x]=c.useState(!0),[T,t]=c.useState([]),[m,I]=c.useState([]),w=m.map(b=>({...b,roles:T.filter(y=>b.roles?.includes(y.id))})),[q,V]=c.useState(),[p,f]=c.useState(),D=U||h;c.useEffect(()=>{s&&(C.current=N.getFirestore(s))},[s]),c.useEffect(()=>{if(!s||!o)return;const b=N.getFirestore(s);return N.onSnapshot(N.collection(b,o),{next:y=>{V(void 0);try{const k=ve(y.docs);t(k)}catch(k){V(k)}v(!1)},error:y=>{V(y),v(!1)}})},[s,o]),c.useEffect(()=>{if(!s||!r)return;const b=N.getFirestore(s);return N.onSnapshot(N.collection(b,r),{next:y=>{f(void 0);try{const k=ue(y.docs);I(k)}catch(k){f(k)}x(!1)},error:y=>{f(y),x(!1)}})},[s,r]);const F=c.useCallback(async b=>{const y=C.current;if(!y||!r)throw Error("useFirestoreConfigurationPersistence Firestore not initialised");console.debug("Persisting user",b);const k=b.roles?.map(ke=>ke.id),{uid:$,...W}=b;return N.setDoc(N.doc(y,r,$),{...W,roles:k},{merge:!0}).then(()=>b)},[r]),A=c.useCallback(b=>{const y=C.current;if(!y||!o)throw Error("useFirestoreConfigurationPersistence Firestore not initialised");console.debug("Persisting role",b);const{id:k,...$}=b,W=N.doc(y,o,k);return N.setDoc(W,$,{merge:!0})},[o]),a=c.useCallback(async b=>{const y=C.current;if(!y||!r)throw Error("useFirestoreConfigurationPersistence Firestore not initialised");console.debug("Deleting",b);const{uid:k}=b;return N.deleteDoc(N.doc(y,r,k))},[r]),E=c.useCallback(b=>{const y=C.current;if(!y||!o)throw Error("useFirestoreConfigurationPersistence Firestore not initialised");console.debug("Deleting",b);const{id:k}=b,$=N.doc(y,o,k);return N.deleteDoc($)},[o]),L=c.useCallback(({collection:b,user:y})=>J({collection:b,user:y}),[]),M=w.map(b=>b.uid),De=c.useCallback(b=>{if(!w)throw Error("Users not loaded");return w.find(k=>k.email?.toLowerCase()===b?.email?.toLowerCase())?.roles},[M]);return{loading:D,roles:T,users:w,saveUser:F,saveRole:A,deleteUser:a,deleteRole:E,usersLimit:d,canEditRoles:n===void 0?!0:n,allowDefaultRolesCreation:g===void 0?!0:g,includeCollectionConfigPermissions:!!u,collectionPermissions:L,defineRolesFor:De}}const ue=s=>s.map(r=>{const o=r.data();return{uid:r.id,...o,created_on:o?.created_on?.toDate(),updated_on:o?.updated_on?.toDate()}}),ve=s=>s.map(r=>({id:r.id,...r.data()})),j=c.createContext({});function G({children:s,userManagement:r}){return e.jsx(j.Provider,{value:r,children:s})}const _=()=>c.useContext(j);function O({role:s}){let r;return s.isAdmin?r="blueDarker":s.id==="editor"?r="yellowLight":s.id==="viewer"?r="grayLight":r=l.getColorSchemeForSeed(s.id),e.jsx(l.Chip,{colorScheme:r,children:s.name},s.id)}const K=B.object().shape({id:B.string().required("Required"),name:B.string().required("Required")});function Q({open:s,role:r,editable:o,handleClose:d,collections:n}){const{saveRole:g}=_(),u=!r,[C,U]=c.useState(),v=c.useCallback(a=>(U(void 0),g(a)),[g]),h=P.useCreateFormex({initialValues:r??{name:""},onSubmit:(a,E)=>v(a).then(()=>{E.resetForm({values:a}),d()}).catch(L=>U(L)),validation:a=>K.validate(a,{abortEarly:!1}).then(()=>({})).catch(E=>{const L={};return E.inner.forEach(M=>{L[M.path]=M.message}),L})}),{isSubmitting:x,touched:T,values:t,errors:m,handleChange:I,setFieldValue:w,dirty:q,setFieldTouched:V}=h,p=t.isAdmin??!1,f=t.defaultPermissions?.create??!1,D=t.defaultPermissions?.read??!1,F=t.defaultPermissions?.edit??!1,A=t.defaultPermissions?.delete??!1;return c.useEffect(()=>{!P.getIn(T,"id")&&t.name&&w("id",S.toSnakeCase(t.name))},[T,t.name]),e.jsx(l.Dialog,{open:s,maxWidth:"4xl",children:e.jsx(P.Formex,{value:h,children:e.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:h.handleSubmit,style:{display:"flex",flexDirection:"column",position:"relative",height:"100%"},children:[e.jsxs(l.DialogContent,{className:"flex-grow",children:[e.jsx("div",{className:"flex flex-row pt-12 pb-8",children:e.jsx(l.Typography,{variant:"h4",className:"flex-grow",children:"Role"})}),e.jsxs("div",{className:"grid grid-cols-12 gap-8",children:[e.jsxs("div",{className:"col-span-12 md:col-span-8",children:[e.jsx(l.TextField,{name:"name",required:!0,error:T.name&&!!m.name,value:t.name,disabled:p||!o,onChange:I,"aria-describedby":"name-helper-text",label:"Name"}),e.jsx(S.FieldCaption,{children:T.name&&m.name?m.name:"Name of this role"})]}),e.jsxs("div",{className:"col-span-12 md:col-span-4",children:[e.jsx(l.TextField,{name:"id",required:!0,error:T.id&&!!m.id,value:t.id,disabled:!u||!o,onChange:a=>{I(a),V("id",!0)},"aria-describedby":"id-helper-text",label:"ID"}),e.jsx(S.FieldCaption,{children:T.id&&m.id?m.id:"ID of this role"})]}),e.jsxs("div",{className:"col-span-12",children:[e.jsx(l.Paper,{className:"bg-inherit",children:e.jsxs(l.Table,{children:[e.jsxs(l.TableHeader,{children:[e.jsx(l.TableCell,{}),e.jsx(l.TableCell,{align:"center",children:"Create entities"}),e.jsx(l.TableCell,{align:"center",children:"Read entities"}),e.jsx(l.TableCell,{align:"center",children:"Update entities"}),e.jsx(l.TableCell,{align:"center",children:"Delete entities"})]}),e.jsxs(l.TableBody,{children:[e.jsxs(l.TableRow,{children:[e.jsx(l.TableCell,{scope:"row",children:e.jsx("strong",{children:"All collections"})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Tooltip,{title:"Create entities in collections",children:e.jsx(l.Checkbox,{disabled:p||!o,checked:(p||f)??!1,onCheckedChange:a=>w("defaultPermissions.create",a)})})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Tooltip,{title:"Access all data in every collection",children:e.jsx(l.Checkbox,{disabled:p||!o,checked:(p||D)??!1,onCheckedChange:a=>w("defaultPermissions.read",a)})})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Tooltip,{title:"Update data in any collection",children:e.jsx(l.Checkbox,{disabled:p||!o,checked:(p||F)??!1,onCheckedChange:a=>w("defaultPermissions.edit",a)})})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Tooltip,{title:"Delete data in any collection",children:e.jsx(l.Checkbox,{disabled:p||!o,checked:(p||A)??!1,onCheckedChange:a=>w("defaultPermissions.delete",a)})})})]}),n&&n.map(a=>e.jsxs(l.TableRow,{children:[e.jsx(l.TableCell,{scope:"row",children:a.name}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:p||f||!o,checked:(p||f||P.getIn(t,`collectionPermissions.${a.path}.create`))??!1,onCheckedChange:E=>w(`collectionPermissions.${a.path}.create`,E)})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:p||D||!o,checked:(p||D||P.getIn(t,`collectionPermissions.${a.path}.read`))??!1,onCheckedChange:E=>w(`collectionPermissions.${a.path}.read`,E)})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:p||F||!o,checked:(p||F||P.getIn(t,`collectionPermissions.${a.path}.edit`))??!1,onCheckedChange:E=>w(`collectionPermissions.${a.path}.edit`,E)})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:p||A||!o,checked:(p||A||P.getIn(t,`collectionPermissions.${a.path}.delete`))??!1,onCheckedChange:E=>w(`collectionPermissions.${a.path}.delete`,E)})})]},a.name))]})]})}),e.jsx(S.FieldCaption,{children:"You can customise the permissions that the users related to this role can perform in the entities of each collection"})]}),e.jsxs("div",{className:"col-span-12 md:col-span-4",children:[e.jsxs(l.Select,{error:T.config&&!!m.config,id:"createCollections",name:"createCollections",label:"Create collections",position:"item-aligned",disabled:p||!o,onChange:a=>w("config.createCollections",a.target.value==="true"),value:p||t.config?.createCollections?"true":"false",renderValue:a=>a==="true"?"Yes":"No",children:[e.jsx(l.SelectItem,{value:"true",children:" Yes "}),e.jsx(l.SelectItem,{value:"false",children:" No "})]}),e.jsx(S.FieldCaption,{children:T.config&&m.config?m.config:"Can the user create collections"})]}),e.jsxs("div",{className:"col-span-12 md:col-span-4",children:[e.jsxs(l.Select,{error:T.config&&!!m.config,id:"editCollections",name:"editCollections",label:"Edit collections",disabled:p||!o,position:"item-aligned",onChange:a=>w("config.editCollections",a.target.value==="own"?"own":a.target.value==="true"),value:p?"true":t.config?.editCollections==="own"?"own":t.config?.editCollections?"true":"false",renderValue:a=>a==="own"?"Own":a==="true"?"Yes":"No",children:[e.jsx(l.SelectItem,{value:"true",children:" Yes "}),e.jsx(l.SelectItem,{value:"false",children:" No "}),e.jsx(l.SelectItem,{value:"own",children:" Only his/her own "})]}),e.jsx(S.FieldCaption,{children:T.config&&m.config?m.config:"Can the user edit collections"})]}),e.jsxs("div",{className:"col-span-12 md:col-span-4",children:[e.jsxs(l.Select,{error:T.config&&!!m.config,id:"deleteCollections",name:"deleteCollections",label:"Delete collections",disabled:p||!o,position:"item-aligned",onChange:a=>w("config.deleteCollections",a.target.value==="own"?"own":a.target.value==="true"),value:p?"true":t.config?.deleteCollections==="own"?"own":t.config?.deleteCollections?"true":"false",renderValue:a=>a==="own"?"Own":a==="true"?"Yes":"No",children:[e.jsx(l.SelectItem,{value:"true",children:" Yes "}),e.jsx(l.SelectItem,{value:"false",children:" No "}),e.jsx(l.SelectItem,{value:"own",children:" Only his/her own "})]}),e.jsx(S.FieldCaption,{children:T.config&&m.config?m.config:"Can the user delete collections"})]})]})]}),e.jsxs(l.DialogActions,{position:"sticky",children:[C&&e.jsx(l.Typography,{className:"text-red-500",children:"There was an error saving this role"}),e.jsx(l.Button,{variant:"text",onClick:()=>{d()},children:"Cancel"}),e.jsx(l.LoadingButton,{variant:"filled",color:"primary",type:"submit",disabled:!q,loading:x,startIcon:e.jsx(l.DoneIcon,{}),children:u?"Create role":"Update"})]})]})})})}const we=[{id:"admin",name:"Admin",isAdmin:!0},{id:"editor",name:"Editor",isAdmin:!1,defaultPermissions:{read:!0,create:!0,edit:!0,delete:!0},config:{createCollections:!0,editCollections:"own",deleteCollections:"own"}},{id:"viewer",name:"Viewer",isAdmin:!1,defaultPermissions:{read:!0,create:!1,edit:!1,delete:!1}}];function X({onRoleClicked:s,editable:r}){const{roles:o,saveRole:d,deleteRole:n,allowDefaultRolesCreation:g}=_(),[u,C]=c.useState(void 0),[U,v]=c.useState(!1);return e.jsxs("div",{className:"w-full overflow-auto",children:[e.jsxs(l.Table,{children:[e.jsxs(l.TableHeader,{children:[e.jsx(l.TableCell,{header:!0,className:"w-16"}),e.jsx(l.TableCell,{header:!0,children:"Role"}),e.jsx(l.TableCell,{header:!0,className:"items-center",children:"Is Admin"}),e.jsx(l.TableCell,{header:!0,children:"Default permissions"})]}),e.jsxs(l.TableBody,{children:[o&&o.map(h=>{const x=h.isAdmin||h.defaultPermissions?.create,T=h.isAdmin||h.defaultPermissions?.read,t=h.isAdmin||h.defaultPermissions?.edit,m=h.isAdmin||h.defaultPermissions?.delete;return e.jsxs(l.TableRow,{onClick:()=>{s(h)},children:[e.jsx(l.TableCell,{style:{width:"64px"},children:!h.isAdmin&&e.jsx(l.Tooltip,{title:"Delete this role",children:e.jsx(l.IconButton,{size:"small",disabled:!r,onClick:I=>(I.stopPropagation(),C(h)),children:e.jsx(l.DeleteIcon,{})})})}),e.jsx(l.TableCell,{children:e.jsx(O,{role:h})}),e.jsx(l.TableCell,{className:"items-center",children:e.jsx(l.Checkbox,{checked:h.isAdmin??!1})}),e.jsx(l.TableCell,{children:e.jsxs("ul",{children:[x&&e.jsx("li",{children:"Create"}),T&&e.jsx("li",{children:"Read"}),t&&e.jsx("li",{children:"Update"}),m&&e.jsx("li",{children:"Delete"})]})})]},h.name)}),(!o||o.length===0)&&e.jsx(l.TableRow,{children:e.jsx(l.TableCell,{colspan:4,children:e.jsxs(l.CenteredView,{className:"flex flex-col gap-4 my-8 items-center",children:[e.jsx(l.Typography,{variant:"label",children:"You don't have any roles yet."}),g&&e.jsx(l.Button,{variant:"outlined",onClick:()=>{we.forEach(h=>{d(h)})},children:"Create default roles"})]})})})]})]}),e.jsx(S.DeleteConfirmationDialog,{open:!!u,loading:U,onAccept:()=>{u&&(v(!0),n(u).then(()=>{C(void 0)}).finally(()=>{v(!1)}))},onCancel:()=>{C(void 0)},title:e.jsx(e.Fragment,{children:"Delete?"}),body:e.jsx(e.Fragment,{children:"Are you sure you want to delete this role?"})})]})}const Z=c.memo(function({children:r}){const{collections:o}=S.useNavigationController(),[d,n]=c.useState(!1),[g,u]=c.useState(),{canEditRoles:C}=_(),U=c.useCallback(h=>{n(!0),u(h)},[]),v=()=>{u(void 0),n(!1)};return e.jsxs(l.Container,{className:"w-full flex flex-col py-4 gap-4",maxWidth:"6xl",children:[r,e.jsxs("div",{className:"flex items-center mt-12",children:[e.jsx(l.Typography,{gutterBottom:!0,variant:"h4",className:"flex-grow",component:"h4",children:"Roles"}),e.jsx(l.Tooltip,{title:C?void 0:"Update plans to customise roles",children:e.jsx(l.Button,{size:"large",disabled:!C,startIcon:e.jsx(l.AddIcon,{}),onClick:()=>n(!0),children:"Add role"})})]}),e.jsx(X,{onRoleClicked:U,editable:!!C}),e.jsx(Q,{open:d,role:g,editable:C,collections:o,handleClose:v},g?.id??"new")]})}),R=B.object().shape({displayName:B.string().required("Required"),email:B.string().email().required("Required"),roles:B.array().min(1)});function ye(s,r,o,d,n){const g=o.filter(v=>v.roles?.map(h=>h.id).includes("admin")),u=s.roles?.map(v=>v.id).includes("admin");if((!n||!H(n.roles??[],r.roles??[]))&&!u)throw new Error("Only admins can change roles");if(n&&n.roles?.map(v=>v.id).includes("admin")&&!r.roles?.map(v=>v.id).includes("admin")&&g.length===1)throw new Error("There must be at least one admin");return!0}function ee({open:s,user:r,handleClose:o}){const d=S.useSnackbarController(),{user:n}=S.useAuthController(),{saveUser:g,users:u,roles:C}=_(),U=!r,v=c.useCallback(f=>{if(!n)throw new Error("Logged user not found");try{return ye(n,f,u,C,r),g(f)}catch(D){return Promise.reject(D)}},[C,g,r,u,n]),h=P.useCreateFormex({initialValues:r??{displayName:"",email:"",roles:C.filter(f=>f.id==="editor")},validation:f=>R.validate(f,{abortEarly:!1}).then(()=>({})).catch(D=>D.inner.reduce((F,A)=>(F[A.path]=A.message,F),{})),onSubmit:(f,D)=>v(f).then(()=>{o(),D.resetForm({values:f})}).catch(F=>{d.open({type:"error",message:F.message})})}),{isSubmitting:x,touched:T,handleChange:t,values:m,errors:I,setFieldValue:w,dirty:q,handleSubmit:V,submitCount:p}=h;return e.jsx(l.Dialog,{open:s,onOpenChange:f=>f?void 0:o(),maxWidth:"4xl",children:e.jsx(P.Formex,{value:h,children:e.jsxs("form",{onSubmit:V,autoComplete:"off",noValidate:!0,style:{display:"flex",flexDirection:"column",position:"relative",height:"100%"},children:[e.jsxs(l.DialogContent,{className:"h-full flex-grow",children:[e.jsx("div",{className:"flex flex-row pt-4 pb-4",children:e.jsx(l.Typography,{variant:"h4",className:"flex-grow",children:"User"})}),e.jsxs("div",{className:"grid grid-cols-12 gap-8",children:[e.jsxs("div",{className:"col-span-12",children:[e.jsx(l.TextField,{name:"displayName",required:!0,error:p>0&&!!I.displayName,value:m.displayName??"",onChange:t,"aria-describedby":"name-helper-text",label:"Name"}),e.jsx(S.FieldCaption,{children:p>0&&I.displayName?I.displayName:"Name of this user"})]}),e.jsxs("div",{className:"col-span-12",children:[e.jsx(l.TextField,{required:!0,error:p>0&&!!I.email,name:"email",value:m.email??"",onChange:t,"aria-describedby":"email-helper-text",label:"Email"}),e.jsx(S.FieldCaption,{children:p>0&&I.email?I.email:"Email of this user"})]}),e.jsx("div",{className:"col-span-12",children:e.jsx(l.MultiSelect,{label:"Roles",value:m.roles?.map(f=>f.id)??[],onMultiValueChange:f=>w("roles",f.map(D=>C.find(F=>F.id===D))),renderValue:f=>{const D=C.find(F=>F.id===f);return D?e.jsx("div",{className:"flex flex-wrap space-x-2 space-y-2",children:e.jsx(O,{role:D},D?.id)}):null},children:C.map(f=>e.jsx(l.MultiSelectItem,{value:f.id,children:e.jsx(O,{role:f},f?.id)},f.id))})})]})]}),e.jsxs(l.DialogActions,{children:[e.jsx(l.Button,{variant:"text",onClick:()=>{o()},children:"Cancel"}),e.jsx(l.LoadingButton,{variant:"filled",color:"primary",type:"submit",disabled:!q,loading:x,startIcon:e.jsx(l.DoneIcon,{}),children:U?"Create user":"Update"})]})]})})})}function le({onUserClicked:s}){const{users:r,saveUser:o,deleteUser:d}=_(),n=S.useAuthController(),g=S.useSnackbarController(),u=S.useCustomizationController(),C=u?.locale?ae[u?.locale]:void 0,U=u?.dateTimeFormat??S.defaultDateFormat,[v,h]=c.useState(void 0),[x,T]=c.useState(!1);return e.jsxs("div",{className:"overflow-auto",children:[e.jsxs(l.Table,{children:[e.jsxs(l.TableHeader,{children:[e.jsx(l.TableCell,{className:"truncate w-16"}),e.jsx(l.TableCell,{children:"ID"}),e.jsx(l.TableCell,{children:"Email"}),e.jsx(l.TableCell,{children:"Name"}),e.jsx(l.TableCell,{children:"Roles"}),e.jsx(l.TableCell,{children:"Created on"})]}),e.jsxs(l.TableBody,{children:[r&&r.map(t=>{const m=t.roles,I=t.created_on?re.format(t.created_on,U,{locale:C}):"";return e.jsxs(l.TableRow,{onClick:()=>{s(t)},children:[e.jsx(l.TableCell,{className:"w-10",children:e.jsx(l.Tooltip,{title:"Delete this user",children:e.jsx(l.IconButton,{size:"small",onClick:w=>(w.stopPropagation(),h(t)),children:e.jsx(l.DeleteIcon,{})})})}),e.jsx(l.TableCell,{children:t.uid}),e.jsx(l.TableCell,{children:t.email}),e.jsx(l.TableCell,{className:"font-medium align-left",children:t.displayName}),e.jsx(l.TableCell,{className:"align-left",children:m?e.jsx("div",{className:"flex flex-wrap gap-2",children:m.map(w=>e.jsx(O,{role:w},w?.id))}):null}),e.jsx(l.TableCell,{children:I})]},"row_"+t.uid)}),(!r||r.length===0)&&e.jsx(l.TableRow,{children:e.jsx(l.TableCell,{colspan:6,children:e.jsxs(l.CenteredView,{className:"flex flex-col gap-4 my-8 items-center",children:[e.jsx(l.Typography,{variant:"label",children:"There are no users yet"}),e.jsx(l.Button,{variant:"outlined",onClick:()=>{if(!n.user?.uid)throw Error("UsersTable, authController misconfiguration");o({uid:n.user?.uid,email:n.user?.email,displayName:n.user?.displayName,photoURL:n.user?.photoURL,providerId:n.user?.providerId,isAnonymous:n.user?.isAnonymous,roles:[{id:"admin",name:"Admin"}],created_on:new Date}).then(()=>{g.open({type:"success",message:"User added successfully"})}).catch(t=>{g.open({type:"error",message:"Error adding user: "+t.message})})},children:"Add the logged user as an admin"})]})})})]})]}),e.jsx(S.DeleteConfirmationDialog,{open:!!v,loading:x,onAccept:()=>{v&&(T(!0),d(v).then(()=>{h(void 0)}).catch(t=>{g.open({type:"error",message:"Error deleting user: "+t.message})}).finally(()=>{T(!1)}))},onCancel:()=>{h(void 0)},title:e.jsx(e.Fragment,{children:"Delete?"}),body:e.jsx(e.Fragment,{children:"Are you sure you want to delete this user?"})})]})}const oe=function({children:r}){const[o,d]=c.useState(),[n,g]=c.useState(),{users:u,usersLimit:C}=_(),U=C!==void 0&&u&&u.length>=C,v=c.useCallback(x=>{g(x),d(!0)},[]),h=c.useCallback(()=>{d(!1),g(void 0)},[]);return e.jsxs(l.Container,{className:"w-full flex flex-col py-4 gap-4",maxWidth:"6xl",children:[r,e.jsxs("div",{className:"flex items-center mt-12",children:[e.jsx(l.Typography,{gutterBottom:!0,variant:"h4",className:"flex-grow",component:"h4",children:"Users"}),e.jsx(l.Button,{size:"large",disabled:U,startIcon:e.jsx(l.AddIcon,{}),onClick:()=>d(!0),children:"Add user"})]}),e.jsx(le,{onUserClicked:v}),e.jsx(ee,{open:o??!1,user:n,handleClose:h},n?.uid??"new")]})};function Te({userManagement:s}){return{key:"user_management",loading:s.loading,provider:{Component:G,props:{userManagement:s}}}}const Se=[{path:"users",name:"CMS Users",group:"Admin",icon:"face",view:e.jsx(oe,{})},{path:"roles",name:"Roles",group:"Admin",icon:"gpp_good",view:e.jsx(Z,{})}];i.RESERVED_GROUPS=te,i.RoleChip=O,i.RoleYupSchema=K,i.RolesDetailsForm=Q,i.RolesTable=X,i.RolesView=Z,i.UserDetailsForm=ee,i.UserManagementContext=j,i.UserManagementProvider=G,i.UserYupSchema=R,i.UsersTable=le,i.UsersView=oe,i.areRolesEqual=H,i.cacheDelegatedLoginToken=he,i.clearDelegatedLoginTokensCache=ge,i.darkenColor=pe,i.getDelegatedLoginTokenFromCache=fe,i.getUserRoles=de,i.hexToRgbaWithOpacity=me,i.resolveUserRolePermissions=J,i.useBuildFirestoreUserManagement=be,i.useUserManagement=_,i.useUserManagementPlugin=Te,i.userManagementAdminViews=Se,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})});
|
1
|
+
(function(c,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("react"),require("firebase/firestore"),require("react/jsx-runtime"),require("@firecms/ui"),require("yup"),require("@firecms/core"),require("@firecms/formex"),require("date-fns"),require("date-fns/locale")):typeof define=="function"&&define.amd?define(["exports","react","firebase/firestore","react/jsx-runtime","@firecms/ui","yup","@firecms/core","@firecms/formex","date-fns","date-fns/locale"],i):(c=typeof globalThis<"u"?globalThis:c||self,i(c.FireCMS={},c.React,c.firestore,c.jsxRuntime,c.ui,c.Yup,c.core,c.formex,c.dateFns,c.locales))})(this,function(c,i,N,e,l,re,k,P,se,ae){"use strict";function z(n){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const o in n)if(o!=="default"){const d=Object.getOwnPropertyDescriptor(n,o);Object.defineProperty(r,o,d.get?d:{enumerable:!0,get:()=>n[o]})}}return r.default=n,Object.freeze(r)}const B=z(re),te=z(ae),ie=["Admin"],ce={read:!1,edit:!1,create:!1,delete:!1};function J({collection:n,user:r}){const o=r?.roles;if(o){if(n.ownerId===r?.uid)return{read:!0,create:!0,edit:!0,delete:!0};{const d={read:!1,create:!1,edit:!1,delete:!1};return o.map(s=>de(s,n.id)).reduce(Y,d)}}else return ce}function de(n,r){const o={read:n.isAdmin||n.defaultPermissions?.read,create:n.isAdmin||n.defaultPermissions?.create,edit:n.isAdmin||n.defaultPermissions?.edit,delete:n.isAdmin||n.defaultPermissions?.delete};return n.collectionPermissions&&n.collectionPermissions[r]?Y(n.collectionPermissions[r],o):n.defaultPermissions?Y(n.defaultPermissions,o):o}const Y=(n,r)=>({read:n.read||r.read,create:n.create||r.create,edit:n.edit||r.edit,delete:n.delete||r.delete});function he(n,r){return n?r.roles?r.roles.map(o=>n.find(d=>d.id===o.id)).filter(Boolean):[]:void 0}const H=(n,r)=>{const o=n.map(s=>s.id),d=r.map(s=>s.id);return o.length===r.length&&o.every(s=>d.includes(s))};function fe(n,r){if(!r)return;const o=pe(r),d=new Date(o.exp*1e3);localStorage.setItem(`auth_token::${n}`,JSON.stringify({token:r,expiry:d}))}function ge(n){const r=localStorage.getItem(`auth_token::${n}`);if(r){const o=JSON.parse(r);if(o.expiry=new Date(o.expiry),o.expiry>new Date)return o.token}}function Ce(){for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);r?.startsWith("auth_token::")&&localStorage.removeItem(r)}}function pe(n){if(!n)throw new Error("No JWT token");const o=n.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),d=decodeURIComponent(window.atob(o).split("").map(function(s){return"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(d)}function me(n,r=10){if(!/^#([0-9A-Fa-f]{3}){1,2}$/.test(n))throw new Error("Invalid color format");let o=n.substring(1).split("");o.length===3&&(o=[o[0],o[0],o[1],o[1],o[2],o[2]]);let d=parseInt(o[0]+o[1],16),s=parseInt(o[2]+o[3],16),C=parseInt(o[4]+o[5],16);return d=Math.floor(d*(1-r/100)),s=Math.floor(s*(1-r/100)),C=Math.floor(C*(1-r/100)),"#"+(d<16?"0":"")+d.toString(16)+(s<16?"0":"")+s.toString(16)+(C<16?"0":"")+C.toString(16)}function ue(n,r=10){if(!/^#([0-9A-Fa-f]{3}){1,2}$/.test(n))throw new Error("Invalid color format");let o=n.substring(1).split("");o.length===3&&(o=[o[0],o[0],o[1],o[1],o[2],o[2]]);const d=parseInt(o[0]+o[1],16),s=parseInt(o[2]+o[3],16),C=parseInt(o[4]+o[5],16),w=r/100;return`rgba(${d}, ${s}, ${C}, ${w})`}function be({firebaseApp:n,usersPath:r="__FIRECMS/config/users",rolesPath:o="__FIRECMS/config/roles",usersLimit:d,canEditRoles:s=!0,allowDefaultRolesCreation:C,includeCollectionConfigPermissions:w}){const p=i.useRef(),[U,y]=i.useState(!0),[h,x]=i.useState(!0),[T,t]=i.useState([]),[b,I]=i.useState([]),u=b.map(g=>({...g,roles:T.filter(v=>g.roles?.includes(v.id))})),[q,_]=i.useState(),[m,f]=i.useState(),S=U||h;i.useEffect(()=>{n&&(p.current=N.getFirestore(n))},[n]),i.useEffect(()=>{if(!n||!o)return;const g=N.getFirestore(n);return N.onSnapshot(N.collection(g,o),{next:v=>{_(void 0);try{const D=we(v.docs);t(D)}catch(D){_(D)}y(!1)},error:v=>{_(v),y(!1)}})},[n,o]),i.useEffect(()=>{if(!n||!r)return;const g=N.getFirestore(n);return N.onSnapshot(N.collection(g,r),{next:v=>{f(void 0);try{const D=ve(v.docs);I(D)}catch(D){f(D)}x(!1)},error:v=>{f(v),x(!1)}})},[n,r]);const F=i.useCallback(async g=>{const v=p.current;if(!v||!r)throw Error("useFirestoreConfigurationPersistence Firestore not initialised");console.debug("Persisting user",g);const D=g.roles?.map(Ue=>Ue.id),{uid:O,...W}=g,ne={...W,roles:D};return O?N.setDoc(N.doc(v,r,O),ne,{merge:!0}).then(()=>g):N.addDoc(N.collection(v,r),ne).then(()=>g)},[r]),A=i.useCallback(g=>{const v=p.current;if(!v||!o)throw Error("useFirestoreConfigurationPersistence Firestore not initialised");console.debug("Persisting role",g);const{id:D,...O}=g,W=N.doc(v,o,D);return N.setDoc(W,O,{merge:!0})},[o]),a=i.useCallback(async g=>{const v=p.current;if(!v||!r)throw Error("useFirestoreConfigurationPersistence Firestore not initialised");console.debug("Deleting",g);const{uid:D}=g;return N.deleteDoc(N.doc(v,r,D))},[r]),E=i.useCallback(g=>{const v=p.current;if(!v||!o)throw Error("useFirestoreConfigurationPersistence Firestore not initialised");console.debug("Deleting",g);const{id:D}=g,O=N.doc(v,o,D);return N.deleteDoc(O)},[o]),V=i.useCallback(({collection:g,user:v})=>J({collection:g,user:v}),[]),M=u.map(g=>g.uid),ke=i.useCallback(g=>{if(!u)throw Error("Users not loaded");return u.find(D=>D.email?.toLowerCase()===g?.email?.toLowerCase())?.roles},[M]),Ne=i.useCallback(({user:g})=>{if(console.log("Authenticating user",g),S)return console.log("User management is still loading"),!1;if(u.length===0||u.find(D=>D.email?.toLowerCase()===g?.email?.toLowerCase()))return!0;throw Error("Could not find a user with the provided email")},[S,u]);return{loading:S,roles:T,users:u,saveUser:F,saveRole:A,deleteUser:a,deleteRole:E,usersLimit:d,canEditRoles:s===void 0?!0:s,allowDefaultRolesCreation:C===void 0?!0:C,includeCollectionConfigPermissions:!!w,collectionPermissions:V,defineRolesFor:ke,authenticator:Ne}}const ve=n=>n.map(r=>{const o=r.data();return{uid:r.id,...o,created_on:o?.created_on?.toDate(),updated_on:o?.updated_on?.toDate()}}),we=n=>n.map(r=>({id:r.id,...r.data()})),j=i.createContext({});function G({children:n,userManagement:r}){return e.jsx(j.Provider,{value:r,children:n})}const L=()=>i.useContext(j);function $({role:n}){let r;return n.isAdmin?r="blueDarker":n.id==="editor"?r="yellowLight":n.id==="viewer"?r="grayLight":r=l.getColorSchemeForSeed(n.id),e.jsx(l.Chip,{colorScheme:r,children:n.name},n.id)}const K=B.object().shape({id:B.string().required("Required"),name:B.string().required("Required")});function Q({open:n,role:r,editable:o,handleClose:d,collections:s}){const{saveRole:C}=L(),w=!r,[p,U]=i.useState(),y=i.useCallback(a=>(U(void 0),C(a)),[C]),h=P.useCreateFormex({initialValues:r??{name:""},onSubmit:(a,E)=>y(a).then(()=>{E.resetForm({values:a}),d()}).catch(V=>U(V)),validation:a=>K.validate(a,{abortEarly:!1}).then(()=>({})).catch(E=>{const V={};return E.inner.forEach(M=>{V[M.path]=M.message}),V})}),{isSubmitting:x,touched:T,values:t,errors:b,handleChange:I,setFieldValue:u,dirty:q,setFieldTouched:_}=h,m=t.isAdmin??!1,f=t.defaultPermissions?.create??!1,S=t.defaultPermissions?.read??!1,F=t.defaultPermissions?.edit??!1,A=t.defaultPermissions?.delete??!1;return i.useEffect(()=>{!P.getIn(T,"id")&&t.name&&u("id",k.toSnakeCase(t.name))},[T,t.name]),e.jsx(l.Dialog,{open:n,maxWidth:"4xl",children:e.jsx(P.Formex,{value:h,children:e.jsxs("form",{noValidate:!0,autoComplete:"off",onSubmit:h.handleSubmit,style:{display:"flex",flexDirection:"column",position:"relative",height:"100%"},children:[e.jsxs(l.DialogContent,{className:"flex-grow",children:[e.jsx("div",{className:"flex flex-row pt-12 pb-8",children:e.jsx(l.Typography,{variant:"h4",className:"flex-grow",children:"Role"})}),e.jsxs("div",{className:"grid grid-cols-12 gap-8",children:[e.jsxs("div",{className:"col-span-12 md:col-span-8",children:[e.jsx(l.TextField,{name:"name",required:!0,error:T.name&&!!b.name,value:t.name,disabled:m||!o,onChange:I,"aria-describedby":"name-helper-text",label:"Name"}),e.jsx(k.FieldCaption,{children:T.name&&b.name?b.name:"Name of this role"})]}),e.jsxs("div",{className:"col-span-12 md:col-span-4",children:[e.jsx(l.TextField,{name:"id",required:!0,error:T.id&&!!b.id,value:t.id,disabled:!w||!o,onChange:a=>{I(a),_("id",!0)},"aria-describedby":"id-helper-text",label:"ID"}),e.jsx(k.FieldCaption,{children:T.id&&b.id?b.id:"ID of this role"})]}),e.jsxs("div",{className:"col-span-12",children:[e.jsx(l.Paper,{className:"bg-inherit",children:e.jsxs(l.Table,{children:[e.jsxs(l.TableHeader,{children:[e.jsx(l.TableCell,{}),e.jsx(l.TableCell,{align:"center",children:"Create entities"}),e.jsx(l.TableCell,{align:"center",children:"Read entities"}),e.jsx(l.TableCell,{align:"center",children:"Update entities"}),e.jsx(l.TableCell,{align:"center",children:"Delete entities"})]}),e.jsxs(l.TableBody,{children:[e.jsxs(l.TableRow,{children:[e.jsx(l.TableCell,{scope:"row",children:e.jsx("strong",{children:"All collections"})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Tooltip,{title:"Create entities in collections",children:e.jsx(l.Checkbox,{disabled:m||!o,checked:(m||f)??!1,onCheckedChange:a=>u("defaultPermissions.create",a)})})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Tooltip,{title:"Access all data in every collection",children:e.jsx(l.Checkbox,{disabled:m||!o,checked:(m||S)??!1,onCheckedChange:a=>u("defaultPermissions.read",a)})})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Tooltip,{title:"Update data in any collection",children:e.jsx(l.Checkbox,{disabled:m||!o,checked:(m||F)??!1,onCheckedChange:a=>u("defaultPermissions.edit",a)})})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Tooltip,{title:"Delete data in any collection",children:e.jsx(l.Checkbox,{disabled:m||!o,checked:(m||A)??!1,onCheckedChange:a=>u("defaultPermissions.delete",a)})})})]}),s&&s.map(a=>e.jsxs(l.TableRow,{children:[e.jsx(l.TableCell,{scope:"row",children:a.name}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:m||f||!o,checked:(m||f||P.getIn(t,`collectionPermissions.${a.path}.create`))??!1,onCheckedChange:E=>u(`collectionPermissions.${a.path}.create`,E)})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:m||S||!o,checked:(m||S||P.getIn(t,`collectionPermissions.${a.path}.read`))??!1,onCheckedChange:E=>u(`collectionPermissions.${a.path}.read`,E)})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:m||F||!o,checked:(m||F||P.getIn(t,`collectionPermissions.${a.path}.edit`))??!1,onCheckedChange:E=>u(`collectionPermissions.${a.path}.edit`,E)})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:m||A||!o,checked:(m||A||P.getIn(t,`collectionPermissions.${a.path}.delete`))??!1,onCheckedChange:E=>u(`collectionPermissions.${a.path}.delete`,E)})})]},a.name))]})]})}),e.jsx(k.FieldCaption,{children:"You can customise the permissions that the users related to this role can perform in the entities of each collection"})]}),e.jsxs("div",{className:"col-span-12 md:col-span-4",children:[e.jsxs(l.Select,{error:T.config&&!!b.config,id:"createCollections",name:"createCollections",label:"Create collections",position:"item-aligned",disabled:m||!o,onChange:a=>u("config.createCollections",a.target.value==="true"),value:m||t.config?.createCollections?"true":"false",renderValue:a=>a==="true"?"Yes":"No",children:[e.jsx(l.SelectItem,{value:"true",children:" Yes "}),e.jsx(l.SelectItem,{value:"false",children:" No "})]}),e.jsx(k.FieldCaption,{children:T.config&&b.config?b.config:"Can the user create collections"})]}),e.jsxs("div",{className:"col-span-12 md:col-span-4",children:[e.jsxs(l.Select,{error:T.config&&!!b.config,id:"editCollections",name:"editCollections",label:"Edit collections",disabled:m||!o,position:"item-aligned",onChange:a=>u("config.editCollections",a.target.value==="own"?"own":a.target.value==="true"),value:m?"true":t.config?.editCollections==="own"?"own":t.config?.editCollections?"true":"false",renderValue:a=>a==="own"?"Own":a==="true"?"Yes":"No",children:[e.jsx(l.SelectItem,{value:"true",children:" Yes "}),e.jsx(l.SelectItem,{value:"false",children:" No "}),e.jsx(l.SelectItem,{value:"own",children:" Only his/her own "})]}),e.jsx(k.FieldCaption,{children:T.config&&b.config?b.config:"Can the user edit collections"})]}),e.jsxs("div",{className:"col-span-12 md:col-span-4",children:[e.jsxs(l.Select,{error:T.config&&!!b.config,id:"deleteCollections",name:"deleteCollections",label:"Delete collections",disabled:m||!o,position:"item-aligned",onChange:a=>u("config.deleteCollections",a.target.value==="own"?"own":a.target.value==="true"),value:m?"true":t.config?.deleteCollections==="own"?"own":t.config?.deleteCollections?"true":"false",renderValue:a=>a==="own"?"Own":a==="true"?"Yes":"No",children:[e.jsx(l.SelectItem,{value:"true",children:" Yes "}),e.jsx(l.SelectItem,{value:"false",children:" No "}),e.jsx(l.SelectItem,{value:"own",children:" Only his/her own "})]}),e.jsx(k.FieldCaption,{children:T.config&&b.config?b.config:"Can the user delete collections"})]})]})]}),e.jsxs(l.DialogActions,{position:"sticky",children:[p&&e.jsx(l.Typography,{className:"text-red-500",children:"There was an error saving this role"}),e.jsx(l.Button,{variant:"text",onClick:()=>{d()},children:"Cancel"}),e.jsx(l.LoadingButton,{variant:"filled",color:"primary",type:"submit",disabled:!q,loading:x,startIcon:e.jsx(l.DoneIcon,{}),children:w?"Create role":"Update"})]})]})})})}const ye=[{id:"admin",name:"Admin",isAdmin:!0},{id:"editor",name:"Editor",isAdmin:!1,defaultPermissions:{read:!0,create:!0,edit:!0,delete:!0},config:{createCollections:!0,editCollections:"own",deleteCollections:"own"}},{id:"viewer",name:"Viewer",isAdmin:!1,defaultPermissions:{read:!0,create:!1,edit:!1,delete:!1}}];function X({onRoleClicked:n,editable:r}){const{roles:o,saveRole:d,deleteRole:s,allowDefaultRolesCreation:C}=L(),[w,p]=i.useState(void 0),[U,y]=i.useState(!1);return e.jsxs("div",{className:"w-full overflow-auto",children:[e.jsxs(l.Table,{children:[e.jsxs(l.TableHeader,{children:[e.jsx(l.TableCell,{header:!0,className:"w-16"}),e.jsx(l.TableCell,{header:!0,children:"Role"}),e.jsx(l.TableCell,{header:!0,className:"items-center",children:"Is Admin"}),e.jsx(l.TableCell,{header:!0,children:"Default permissions"})]}),e.jsxs(l.TableBody,{children:[o&&o.map(h=>{const x=h.isAdmin||h.defaultPermissions?.create,T=h.isAdmin||h.defaultPermissions?.read,t=h.isAdmin||h.defaultPermissions?.edit,b=h.isAdmin||h.defaultPermissions?.delete;return e.jsxs(l.TableRow,{onClick:()=>{n(h)},children:[e.jsx(l.TableCell,{style:{width:"64px"},children:!h.isAdmin&&e.jsx(l.Tooltip,{title:"Delete this role",children:e.jsx(l.IconButton,{size:"small",disabled:!r,onClick:I=>(I.stopPropagation(),p(h)),children:e.jsx(l.DeleteIcon,{})})})}),e.jsx(l.TableCell,{children:e.jsx($,{role:h})}),e.jsx(l.TableCell,{className:"items-center",children:e.jsx(l.Checkbox,{checked:h.isAdmin??!1})}),e.jsx(l.TableCell,{children:e.jsxs("ul",{children:[x&&e.jsx("li",{children:"Create"}),T&&e.jsx("li",{children:"Read"}),t&&e.jsx("li",{children:"Update"}),b&&e.jsx("li",{children:"Delete"})]})})]},h.name)}),(!o||o.length===0)&&e.jsx(l.TableRow,{children:e.jsx(l.TableCell,{colspan:4,children:e.jsxs(l.CenteredView,{className:"flex flex-col gap-4 my-8 items-center",children:[e.jsx(l.Typography,{variant:"label",children:"You don't have any roles yet."}),C&&e.jsx(l.Button,{variant:"outlined",onClick:()=>{ye.forEach(h=>{d(h)})},children:"Create default roles"})]})})})]})]}),e.jsx(k.DeleteConfirmationDialog,{open:!!w,loading:U,onAccept:()=>{w&&(y(!0),s(w).then(()=>{p(void 0)}).finally(()=>{y(!1)}))},onCancel:()=>{p(void 0)},title:e.jsx(e.Fragment,{children:"Delete?"}),body:e.jsx(e.Fragment,{children:"Are you sure you want to delete this role?"})})]})}const Z=i.memo(function({children:r}){const{collections:o}=k.useNavigationController(),[d,s]=i.useState(!1),[C,w]=i.useState(),{canEditRoles:p}=L(),U=i.useCallback(h=>{s(!0),w(h)},[]),y=()=>{w(void 0),s(!1)};return e.jsxs(l.Container,{className:"w-full flex flex-col py-4 gap-4",maxWidth:"6xl",children:[r,e.jsxs("div",{className:"flex items-center mt-12",children:[e.jsx(l.Typography,{gutterBottom:!0,variant:"h4",className:"flex-grow",component:"h4",children:"Roles"}),e.jsx(l.Tooltip,{title:p?void 0:"Update plans to customise roles",children:e.jsx(l.Button,{size:"large",disabled:!p,startIcon:e.jsx(l.AddIcon,{}),onClick:()=>s(!0),children:"Add role"})})]}),e.jsx(X,{onRoleClicked:U,editable:!!p}),e.jsx(Q,{open:d,role:C,editable:p,collections:o,handleClose:y},C?.id??"new")]})}),R=B.object().shape({displayName:B.string().required("Required"),email:B.string().email().required("Required"),roles:B.array().min(1)});function Te(n,r,o,d,s){const C=o.filter(y=>y.roles?.map(h=>h.id).includes("admin")),w=n.roles?.map(y=>y.id).includes("admin");if((!s||!H(s.roles??[],r.roles??[]))&&!w)throw new Error("Only admins can change roles");if(s&&s.roles?.map(y=>y.id).includes("admin")&&!r.roles?.map(y=>y.id).includes("admin")&&C.length===1)throw new Error("There must be at least one admin");return!0}function ee({open:n,user:r,handleClose:o}){const d=k.useSnackbarController(),{user:s}=k.useAuthController(),{saveUser:C,users:w,roles:p}=L(),U=!r,y=i.useCallback(f=>{if(!s)throw new Error("Logged user not found");try{return Te(s,f,w,p,r),C(f)}catch(S){return Promise.reject(S)}},[p,C,r,w,s]),h=P.useCreateFormex({initialValues:r??{displayName:"",email:"",roles:p.filter(f=>f.id==="editor")},validation:f=>R.validate(f,{abortEarly:!1}).then(()=>({})).catch(S=>S.inner.reduce((F,A)=>(F[A.path]=A.message,F),{})),onSubmit:(f,S)=>y(f).then(()=>{o(),S.resetForm({values:f})}).catch(F=>{d.open({type:"error",message:F.message})})}),{isSubmitting:x,touched:T,handleChange:t,values:b,errors:I,setFieldValue:u,dirty:q,handleSubmit:_,submitCount:m}=h;return e.jsx(l.Dialog,{open:n,onOpenChange:f=>f?void 0:o(),maxWidth:"4xl",children:e.jsx(P.Formex,{value:h,children:e.jsxs("form",{onSubmit:_,autoComplete:"off",noValidate:!0,style:{display:"flex",flexDirection:"column",position:"relative",height:"100%"},children:[e.jsxs(l.DialogContent,{className:"h-full flex-grow",children:[e.jsx("div",{className:"flex flex-row pt-4 pb-4",children:e.jsx(l.Typography,{variant:"h4",className:"flex-grow",children:"User"})}),e.jsxs("div",{className:"grid grid-cols-12 gap-8",children:[e.jsxs("div",{className:"col-span-12",children:[e.jsx(l.TextField,{name:"displayName",required:!0,error:m>0&&!!I.displayName,value:b.displayName??"",onChange:t,"aria-describedby":"name-helper-text",label:"Name"}),e.jsx(k.FieldCaption,{children:m>0&&I.displayName?I.displayName:"Name of this user"})]}),e.jsxs("div",{className:"col-span-12",children:[e.jsx(l.TextField,{required:!0,error:m>0&&!!I.email,name:"email",value:b.email??"",onChange:t,"aria-describedby":"email-helper-text",label:"Email"}),e.jsx(k.FieldCaption,{children:m>0&&I.email?I.email:"Email of this user"})]}),e.jsx("div",{className:"col-span-12",children:e.jsx(l.MultiSelect,{label:"Roles",value:b.roles?.map(f=>f.id)??[],onMultiValueChange:f=>u("roles",f.map(S=>p.find(F=>F.id===S))),renderValue:f=>{const S=p.find(F=>F.id===f);return S?e.jsx("div",{className:"flex flex-wrap space-x-2 space-y-2",children:e.jsx($,{role:S},S?.id)}):null},children:p.map(f=>e.jsx(l.MultiSelectItem,{value:f.id,children:e.jsx($,{role:f},f?.id)},f.id))})})]})]}),e.jsxs(l.DialogActions,{children:[e.jsx(l.Button,{variant:"text",onClick:()=>{o()},children:"Cancel"}),e.jsx(l.LoadingButton,{variant:"filled",color:"primary",type:"submit",disabled:!q,loading:x,startIcon:e.jsx(l.DoneIcon,{}),children:U?"Create user":"Update"})]})]})})})}function le({onUserClicked:n}){const{users:r,saveUser:o,deleteUser:d}=L(),s=k.useAuthController(),C=k.useSnackbarController(),w=k.useCustomizationController(),p=w?.locale?te[w?.locale]:void 0,U=w?.dateTimeFormat??k.defaultDateFormat,[y,h]=i.useState(void 0),[x,T]=i.useState(!1);return e.jsxs("div",{className:"overflow-auto",children:[e.jsxs(l.Table,{children:[e.jsxs(l.TableHeader,{children:[e.jsx(l.TableCell,{className:"truncate w-16"}),e.jsx(l.TableCell,{children:"ID"}),e.jsx(l.TableCell,{children:"Email"}),e.jsx(l.TableCell,{children:"Name"}),e.jsx(l.TableCell,{children:"Roles"}),e.jsx(l.TableCell,{children:"Created on"})]}),e.jsxs(l.TableBody,{children:[r&&r.map(t=>{const b=t.roles,I=t.created_on?se.format(t.created_on,U,{locale:p}):"";return e.jsxs(l.TableRow,{onClick:()=>{n(t)},children:[e.jsx(l.TableCell,{className:"w-10",children:e.jsx(l.Tooltip,{title:"Delete this user",children:e.jsx(l.IconButton,{size:"small",onClick:u=>(u.stopPropagation(),h(t)),children:e.jsx(l.DeleteIcon,{})})})}),e.jsx(l.TableCell,{children:t.uid}),e.jsx(l.TableCell,{children:t.email}),e.jsx(l.TableCell,{className:"font-medium align-left",children:t.displayName}),e.jsx(l.TableCell,{className:"align-left",children:b?e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(u=>e.jsx($,{role:u},u?.id))}):null}),e.jsx(l.TableCell,{children:I})]},"row_"+t.uid)}),(!r||r.length===0)&&e.jsx(l.TableRow,{children:e.jsx(l.TableCell,{colspan:6,children:e.jsxs(l.CenteredView,{className:"flex flex-col gap-4 my-8 items-center",children:[e.jsx(l.Typography,{variant:"label",children:"There are no users yet"}),e.jsx(l.Button,{variant:"outlined",onClick:()=>{if(!s.user?.uid)throw Error("UsersTable, authController misconfiguration");o({uid:s.user?.uid,email:s.user?.email,displayName:s.user?.displayName,photoURL:s.user?.photoURL,providerId:s.user?.providerId,isAnonymous:s.user?.isAnonymous,roles:[{id:"admin",name:"Admin"}],created_on:new Date}).then(()=>{C.open({type:"success",message:"User added successfully"})}).catch(t=>{C.open({type:"error",message:"Error adding user: "+t.message})})},children:"Add the logged user as an admin"})]})})})]})]}),e.jsx(k.DeleteConfirmationDialog,{open:!!y,loading:x,onAccept:()=>{y&&(T(!0),d(y).then(()=>{h(void 0)}).catch(t=>{C.open({type:"error",message:"Error deleting user: "+t.message})}).finally(()=>{T(!1)}))},onCancel:()=>{h(void 0)},title:e.jsx(e.Fragment,{children:"Delete?"}),body:e.jsx(e.Fragment,{children:"Are you sure you want to delete this user?"})})]})}const oe=function({children:r}){const[o,d]=i.useState(),[s,C]=i.useState(),{users:w,usersLimit:p}=L(),U=p!==void 0&&w&&w.length>=p,y=i.useCallback(x=>{C(x),d(!0)},[]),h=i.useCallback(()=>{d(!1),C(void 0)},[]);return e.jsxs(l.Container,{className:"w-full flex flex-col py-4 gap-4",maxWidth:"6xl",children:[r,e.jsxs("div",{className:"flex items-center mt-12",children:[e.jsx(l.Typography,{gutterBottom:!0,variant:"h4",className:"flex-grow",component:"h4",children:"Users"}),e.jsx(l.Button,{size:"large",disabled:U,startIcon:e.jsx(l.AddIcon,{}),onClick:()=>d(!0),children:"Add user"})]}),e.jsx(le,{onUserClicked:y}),e.jsx(ee,{open:o??!1,user:s,handleClose:h},s?.uid??"new")]})};function Se({userManagement:n}){return{key:"user_management",loading:n.loading,provider:{Component:G,props:{userManagement:n}}}}const De=[{path:"users",name:"CMS Users",group:"Admin",icon:"face",view:e.jsx(oe,{})},{path:"roles",name:"Roles",group:"Admin",icon:"gpp_good",view:e.jsx(Z,{})}];c.RESERVED_GROUPS=ie,c.RoleChip=$,c.RoleYupSchema=K,c.RolesDetailsForm=Q,c.RolesTable=X,c.RolesView=Z,c.UserDetailsForm=ee,c.UserManagementContext=j,c.UserManagementProvider=G,c.UserYupSchema=R,c.UsersTable=le,c.UsersView=oe,c.areRolesEqual=H,c.cacheDelegatedLoginToken=fe,c.clearDelegatedLoginTokensCache=Ce,c.darkenColor=me,c.getDelegatedLoginTokenFromCache=ge,c.getUserRoles=he,c.hexToRgbaWithOpacity=ue,c.resolveUserRolePermissions=J,c.useBuildFirestoreUserManagement=be,c.useUserManagement=L,c.useUserManagementPlugin=Se,c.userManagementAdminViews=De,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
|
2
2
|
//# sourceMappingURL=index.umd.js.map
|