@firecms/user_management 3.0.0-canary.80 → 3.0.0-canary.82
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/LICENSE +3 -2
- package/dist/index.es.js +962 -774
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +1539 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +5 -5
package/dist/index.umd.js
CHANGED
@@ -1,2 +1,1540 @@
|
|
1
|
-
(function(d,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):(d=typeof globalThis<"u"?globalThis:d||self,c(d.FireCMS={},d.React,d.firestore,d.jsxRuntime,d.ui,d.Yup,d.core,d.formex,d.dateFns,d.locales))})(this,function(d,c,U,e,l,ae,k,P,te,ie){"use strict";function z(o){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const r in o)if(r!=="default"){const a=Object.getOwnPropertyDescriptor(o,r);Object.defineProperty(s,r,a.get?a:{enumerable:!0,get:()=>o[r]})}}return s.default=o,Object.freeze(s)}const B=z(ae),de=z(ie),ce=["Admin"],he={read:!1,edit:!1,create:!1,delete:!1};function J({collection:o,user:s}){const r=s?.roles;if(r){if(o.ownerId===s?.uid)return{read:!0,create:!0,edit:!0,delete:!0};{const a={read:!1,create:!1,edit:!1,delete:!1};return r.map(n=>ge(n,o.id)).reduce(Y,a)}}else return he}function ge(o,s){const r={read:o.isAdmin||o.defaultPermissions?.read,create:o.isAdmin||o.defaultPermissions?.create,edit:o.isAdmin||o.defaultPermissions?.edit,delete:o.isAdmin||o.defaultPermissions?.delete};return o.collectionPermissions&&o.collectionPermissions[s]?Y(o.collectionPermissions[s],r):o.defaultPermissions?Y(o.defaultPermissions,r):r}const Y=(o,s)=>({read:o.read||s.read,create:o.create||s.create,edit:o.edit||s.edit,delete:o.delete||s.delete});function fe(o,s){return o?s.roles?s.roles.map(r=>o.find(a=>a.id===r.id)).filter(Boolean):[]:void 0}const H=(o,s)=>{const r=o.map(n=>n.id),a=s.map(n=>n.id);return r.length===s.length&&r.every(n=>a.includes(n))};function me(o,s){if(!s)return;const r=ue(s),a=new Date(r.exp*1e3);localStorage.setItem(`auth_token::${o}`,JSON.stringify({token:s,expiry:a}))}function Ce(o){const s=localStorage.getItem(`auth_token::${o}`);if(s){const r=JSON.parse(s);if(r.expiry=new Date(r.expiry),r.expiry>new Date)return r.token}}function pe(){for(let o=0;o<localStorage.length;o++){const s=localStorage.key(o);s?.startsWith("auth_token::")&&localStorage.removeItem(s)}}function ue(o){if(!o)throw new Error("No JWT token");const r=o.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),a=decodeURIComponent(window.atob(r).split("").map(function(n){return"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(a)}function be(o,s=10){if(!/^#([0-9A-Fa-f]{3}){1,2}$/.test(o))throw new Error("Invalid color format");let r=o.substring(1).split("");r.length===3&&(r=[r[0],r[0],r[1],r[1],r[2],r[2]]);let a=parseInt(r[0]+r[1],16),n=parseInt(r[2]+r[3],16),f=parseInt(r[4]+r[5],16);return a=Math.floor(a*(1-s/100)),n=Math.floor(n*(1-s/100)),f=Math.floor(f*(1-s/100)),"#"+(a<16?"0":"")+a.toString(16)+(n<16?"0":"")+n.toString(16)+(f<16?"0":"")+f.toString(16)}function ve(o,s=10){if(!/^#([0-9A-Fa-f]{3}){1,2}$/.test(o))throw new Error("Invalid color format");let r=o.substring(1).split("");r.length===3&&(r=[r[0],r[0],r[1],r[1],r[2],r[2]]);const a=parseInt(r[0]+r[1],16),n=parseInt(r[2]+r[3],16),f=parseInt(r[4]+r[5],16),p=s/100;return`rgba(${a}, ${n}, ${f}, ${p})`}function ye({firebaseApp:o,usersPath:s="__FIRECMS/config/users",rolesPath:r="__FIRECMS/config/roles",usersLimit:a,canEditRoles:n=!0,allowDefaultRolesCreation:f,includeCollectionConfigPermissions:p}){const[v,F]=c.useState(!0),[y,h]=c.useState(!0),[E,D]=c.useState([]),[i,b]=c.useState([]),w=i.map(C=>({...C,roles:E.filter(u=>C.roles?.includes(u.id))})),[T,_]=c.useState(),[$,g]=c.useState(),m=v||y;c.useEffect(()=>{if(!o||!r)return;const C=U.getFirestore(o);return U.onSnapshot(U.collection(C,r),{next:u=>{_(void 0);try{const S=Te(u.docs);D(S)}catch(S){console.error("Error loading roles",S),_(S)}F(!1)},error:u=>{console.error("Error loading roles",u),_(u),F(!1)}})},[o,r]),c.useEffect(()=>{if(!o||!s)return;const C=U.getFirestore(o);return U.onSnapshot(U.collection(C,s),{next:u=>{g(void 0);try{const S=we(u.docs);b(S)}catch(S){console.error("Error loading users",S),g(S)}h(!1)},error:u=>{console.error("Error loading users",u),g(u),h(!1)}})},[o,s]);const N=c.useCallback(async C=>{if(!o)throw Error("useFirestoreUserManagement Firebase not initialised");const u=U.getFirestore(o);if(!u||!s)throw Error("useFirestoreUserManagement Firestore not initialised");console.debug("Persisting user",C);const S=C.roles?.map(Ne=>Ne.id),{uid:V,...j}=C,ne={...j,roles:S};return V?U.setDoc(U.doc(u,s,V),ne,{merge:!0}).then(()=>C):U.addDoc(U.collection(u,s),ne).then(()=>C)},[s,o]),I=c.useCallback(C=>{if(!o)throw Error("useFirestoreUserManagement Firebase not initialised");const u=U.getFirestore(o);if(!u||!r)throw Error("useFirestoreUserManagement Firestore not initialised");console.debug("Persisting role",C);const{id:S,...V}=C,j=U.doc(u,r,S);return U.setDoc(j,V,{merge:!0})},[r,o]),A=c.useCallback(async C=>{if(!o)throw Error("useFirestoreUserManagement Firebase not initialised");const u=U.getFirestore(o);if(!u||!s)throw Error("useFirestoreUserManagement Firestore not initialised");console.debug("Deleting",C);const{uid:S}=C;return U.deleteDoc(U.doc(u,s,S))},[s,o]),t=c.useCallback(C=>{if(!o)throw Error("useFirestoreUserManagement Firebase not initialised");const u=U.getFirestore(o);if(!u||!r)throw Error("useFirestoreUserManagement Firestore not initialised");console.debug("Deleting",C);const{id:S}=C,V=U.doc(u,r,S);return U.deleteDoc(V)},[r,o]),x=c.useCallback(({collection:C,user:u})=>J({collection:C,user:u}),[]),M=c.useCallback(C=>{if(!w)throw Error("Users not loaded");return w.find(S=>S.email?.toLowerCase()===C?.email?.toLowerCase())?.roles},[w]),q=c.useCallback(({user:C})=>{if(console.debug("Authenticating user",C),m)return console.warn("User management is still loading"),!1;if(w.length===0||w.find(S=>S.email?.toLowerCase()===C?.email?.toLowerCase()))return!0;throw Error("Could not find a user with the provided email in the user management system.")},[m,w]),De=E.some(C=>C.id==="admin");return{loading:m,roles:E,users:w,saveUser:N,saveRole:I,rolesError:T,deleteUser:A,deleteRole:t,usersLimit:a,usersError:$,isAdmin:De,canEditRoles:n===void 0?!0:n,allowDefaultRolesCreation:f===void 0?!0:f,includeCollectionConfigPermissions:!!p,collectionPermissions:x,defineRolesFor:M,authenticator:q}}const we=o=>o.map(s=>{const r=s.data();return{uid:s.id,...r,created_on:r?.created_on?.toDate(),updated_on:r?.updated_on?.toDate()}}),Te=o=>o.map(s=>({id:s.id,...s.data()})),W=c.createContext({});function G({children:o,userManagement:s}){return e.jsx(W.Provider,{value:s,children:o})}const L=()=>c.useContext(W);function O({role:o}){let s;return o.isAdmin?s="blueDarker":o.id==="editor"?s="yellowLight":o.id==="viewer"?s="grayLight":s=l.getColorSchemeForSeed(o.id),e.jsx(l.Chip,{colorScheme:s,children:o.name},o.id)}const K=B.object().shape({id:B.string().required("Required"),name:B.string().required("Required")});function Q({open:o,role:s,editable:r,handleClose:a,collections:n}){const{saveRole:f}=L(),p=!s,[v,F]=c.useState(),y=c.useCallback(t=>(F(void 0),f(t)),[f]),h=P.useCreateFormex({initialValues:s??{name:""},onSubmit:(t,x)=>y(t).then(()=>{x.resetForm({values:t}),a()}).catch(M=>F(M)),validation:t=>K.validate(t,{abortEarly:!1}).then(()=>({})).catch(x=>{const M={};return x.inner.forEach(q=>{M[q.path]=q.message}),M})}),{isSubmitting:E,touched:D,values:i,errors:b,handleChange:w,setFieldValue:T,dirty:_,setFieldTouched:$}=h,g=i.isAdmin??!1,m=i.defaultPermissions?.create??!1,N=i.defaultPermissions?.read??!1,I=i.defaultPermissions?.edit??!1,A=i.defaultPermissions?.delete??!1;return c.useEffect(()=>{!P.getIn(D,"id")&&i.name&&T("id",k.toSnakeCase(i.name))},[D,i.name]),e.jsx(l.Dialog,{open:o,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:D.name&&!!b.name,value:i.name,disabled:g||!r,onChange:w,"aria-describedby":"name-helper-text",label:"Name"}),e.jsx(k.FieldCaption,{children:D.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:D.id&&!!b.id,value:i.id,disabled:!p||!r,onChange:t=>{w(t),$("id",!0)},"aria-describedby":"id-helper-text",label:"ID"}),e.jsx(k.FieldCaption,{children:D.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:g||!r,checked:(g||m)??!1,onCheckedChange:t=>T("defaultPermissions.create",t)})})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Tooltip,{title:"Access all data in every collection",children:e.jsx(l.Checkbox,{disabled:g||!r,checked:(g||N)??!1,onCheckedChange:t=>T("defaultPermissions.read",t)})})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Tooltip,{title:"Update data in any collection",children:e.jsx(l.Checkbox,{disabled:g||!r,checked:(g||I)??!1,onCheckedChange:t=>T("defaultPermissions.edit",t)})})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Tooltip,{title:"Delete data in any collection",children:e.jsx(l.Checkbox,{disabled:g||!r,checked:(g||A)??!1,onCheckedChange:t=>T("defaultPermissions.delete",t)})})})]}),n&&n.map(t=>e.jsxs(l.TableRow,{children:[e.jsx(l.TableCell,{scope:"row",children:t.name}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:g||m||!r,checked:(g||m||P.getIn(i,`collectionPermissions.${t.path}.create`))??!1,onCheckedChange:x=>T(`collectionPermissions.${t.path}.create`,x)})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:g||N||!r,checked:(g||N||P.getIn(i,`collectionPermissions.${t.path}.read`))??!1,onCheckedChange:x=>T(`collectionPermissions.${t.path}.read`,x)})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:g||I||!r,checked:(g||I||P.getIn(i,`collectionPermissions.${t.path}.edit`))??!1,onCheckedChange:x=>T(`collectionPermissions.${t.path}.edit`,x)})}),e.jsx(l.TableCell,{align:"center",children:e.jsx(l.Checkbox,{disabled:g||A||!r,checked:(g||A||P.getIn(i,`collectionPermissions.${t.path}.delete`))??!1,onCheckedChange:x=>T(`collectionPermissions.${t.path}.delete`,x)})})]},t.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:D.config&&!!b.config,id:"createCollections",name:"createCollections",label:"Create collections",position:"item-aligned",disabled:g||!r,onChange:t=>T("config.createCollections",t.target.value==="true"),value:g||i.config?.createCollections?"true":"false",renderValue:t=>t==="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:D.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:D.config&&!!b.config,id:"editCollections",name:"editCollections",label:"Edit collections",disabled:g||!r,position:"item-aligned",onChange:t=>T("config.editCollections",t.target.value==="own"?"own":t.target.value==="true"),value:g?"true":i.config?.editCollections==="own"?"own":i.config?.editCollections?"true":"false",renderValue:t=>t==="own"?"Own":t==="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:D.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:D.config&&!!b.config,id:"deleteCollections",name:"deleteCollections",label:"Delete collections",disabled:g||!r,position:"item-aligned",onChange:t=>T("config.deleteCollections",t.target.value==="own"?"own":t.target.value==="true"),value:g?"true":i.config?.deleteCollections==="own"?"own":i.config?.deleteCollections?"true":"false",renderValue:t=>t==="own"?"Own":t==="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:D.config&&b.config?b.config:"Can the user delete collections"})]})]})]}),e.jsxs(l.DialogActions,{position:"sticky",children:[v&&e.jsx(l.Typography,{className:"text-red-500",children:"There was an error saving this role"}),e.jsx(l.Button,{variant:"text",onClick:()=>{a()},children:"Cancel"}),e.jsx(l.LoadingButton,{variant:"filled",color:"primary",type:"submit",disabled:!_,loading:E,startIcon:e.jsx(l.DoneIcon,{}),children:p?"Create role":"Update"})]})]})})})}const X=[{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 Z({onRoleClicked:o,editable:s}){const{roles:r,saveRole:a,deleteRole:n,allowDefaultRolesCreation:f}=L(),[p,v]=c.useState(void 0),[F,y]=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:[r&&r.map(h=>{const E=h.isAdmin||h.defaultPermissions?.create,D=h.isAdmin||h.defaultPermissions?.read,i=h.isAdmin||h.defaultPermissions?.edit,b=h.isAdmin||h.defaultPermissions?.delete;return e.jsxs(l.TableRow,{onClick:()=>{o(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:!s,onClick:w=>(w.stopPropagation(),v(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:[E&&e.jsx("li",{children:"Create"}),D&&e.jsx("li",{children:"Read"}),i&&e.jsx("li",{children:"Update"}),b&&e.jsx("li",{children:"Delete"})]})})]},h.name)}),(!r||r.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."}),f&&e.jsx(l.Button,{variant:"outlined",onClick:()=>{X.forEach(h=>{a(h)})},children:"Create default roles"})]})})})]})]}),e.jsx(k.DeleteConfirmationDialog,{open:!!p,loading:F,onAccept:()=>{p&&(y(!0),n(p).then(()=>{v(void 0)}).finally(()=>{y(!1)}))},onCancel:()=>{v(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 R=c.memo(function({children:s}){const{collections:r}=k.useNavigationController(),[a,n]=c.useState(!1),[f,p]=c.useState(),{canEditRoles:v}=L(),F=c.useCallback(h=>{n(!0),p(h)},[]),y=()=>{p(void 0),n(!1)};return e.jsxs(l.Container,{className:"w-full flex flex-col py-4 gap-4",maxWidth:"6xl",children:[s,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:v?void 0:"Update plans to customise roles",children:e.jsx(l.Button,{size:"large",disabled:!v,startIcon:e.jsx(l.AddIcon,{}),onClick:()=>n(!0),children:"Add role"})})]}),e.jsx(Z,{onRoleClicked:F,editable:!!v}),e.jsx(Q,{open:a,role:f,editable:v,collections:r,handleClose:y},f?.id??"new")]})}),ee=B.object().shape({displayName:B.string().required("Required"),email:B.string().email().required("Required"),roles:B.array().min(1)});function Se(o,s,r,a,n){const f=r.filter(y=>y.roles?.map(h=>h.id).includes("admin")),p=o.roles?.map(y=>y.id).includes("admin");if((!n||!H(n.roles??[],s.roles??[]))&&!p)throw new Error("Only admins can change roles");if(n&&n.roles?.map(y=>y.id).includes("admin")&&!s.roles?.map(y=>y.id).includes("admin")&&f.length===1)throw new Error("There must be at least one admin");return!0}function le({open:o,user:s,handleClose:r}){const a=k.useSnackbarController(),{user:n}=k.useAuthController(),{saveUser:f,users:p,roles:v}=L(),F=!s,y=c.useCallback(m=>{if(!n)throw new Error("Logged user not found");try{return Se(n,m,p,v,s),f(m)}catch(N){return Promise.reject(N)}},[v,f,s,p,n]),h=P.useCreateFormex({initialValues:s??{displayName:"",email:"",roles:v.filter(m=>m.id==="editor")},validation:m=>ee.validate(m,{abortEarly:!1}).then(()=>({})).catch(N=>N.inner.reduce((I,A)=>(I[A.path]=A.message,I),{})),onSubmit:(m,N)=>y(m).then(()=>{r(),N.resetForm({values:m})}).catch(I=>{a.open({type:"error",message:I.message})})}),{isSubmitting:E,touched:D,handleChange:i,values:b,errors:w,setFieldValue:T,dirty:_,handleSubmit:$,submitCount:g}=h;return e.jsx(l.Dialog,{open:o,onOpenChange:m=>m?void 0:r(),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:g>0&&!!w.displayName,value:b.displayName??"",onChange:i,"aria-describedby":"name-helper-text",label:"Name"}),e.jsx(k.FieldCaption,{children:g>0&&w.displayName?w.displayName:"Name of this user"})]}),e.jsxs("div",{className:"col-span-12",children:[e.jsx(l.TextField,{required:!0,error:g>0&&!!w.email,name:"email",value:b.email??"",onChange:i,"aria-describedby":"email-helper-text",label:"Email"}),e.jsx(k.FieldCaption,{children:g>0&&w.email?w.email:"Email of this user"})]}),e.jsx("div",{className:"col-span-12",children:e.jsx(l.MultiSelect,{label:"Roles",value:b.roles?.map(m=>m.id)??[],onMultiValueChange:m=>T("roles",m.map(N=>v.find(I=>I.id===N))),renderValue:m=>{const N=v.find(I=>I.id===m);return N?e.jsx("div",{className:"flex flex-wrap space-x-2 space-y-2",children:e.jsx(O,{role:N},N?.id)}):null},children:v.map(m=>e.jsx(l.MultiSelectItem,{value:m.id,children:e.jsx(O,{role:m},m?.id)},m.id))})})]})]}),e.jsxs(l.DialogActions,{children:[e.jsx(l.Button,{variant:"text",onClick:()=>{r()},children:"Cancel"}),e.jsx(l.LoadingButton,{variant:"filled",color:"primary",type:"submit",disabled:!_,loading:E,startIcon:e.jsx(l.DoneIcon,{}),children:F?"Create user":"Update"})]})]})})})}function re({onUserClicked:o}){const{users:s,saveUser:r,deleteUser:a}=L(),n=k.useAuthController(),f=k.useSnackbarController(),p=k.useCustomizationController(),v=p?.locale?de[p?.locale]:void 0,F=p?.dateTimeFormat??k.defaultDateFormat,[y,h]=c.useState(void 0),[E,D]=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:[s&&s.map(i=>{const b=i.roles,w=i.created_on?te.format(i.created_on,F,{locale:v}):"";return e.jsxs(l.TableRow,{onClick:()=>{o(i)},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:T=>(T.stopPropagation(),h(i)),children:e.jsx(l.DeleteIcon,{})})})}),e.jsx(l.TableCell,{children:i.uid}),e.jsx(l.TableCell,{children:i.email}),e.jsx(l.TableCell,{className:"font-medium align-left",children:i.displayName}),e.jsx(l.TableCell,{className:"align-left",children:b?e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(T=>e.jsx(O,{role:T},T?.id))}):null}),e.jsx(l.TableCell,{children:w})]},"row_"+i.uid)}),(!s||s.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");r({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(()=>{f.open({type:"success",message:"User added successfully"})}).catch(i=>{f.open({type:"error",message:"Error adding user: "+i.message})})},children:"Add the logged user as an admin"})]})})})]})]}),e.jsx(k.DeleteConfirmationDialog,{open:!!y,loading:E,onAccept:()=>{y&&(D(!0),a(y).then(()=>{h(void 0)}).catch(i=>{f.open({type:"error",message:"Error deleting user: "+i.message})}).finally(()=>{D(!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:s}){const[r,a]=c.useState(),[n,f]=c.useState(),{users:p,usersLimit:v}=L(),F=v!==void 0&&p&&p.length>=v,y=c.useCallback(E=>{f(E),a(!0)},[]),h=c.useCallback(()=>{a(!1),f(void 0)},[]);return e.jsxs(l.Container,{className:"w-full flex flex-col py-4 gap-4",maxWidth:"6xl",children:[s,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:F,startIcon:e.jsx(l.AddIcon,{}),onClick:()=>a(!0),children:"Add user"})]}),e.jsx(re,{onUserClicked:y}),e.jsx(le,{open:r??!1,user:n,handleClose:h},n?.uid??"new")]})};function Ue({userManagement:o}){const s=o.users.length===0,r=o.roles.length===0;return{key:"user_management",loading:o.loading,homePage:{additionalChildrenStart:s||r?e.jsx(se,{noUsers:s,noRoles:r,userManagement:o}):void 0},provider:{Component:G,props:{userManagement:o}}}}function se({noUsers:o,noRoles:s,userManagement:r}){const a=k.useAuthController(),n=k.useSnackbarController(),f=o&&s?"Create default roles and add current user as admin":o?"Add current user as admin":s?"Create default roles":void 0;return e.jsxs(l.Paper,{className:"my-4 flex flex-col px-4 py-6 bg-white dark:bg-slate-800 gap-2",children:[e.jsx(l.Typography,{variant:"subtitle2",className:"uppercase",children:"Create your users and roles"}),e.jsx(l.Typography,{children:"You have no users or roles defined. You can create default roles and add the current user as admin."}),e.jsxs(l.Button,{onClick:()=>{if(!a.user?.uid)throw Error("UsersTable, authController misconfiguration");o&&r.saveUser({uid:a.user?.uid,email:a.user?.email,displayName:a.user?.displayName,photoURL:a.user?.photoURL,providerId:a.user?.providerId,isAnonymous:a.user?.isAnonymous,roles:[{id:"admin",name:"Admin"}],created_on:new Date}).then(()=>{n.open({type:"success",message:"User added successfully"})}).catch(p=>{n.open({type:"error",message:"Error adding user: "+p.message})}),s&&X.forEach(p=>{r.saveRole(p)})},children:[e.jsx(l.AddIcon,{}),f]})]})}const ke=[{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(R,{})}];d.IntroWidget=se,d.RESERVED_GROUPS=ce,d.RoleChip=O,d.RoleYupSchema=K,d.RolesDetailsForm=Q,d.RolesTable=Z,d.RolesView=R,d.UserDetailsForm=le,d.UserManagementContext=W,d.UserManagementProvider=G,d.UserYupSchema=ee,d.UsersTable=re,d.UsersView=oe,d.areRolesEqual=H,d.cacheDelegatedLoginToken=me,d.clearDelegatedLoginTokensCache=pe,d.darkenColor=be,d.getDelegatedLoginTokenFromCache=Ce,d.getUserRoles=fe,d.hexToRgbaWithOpacity=ve,d.resolveUserRolePermissions=J,d.useFirestoreUserManagement=ye,d.useUserManagement=L,d.useUserManagementPlugin=Ue,d.userManagementAdminViews=ke,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});
|
1
|
+
(function(global, factory) {
|
2
|
+
typeof exports === "object" && typeof module !== "undefined" ? factory(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"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.FireCMS = {}, global.React, global.firestore, global.jsxRuntime, global.ui, global.Yup, global.core, global.formex, global.dateFns, global.locales));
|
3
|
+
})(this, function(exports2, React, firestore, jsxRuntime, ui, Yup, core, formex, dateFns, locales) {
|
4
|
+
"use strict";
|
5
|
+
function _interopNamespaceDefault(e) {
|
6
|
+
const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
|
7
|
+
if (e) {
|
8
|
+
for (const k in e) {
|
9
|
+
if (k !== "default") {
|
10
|
+
const d = Object.getOwnPropertyDescriptor(e, k);
|
11
|
+
Object.defineProperty(n, k, d.get ? d : {
|
12
|
+
enumerable: true,
|
13
|
+
get: () => e[k]
|
14
|
+
});
|
15
|
+
}
|
16
|
+
}
|
17
|
+
}
|
18
|
+
n.default = e;
|
19
|
+
return Object.freeze(n);
|
20
|
+
}
|
21
|
+
const Yup__namespace = /* @__PURE__ */ _interopNamespaceDefault(Yup);
|
22
|
+
const locales__namespace = /* @__PURE__ */ _interopNamespaceDefault(locales);
|
23
|
+
const RESERVED_GROUPS = ["Admin"];
|
24
|
+
const DEFAULT_PERMISSIONS = {
|
25
|
+
read: false,
|
26
|
+
edit: false,
|
27
|
+
create: false,
|
28
|
+
delete: false
|
29
|
+
};
|
30
|
+
function resolveUserRolePermissions({
|
31
|
+
collection,
|
32
|
+
user
|
33
|
+
}) {
|
34
|
+
const roles = user?.roles;
|
35
|
+
if (!roles) {
|
36
|
+
return DEFAULT_PERMISSIONS;
|
37
|
+
} else if (collection.ownerId === user?.uid) {
|
38
|
+
return {
|
39
|
+
read: true,
|
40
|
+
create: true,
|
41
|
+
edit: true,
|
42
|
+
delete: true
|
43
|
+
};
|
44
|
+
} else {
|
45
|
+
const basePermissions = {
|
46
|
+
read: false,
|
47
|
+
create: false,
|
48
|
+
edit: false,
|
49
|
+
delete: false
|
50
|
+
};
|
51
|
+
return roles.map((role) => resolveCollectionRole(role, collection.id)).reduce(mergePermissions, basePermissions);
|
52
|
+
}
|
53
|
+
}
|
54
|
+
function resolveCollectionRole(role, id) {
|
55
|
+
const basePermissions = {
|
56
|
+
read: role.isAdmin || role.defaultPermissions?.read,
|
57
|
+
create: role.isAdmin || role.defaultPermissions?.create,
|
58
|
+
edit: role.isAdmin || role.defaultPermissions?.edit,
|
59
|
+
delete: role.isAdmin || role.defaultPermissions?.delete
|
60
|
+
};
|
61
|
+
if (role.collectionPermissions && role.collectionPermissions[id]) {
|
62
|
+
return mergePermissions(role.collectionPermissions[id], basePermissions);
|
63
|
+
} else if (role.defaultPermissions) {
|
64
|
+
return mergePermissions(role.defaultPermissions, basePermissions);
|
65
|
+
} else {
|
66
|
+
return basePermissions;
|
67
|
+
}
|
68
|
+
}
|
69
|
+
const mergePermissions = (permA, permB) => {
|
70
|
+
return {
|
71
|
+
read: permA.read || permB.read,
|
72
|
+
create: permA.create || permB.create,
|
73
|
+
edit: permA.edit || permB.edit,
|
74
|
+
delete: permA.delete || permB.delete
|
75
|
+
};
|
76
|
+
};
|
77
|
+
function getUserRoles(roles, fireCMSUser) {
|
78
|
+
return !roles ? void 0 : fireCMSUser.roles ? fireCMSUser.roles.map((role) => roles.find((r) => r.id === role.id)).filter(Boolean) : [];
|
79
|
+
}
|
80
|
+
const areRolesEqual = (rolesA, rolesB) => {
|
81
|
+
const rolesAIds = rolesA.map((r) => r.id);
|
82
|
+
const rolesBIds = rolesB.map((r) => r.id);
|
83
|
+
return rolesAIds.length === rolesB.length && rolesAIds.every((role) => rolesBIds.includes(role));
|
84
|
+
};
|
85
|
+
function cacheDelegatedLoginToken(projectId, delegatedToken) {
|
86
|
+
if (!delegatedToken) {
|
87
|
+
return;
|
88
|
+
}
|
89
|
+
const data = parseJwt(delegatedToken);
|
90
|
+
const expiry = new Date(data.exp * 1e3);
|
91
|
+
localStorage.setItem(`auth_token::${projectId}`, JSON.stringify({
|
92
|
+
token: delegatedToken,
|
93
|
+
expiry
|
94
|
+
}));
|
95
|
+
}
|
96
|
+
function getDelegatedLoginTokenFromCache(projectId) {
|
97
|
+
const entry = localStorage.getItem(`auth_token::${projectId}`);
|
98
|
+
if (entry) {
|
99
|
+
const data = JSON.parse(entry);
|
100
|
+
data.expiry = new Date(data.expiry);
|
101
|
+
if (data.expiry > /* @__PURE__ */ new Date()) {
|
102
|
+
return data.token;
|
103
|
+
}
|
104
|
+
}
|
105
|
+
return void 0;
|
106
|
+
}
|
107
|
+
function clearDelegatedLoginTokensCache() {
|
108
|
+
for (let i = 0; i < localStorage.length; i++) {
|
109
|
+
const key = localStorage.key(i);
|
110
|
+
if (key?.startsWith("auth_token::")) {
|
111
|
+
localStorage.removeItem(key);
|
112
|
+
}
|
113
|
+
}
|
114
|
+
}
|
115
|
+
function parseJwt(token) {
|
116
|
+
if (!token) {
|
117
|
+
throw new Error("No JWT token");
|
118
|
+
}
|
119
|
+
const base64Url = token.split(".")[1];
|
120
|
+
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
|
121
|
+
const jsonPayload = decodeURIComponent(window.atob(base64).split("").map(function(c) {
|
122
|
+
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
|
123
|
+
}).join(""));
|
124
|
+
return JSON.parse(jsonPayload);
|
125
|
+
}
|
126
|
+
function darkenColor(hexColor, darkenBy = 10) {
|
127
|
+
if (!/^#([0-9A-Fa-f]{3}){1,2}$/.test(hexColor)) {
|
128
|
+
throw new Error("Invalid color format");
|
129
|
+
}
|
130
|
+
let color = hexColor.substring(1).split("");
|
131
|
+
if (color.length === 3) {
|
132
|
+
color = [color[0], color[0], color[1], color[1], color[2], color[2]];
|
133
|
+
}
|
134
|
+
let r = parseInt(color[0] + color[1], 16);
|
135
|
+
let g = parseInt(color[2] + color[3], 16);
|
136
|
+
let b = parseInt(color[4] + color[5], 16);
|
137
|
+
r = Math.floor(r * (1 - darkenBy / 100));
|
138
|
+
g = Math.floor(g * (1 - darkenBy / 100));
|
139
|
+
b = Math.floor(b * (1 - darkenBy / 100));
|
140
|
+
return "#" + (r < 16 ? "0" : "") + r.toString(16) + (g < 16 ? "0" : "") + g.toString(16) + (b < 16 ? "0" : "") + b.toString(16);
|
141
|
+
}
|
142
|
+
function hexToRgbaWithOpacity(hexColor, opacity = 10) {
|
143
|
+
if (!/^#([0-9A-Fa-f]{3}){1,2}$/.test(hexColor)) {
|
144
|
+
throw new Error("Invalid color format");
|
145
|
+
}
|
146
|
+
let color = hexColor.substring(1).split("");
|
147
|
+
if (color.length === 3) {
|
148
|
+
color = [color[0], color[0], color[1], color[1], color[2], color[2]];
|
149
|
+
}
|
150
|
+
const r = parseInt(color[0] + color[1], 16);
|
151
|
+
const g = parseInt(color[2] + color[3], 16);
|
152
|
+
const b = parseInt(color[4] + color[5], 16);
|
153
|
+
const alpha = opacity / 100;
|
154
|
+
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
155
|
+
}
|
156
|
+
function useFirestoreUserManagement({
|
157
|
+
firebaseApp,
|
158
|
+
usersPath = "__FIRECMS/config/users",
|
159
|
+
rolesPath = "__FIRECMS/config/roles",
|
160
|
+
usersLimit,
|
161
|
+
canEditRoles = true,
|
162
|
+
allowDefaultRolesCreation,
|
163
|
+
includeCollectionConfigPermissions
|
164
|
+
}) {
|
165
|
+
const [rolesLoading, setRolesLoading] = React.useState(true);
|
166
|
+
const [usersLoading, setUsersLoading] = React.useState(true);
|
167
|
+
const [roles, setRoles] = React.useState([]);
|
168
|
+
const [usersWithRoleIds, setUsersWithRoleIds] = React.useState([]);
|
169
|
+
const users = usersWithRoleIds.map((u) => ({
|
170
|
+
...u,
|
171
|
+
roles: roles.filter((r) => u.roles?.includes(r.id))
|
172
|
+
}));
|
173
|
+
const [rolesError, setRolesError] = React.useState();
|
174
|
+
const [usersError, setUsersError] = React.useState();
|
175
|
+
const loading = rolesLoading || usersLoading;
|
176
|
+
React.useEffect(() => {
|
177
|
+
if (!firebaseApp || !rolesPath) return;
|
178
|
+
const firestore$1 = firestore.getFirestore(firebaseApp);
|
179
|
+
return firestore.onSnapshot(
|
180
|
+
firestore.collection(firestore$1, rolesPath),
|
181
|
+
{
|
182
|
+
next: (snapshot) => {
|
183
|
+
setRolesError(void 0);
|
184
|
+
try {
|
185
|
+
const newRoles = docsToRoles(snapshot.docs);
|
186
|
+
setRoles(newRoles);
|
187
|
+
} catch (e) {
|
188
|
+
console.error("Error loading roles", e);
|
189
|
+
setRolesError(e);
|
190
|
+
}
|
191
|
+
setRolesLoading(false);
|
192
|
+
},
|
193
|
+
error: (e) => {
|
194
|
+
console.error("Error loading roles", e);
|
195
|
+
setRolesError(e);
|
196
|
+
setRolesLoading(false);
|
197
|
+
}
|
198
|
+
}
|
199
|
+
);
|
200
|
+
}, [firebaseApp, rolesPath]);
|
201
|
+
React.useEffect(() => {
|
202
|
+
if (!firebaseApp || !usersPath) return;
|
203
|
+
const firestore$1 = firestore.getFirestore(firebaseApp);
|
204
|
+
return firestore.onSnapshot(
|
205
|
+
firestore.collection(firestore$1, usersPath),
|
206
|
+
{
|
207
|
+
next: (snapshot) => {
|
208
|
+
setUsersError(void 0);
|
209
|
+
try {
|
210
|
+
const newUsers = docsToUsers(snapshot.docs);
|
211
|
+
setUsersWithRoleIds(newUsers);
|
212
|
+
} catch (e) {
|
213
|
+
console.error("Error loading users", e);
|
214
|
+
setUsersError(e);
|
215
|
+
}
|
216
|
+
setUsersLoading(false);
|
217
|
+
},
|
218
|
+
error: (e) => {
|
219
|
+
console.error("Error loading users", e);
|
220
|
+
setUsersError(e);
|
221
|
+
setUsersLoading(false);
|
222
|
+
}
|
223
|
+
}
|
224
|
+
);
|
225
|
+
}, [firebaseApp, usersPath]);
|
226
|
+
const saveUser = React.useCallback(async (user) => {
|
227
|
+
if (!firebaseApp) throw Error("useFirestoreUserManagement Firebase not initialised");
|
228
|
+
const firestore$1 = firestore.getFirestore(firebaseApp);
|
229
|
+
if (!firestore$1 || !usersPath) throw Error("useFirestoreUserManagement Firestore not initialised");
|
230
|
+
console.debug("Persisting user", user);
|
231
|
+
const roleIds = user.roles?.map((r) => r.id);
|
232
|
+
const {
|
233
|
+
uid,
|
234
|
+
...userData
|
235
|
+
} = user;
|
236
|
+
const data = {
|
237
|
+
...userData,
|
238
|
+
roles: roleIds
|
239
|
+
};
|
240
|
+
if (uid) {
|
241
|
+
return firestore.setDoc(firestore.doc(firestore$1, usersPath, uid), data, { merge: true }).then(() => user);
|
242
|
+
} else {
|
243
|
+
return firestore.addDoc(firestore.collection(firestore$1, usersPath), data).then(() => user);
|
244
|
+
}
|
245
|
+
}, [usersPath, firebaseApp]);
|
246
|
+
const saveRole = React.useCallback((role) => {
|
247
|
+
if (!firebaseApp) throw Error("useFirestoreUserManagement Firebase not initialised");
|
248
|
+
const firestore$1 = firestore.getFirestore(firebaseApp);
|
249
|
+
if (!firestore$1 || !rolesPath) throw Error("useFirestoreUserManagement Firestore not initialised");
|
250
|
+
console.debug("Persisting role", role);
|
251
|
+
const {
|
252
|
+
id,
|
253
|
+
...roleData
|
254
|
+
} = role;
|
255
|
+
const ref = firestore.doc(firestore$1, rolesPath, id);
|
256
|
+
return firestore.setDoc(ref, roleData, { merge: true });
|
257
|
+
}, [rolesPath, firebaseApp]);
|
258
|
+
const deleteUser = React.useCallback(async (user) => {
|
259
|
+
if (!firebaseApp) throw Error("useFirestoreUserManagement Firebase not initialised");
|
260
|
+
const firestore$1 = firestore.getFirestore(firebaseApp);
|
261
|
+
if (!firestore$1 || !usersPath) throw Error("useFirestoreUserManagement Firestore not initialised");
|
262
|
+
console.debug("Deleting", user);
|
263
|
+
const { uid } = user;
|
264
|
+
return firestore.deleteDoc(firestore.doc(firestore$1, usersPath, uid));
|
265
|
+
}, [usersPath, firebaseApp]);
|
266
|
+
const deleteRole = React.useCallback((role) => {
|
267
|
+
if (!firebaseApp) throw Error("useFirestoreUserManagement Firebase not initialised");
|
268
|
+
const firestore$1 = firestore.getFirestore(firebaseApp);
|
269
|
+
if (!firestore$1 || !rolesPath) throw Error("useFirestoreUserManagement Firestore not initialised");
|
270
|
+
console.debug("Deleting", role);
|
271
|
+
const { id } = role;
|
272
|
+
const ref = firestore.doc(firestore$1, rolesPath, id);
|
273
|
+
return firestore.deleteDoc(ref);
|
274
|
+
}, [rolesPath, firebaseApp]);
|
275
|
+
const collectionPermissions = React.useCallback(({
|
276
|
+
collection: collection2,
|
277
|
+
user
|
278
|
+
}) => resolveUserRolePermissions({
|
279
|
+
collection: collection2,
|
280
|
+
user
|
281
|
+
}), []);
|
282
|
+
const defineRolesFor = React.useCallback((user) => {
|
283
|
+
if (!users) throw Error("Users not loaded");
|
284
|
+
const mgmtUser = users.find((u) => u.email?.toLowerCase() === user?.email?.toLowerCase());
|
285
|
+
return mgmtUser?.roles;
|
286
|
+
}, [users]);
|
287
|
+
const authenticator = React.useCallback(({ user }) => {
|
288
|
+
console.debug("Authenticating user", user);
|
289
|
+
if (loading) {
|
290
|
+
console.warn("User management is still loading");
|
291
|
+
return false;
|
292
|
+
}
|
293
|
+
if (users.length === 0) {
|
294
|
+
return true;
|
295
|
+
}
|
296
|
+
const mgmtUser = users.find((u) => u.email?.toLowerCase() === user?.email?.toLowerCase());
|
297
|
+
if (mgmtUser) {
|
298
|
+
return true;
|
299
|
+
}
|
300
|
+
throw Error("Could not find a user with the provided email in the user management system.");
|
301
|
+
}, [loading, users]);
|
302
|
+
const isAdmin = roles.some((r) => r.id === "admin");
|
303
|
+
return {
|
304
|
+
loading,
|
305
|
+
roles,
|
306
|
+
users,
|
307
|
+
saveUser,
|
308
|
+
saveRole,
|
309
|
+
rolesError,
|
310
|
+
deleteUser,
|
311
|
+
deleteRole,
|
312
|
+
usersLimit,
|
313
|
+
usersError,
|
314
|
+
isAdmin,
|
315
|
+
canEditRoles: canEditRoles === void 0 ? true : canEditRoles,
|
316
|
+
allowDefaultRolesCreation: allowDefaultRolesCreation === void 0 ? true : allowDefaultRolesCreation,
|
317
|
+
includeCollectionConfigPermissions: Boolean(includeCollectionConfigPermissions),
|
318
|
+
collectionPermissions,
|
319
|
+
defineRolesFor,
|
320
|
+
authenticator
|
321
|
+
};
|
322
|
+
}
|
323
|
+
const docsToUsers = (docs) => {
|
324
|
+
return docs.map((doc2) => {
|
325
|
+
const data = doc2.data();
|
326
|
+
const newVar = {
|
327
|
+
uid: doc2.id,
|
328
|
+
...data,
|
329
|
+
created_on: data?.created_on?.toDate(),
|
330
|
+
updated_on: data?.updated_on?.toDate()
|
331
|
+
};
|
332
|
+
return newVar;
|
333
|
+
});
|
334
|
+
};
|
335
|
+
const docsToRoles = (docs) => {
|
336
|
+
return docs.map((doc2) => ({
|
337
|
+
id: doc2.id,
|
338
|
+
...doc2.data()
|
339
|
+
}));
|
340
|
+
};
|
341
|
+
const UserManagementContext = React.createContext({});
|
342
|
+
function UserManagementProvider({
|
343
|
+
children,
|
344
|
+
userManagement
|
345
|
+
}) {
|
346
|
+
return /* @__PURE__ */ jsxRuntime.jsx(UserManagementContext.Provider, { value: userManagement, children });
|
347
|
+
}
|
348
|
+
const useUserManagement = () => React.useContext(UserManagementContext);
|
349
|
+
function RoleChip({ role }) {
|
350
|
+
let colorScheme;
|
351
|
+
if (role.isAdmin) {
|
352
|
+
colorScheme = "blueDarker";
|
353
|
+
} else if (role.id === "editor") {
|
354
|
+
colorScheme = "yellowLight";
|
355
|
+
} else if (role.id === "viewer") {
|
356
|
+
colorScheme = "grayLight";
|
357
|
+
} else {
|
358
|
+
colorScheme = ui.getColorSchemeForSeed(role.id);
|
359
|
+
}
|
360
|
+
return /* @__PURE__ */ jsxRuntime.jsx(
|
361
|
+
ui.Chip,
|
362
|
+
{
|
363
|
+
colorScheme,
|
364
|
+
children: role.name
|
365
|
+
},
|
366
|
+
role.id
|
367
|
+
);
|
368
|
+
}
|
369
|
+
const RoleYupSchema = Yup__namespace.object().shape({
|
370
|
+
id: Yup__namespace.string().required("Required"),
|
371
|
+
name: Yup__namespace.string().required("Required")
|
372
|
+
});
|
373
|
+
function RolesDetailsForm({
|
374
|
+
open,
|
375
|
+
role,
|
376
|
+
editable,
|
377
|
+
handleClose,
|
378
|
+
collections
|
379
|
+
}) {
|
380
|
+
const { saveRole } = useUserManagement();
|
381
|
+
const isNewRole = !role;
|
382
|
+
const [savingError, setSavingError] = React.useState();
|
383
|
+
const onRoleUpdated = React.useCallback((role2) => {
|
384
|
+
setSavingError(void 0);
|
385
|
+
return saveRole(role2);
|
386
|
+
}, [saveRole]);
|
387
|
+
const formex$1 = formex.useCreateFormex({
|
388
|
+
initialValues: role ?? {
|
389
|
+
name: ""
|
390
|
+
},
|
391
|
+
onSubmit: (role2, formexController) => {
|
392
|
+
return onRoleUpdated(role2).then(() => {
|
393
|
+
formexController.resetForm({
|
394
|
+
values: role2
|
395
|
+
});
|
396
|
+
handleClose();
|
397
|
+
}).catch((e) => setSavingError(e));
|
398
|
+
},
|
399
|
+
validation: (values2) => {
|
400
|
+
return RoleYupSchema.validate(values2, { abortEarly: false }).then(() => ({})).catch((e) => {
|
401
|
+
const errors2 = {};
|
402
|
+
e.inner.forEach((error) => {
|
403
|
+
errors2[error.path] = error.message;
|
404
|
+
});
|
405
|
+
return errors2;
|
406
|
+
});
|
407
|
+
}
|
408
|
+
});
|
409
|
+
const {
|
410
|
+
isSubmitting,
|
411
|
+
touched,
|
412
|
+
values,
|
413
|
+
errors,
|
414
|
+
handleChange,
|
415
|
+
setFieldValue,
|
416
|
+
dirty,
|
417
|
+
setFieldTouched
|
418
|
+
} = formex$1;
|
419
|
+
const isAdmin = values.isAdmin ?? false;
|
420
|
+
const defaultCreate = values.defaultPermissions?.create ?? false;
|
421
|
+
const defaultRead = values.defaultPermissions?.read ?? false;
|
422
|
+
const defaultEdit = values.defaultPermissions?.edit ?? false;
|
423
|
+
const defaultDelete = values.defaultPermissions?.delete ?? false;
|
424
|
+
React.useEffect(() => {
|
425
|
+
const idTouched = formex.getIn(touched, "id");
|
426
|
+
if (!idTouched && values.name) {
|
427
|
+
setFieldValue("id", core.toSnakeCase(values.name));
|
428
|
+
}
|
429
|
+
}, [touched, values.name]);
|
430
|
+
return /* @__PURE__ */ jsxRuntime.jsx(
|
431
|
+
ui.Dialog,
|
432
|
+
{
|
433
|
+
open,
|
434
|
+
maxWidth: "4xl",
|
435
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(formex.Formex, { value: formex$1, children: /* @__PURE__ */ jsxRuntime.jsxs(
|
436
|
+
"form",
|
437
|
+
{
|
438
|
+
noValidate: true,
|
439
|
+
autoComplete: "off",
|
440
|
+
onSubmit: formex$1.handleSubmit,
|
441
|
+
style: {
|
442
|
+
display: "flex",
|
443
|
+
flexDirection: "column",
|
444
|
+
position: "relative",
|
445
|
+
height: "100%"
|
446
|
+
},
|
447
|
+
children: [
|
448
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.DialogContent, { className: "flex-grow", children: [
|
449
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
450
|
+
"div",
|
451
|
+
{
|
452
|
+
className: "flex flex-row pt-12 pb-8",
|
453
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
454
|
+
ui.Typography,
|
455
|
+
{
|
456
|
+
variant: "h4",
|
457
|
+
className: "flex-grow",
|
458
|
+
children: "Role"
|
459
|
+
}
|
460
|
+
)
|
461
|
+
}
|
462
|
+
),
|
463
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-12 gap-8", children: [
|
464
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "col-span-12 md:col-span-8", children: [
|
465
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
466
|
+
ui.TextField,
|
467
|
+
{
|
468
|
+
name: "name",
|
469
|
+
required: true,
|
470
|
+
error: touched.name && Boolean(errors.name),
|
471
|
+
value: values.name,
|
472
|
+
disabled: isAdmin || !editable,
|
473
|
+
onChange: handleChange,
|
474
|
+
"aria-describedby": "name-helper-text",
|
475
|
+
label: "Name"
|
476
|
+
}
|
477
|
+
),
|
478
|
+
/* @__PURE__ */ jsxRuntime.jsx(core.FieldCaption, { children: touched.name && Boolean(errors.name) ? errors.name : "Name of this role" })
|
479
|
+
] }),
|
480
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "col-span-12 md:col-span-4", children: [
|
481
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
482
|
+
ui.TextField,
|
483
|
+
{
|
484
|
+
name: "id",
|
485
|
+
required: true,
|
486
|
+
error: touched.id && Boolean(errors.id),
|
487
|
+
value: values.id,
|
488
|
+
disabled: !isNewRole || !editable,
|
489
|
+
onChange: (e) => {
|
490
|
+
handleChange(e);
|
491
|
+
setFieldTouched("id", true);
|
492
|
+
},
|
493
|
+
"aria-describedby": "id-helper-text",
|
494
|
+
label: "ID"
|
495
|
+
}
|
496
|
+
),
|
497
|
+
/* @__PURE__ */ jsxRuntime.jsx(core.FieldCaption, { children: touched.id && Boolean(errors.id) ? errors.id : "ID of this role" })
|
498
|
+
] }),
|
499
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "col-span-12", children: [
|
500
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
501
|
+
ui.Paper,
|
502
|
+
{
|
503
|
+
className: "bg-inherit",
|
504
|
+
children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Table, { children: [
|
505
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.TableHeader, { children: [
|
506
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, {}),
|
507
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
508
|
+
ui.TableCell,
|
509
|
+
{
|
510
|
+
align: "center",
|
511
|
+
children: "Create entities"
|
512
|
+
}
|
513
|
+
),
|
514
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
515
|
+
ui.TableCell,
|
516
|
+
{
|
517
|
+
align: "center",
|
518
|
+
children: "Read entities"
|
519
|
+
}
|
520
|
+
),
|
521
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
522
|
+
ui.TableCell,
|
523
|
+
{
|
524
|
+
align: "center",
|
525
|
+
children: "Update entities"
|
526
|
+
}
|
527
|
+
),
|
528
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
529
|
+
ui.TableCell,
|
530
|
+
{
|
531
|
+
align: "center",
|
532
|
+
children: "Delete entities"
|
533
|
+
}
|
534
|
+
)
|
535
|
+
] }),
|
536
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.TableBody, { children: [
|
537
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.TableRow, { children: [
|
538
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
539
|
+
ui.TableCell,
|
540
|
+
{
|
541
|
+
scope: "row",
|
542
|
+
children: /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "All collections" })
|
543
|
+
}
|
544
|
+
),
|
545
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
546
|
+
ui.TableCell,
|
547
|
+
{
|
548
|
+
align: "center",
|
549
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
550
|
+
ui.Tooltip,
|
551
|
+
{
|
552
|
+
title: "Create entities in collections",
|
553
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
554
|
+
ui.Checkbox,
|
555
|
+
{
|
556
|
+
disabled: isAdmin || !editable,
|
557
|
+
checked: (isAdmin || defaultCreate) ?? false,
|
558
|
+
onCheckedChange: (checked) => setFieldValue("defaultPermissions.create", checked)
|
559
|
+
}
|
560
|
+
)
|
561
|
+
}
|
562
|
+
)
|
563
|
+
}
|
564
|
+
),
|
565
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
566
|
+
ui.TableCell,
|
567
|
+
{
|
568
|
+
align: "center",
|
569
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
570
|
+
ui.Tooltip,
|
571
|
+
{
|
572
|
+
title: "Access all data in every collection",
|
573
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
574
|
+
ui.Checkbox,
|
575
|
+
{
|
576
|
+
disabled: isAdmin || !editable,
|
577
|
+
checked: (isAdmin || defaultRead) ?? false,
|
578
|
+
onCheckedChange: (checked) => setFieldValue("defaultPermissions.read", checked)
|
579
|
+
}
|
580
|
+
)
|
581
|
+
}
|
582
|
+
)
|
583
|
+
}
|
584
|
+
),
|
585
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
586
|
+
ui.TableCell,
|
587
|
+
{
|
588
|
+
align: "center",
|
589
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
590
|
+
ui.Tooltip,
|
591
|
+
{
|
592
|
+
title: "Update data in any collection",
|
593
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
594
|
+
ui.Checkbox,
|
595
|
+
{
|
596
|
+
disabled: isAdmin || !editable,
|
597
|
+
checked: (isAdmin || defaultEdit) ?? false,
|
598
|
+
onCheckedChange: (checked) => setFieldValue("defaultPermissions.edit", checked)
|
599
|
+
}
|
600
|
+
)
|
601
|
+
}
|
602
|
+
)
|
603
|
+
}
|
604
|
+
),
|
605
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
606
|
+
ui.TableCell,
|
607
|
+
{
|
608
|
+
align: "center",
|
609
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
610
|
+
ui.Tooltip,
|
611
|
+
{
|
612
|
+
title: "Delete data in any collection",
|
613
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
614
|
+
ui.Checkbox,
|
615
|
+
{
|
616
|
+
disabled: isAdmin || !editable,
|
617
|
+
checked: (isAdmin || defaultDelete) ?? false,
|
618
|
+
onCheckedChange: (checked) => setFieldValue("defaultPermissions.delete", checked)
|
619
|
+
}
|
620
|
+
)
|
621
|
+
}
|
622
|
+
)
|
623
|
+
}
|
624
|
+
)
|
625
|
+
] }),
|
626
|
+
collections && collections.map((col) => /* @__PURE__ */ jsxRuntime.jsxs(ui.TableRow, { children: [
|
627
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
628
|
+
ui.TableCell,
|
629
|
+
{
|
630
|
+
scope: "row",
|
631
|
+
children: col.name
|
632
|
+
}
|
633
|
+
),
|
634
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
635
|
+
ui.TableCell,
|
636
|
+
{
|
637
|
+
align: "center",
|
638
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
639
|
+
ui.Checkbox,
|
640
|
+
{
|
641
|
+
disabled: isAdmin || defaultCreate || !editable,
|
642
|
+
checked: (isAdmin || defaultCreate || formex.getIn(values, `collectionPermissions.${col.path}.create`)) ?? false,
|
643
|
+
onCheckedChange: (checked) => setFieldValue(`collectionPermissions.${col.path}.create`, checked)
|
644
|
+
}
|
645
|
+
)
|
646
|
+
}
|
647
|
+
),
|
648
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
649
|
+
ui.TableCell,
|
650
|
+
{
|
651
|
+
align: "center",
|
652
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
653
|
+
ui.Checkbox,
|
654
|
+
{
|
655
|
+
disabled: isAdmin || defaultRead || !editable,
|
656
|
+
checked: (isAdmin || defaultRead || formex.getIn(values, `collectionPermissions.${col.path}.read`)) ?? false,
|
657
|
+
onCheckedChange: (checked) => setFieldValue(`collectionPermissions.${col.path}.read`, checked)
|
658
|
+
}
|
659
|
+
)
|
660
|
+
}
|
661
|
+
),
|
662
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
663
|
+
ui.TableCell,
|
664
|
+
{
|
665
|
+
align: "center",
|
666
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
667
|
+
ui.Checkbox,
|
668
|
+
{
|
669
|
+
disabled: isAdmin || defaultEdit || !editable,
|
670
|
+
checked: (isAdmin || defaultEdit || formex.getIn(values, `collectionPermissions.${col.path}.edit`)) ?? false,
|
671
|
+
onCheckedChange: (checked) => setFieldValue(`collectionPermissions.${col.path}.edit`, checked)
|
672
|
+
}
|
673
|
+
)
|
674
|
+
}
|
675
|
+
),
|
676
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
677
|
+
ui.TableCell,
|
678
|
+
{
|
679
|
+
align: "center",
|
680
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
681
|
+
ui.Checkbox,
|
682
|
+
{
|
683
|
+
disabled: isAdmin || defaultDelete || !editable,
|
684
|
+
checked: (isAdmin || defaultDelete || formex.getIn(values, `collectionPermissions.${col.path}.delete`)) ?? false,
|
685
|
+
onCheckedChange: (checked) => setFieldValue(`collectionPermissions.${col.path}.delete`, checked)
|
686
|
+
}
|
687
|
+
)
|
688
|
+
}
|
689
|
+
)
|
690
|
+
] }, col.name))
|
691
|
+
] })
|
692
|
+
] })
|
693
|
+
}
|
694
|
+
),
|
695
|
+
/* @__PURE__ */ jsxRuntime.jsx(core.FieldCaption, { children: "You can customise the permissions that the users related to this role can perform in the entities of each collection" })
|
696
|
+
] }),
|
697
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "col-span-12 md:col-span-4", children: [
|
698
|
+
/* @__PURE__ */ jsxRuntime.jsxs(
|
699
|
+
ui.Select,
|
700
|
+
{
|
701
|
+
error: touched.config && Boolean(errors.config),
|
702
|
+
id: "createCollections",
|
703
|
+
name: "createCollections",
|
704
|
+
label: "Create collections",
|
705
|
+
position: "item-aligned",
|
706
|
+
disabled: isAdmin || !editable,
|
707
|
+
onChange: (event) => setFieldValue("config.createCollections", event.target.value === "true"),
|
708
|
+
value: isAdmin || values.config?.createCollections ? "true" : "false",
|
709
|
+
renderValue: (value) => value === "true" ? "Yes" : "No",
|
710
|
+
children: [
|
711
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
712
|
+
ui.SelectItem,
|
713
|
+
{
|
714
|
+
value: "true",
|
715
|
+
children: " Yes "
|
716
|
+
}
|
717
|
+
),
|
718
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
719
|
+
ui.SelectItem,
|
720
|
+
{
|
721
|
+
value: "false",
|
722
|
+
children: " No "
|
723
|
+
}
|
724
|
+
)
|
725
|
+
]
|
726
|
+
}
|
727
|
+
),
|
728
|
+
/* @__PURE__ */ jsxRuntime.jsx(core.FieldCaption, { children: touched.config && Boolean(errors.config) ? errors.config : "Can the user create collections" })
|
729
|
+
] }),
|
730
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "col-span-12 md:col-span-4", children: [
|
731
|
+
/* @__PURE__ */ jsxRuntime.jsxs(
|
732
|
+
ui.Select,
|
733
|
+
{
|
734
|
+
error: touched.config && Boolean(errors.config),
|
735
|
+
id: "editCollections",
|
736
|
+
name: "editCollections",
|
737
|
+
label: "Edit collections",
|
738
|
+
disabled: isAdmin || !editable,
|
739
|
+
position: "item-aligned",
|
740
|
+
onChange: (event) => setFieldValue("config.editCollections", event.target.value === "own" ? "own" : event.target.value === "true"),
|
741
|
+
value: isAdmin ? "true" : values.config?.editCollections === "own" ? "own" : values.config?.editCollections ? "true" : "false",
|
742
|
+
renderValue: (value) => value === "own" ? "Own" : value === "true" ? "Yes" : "No",
|
743
|
+
children: [
|
744
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
745
|
+
ui.SelectItem,
|
746
|
+
{
|
747
|
+
value: "true",
|
748
|
+
children: " Yes "
|
749
|
+
}
|
750
|
+
),
|
751
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
752
|
+
ui.SelectItem,
|
753
|
+
{
|
754
|
+
value: "false",
|
755
|
+
children: " No "
|
756
|
+
}
|
757
|
+
),
|
758
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
759
|
+
ui.SelectItem,
|
760
|
+
{
|
761
|
+
value: "own",
|
762
|
+
children: " Only his/her own "
|
763
|
+
}
|
764
|
+
)
|
765
|
+
]
|
766
|
+
}
|
767
|
+
),
|
768
|
+
/* @__PURE__ */ jsxRuntime.jsx(core.FieldCaption, { children: touched.config && Boolean(errors.config) ? errors.config : "Can the user edit collections" })
|
769
|
+
] }),
|
770
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "col-span-12 md:col-span-4", children: [
|
771
|
+
/* @__PURE__ */ jsxRuntime.jsxs(
|
772
|
+
ui.Select,
|
773
|
+
{
|
774
|
+
error: touched.config && Boolean(errors.config),
|
775
|
+
id: "deleteCollections",
|
776
|
+
name: "deleteCollections",
|
777
|
+
label: "Delete collections",
|
778
|
+
disabled: isAdmin || !editable,
|
779
|
+
position: "item-aligned",
|
780
|
+
onChange: (event) => setFieldValue("config.deleteCollections", event.target.value === "own" ? "own" : event.target.value === "true"),
|
781
|
+
value: isAdmin ? "true" : values.config?.deleteCollections === "own" ? "own" : values.config?.deleteCollections ? "true" : "false",
|
782
|
+
renderValue: (value) => value === "own" ? "Own" : value === "true" ? "Yes" : "No",
|
783
|
+
children: [
|
784
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
785
|
+
ui.SelectItem,
|
786
|
+
{
|
787
|
+
value: "true",
|
788
|
+
children: " Yes "
|
789
|
+
}
|
790
|
+
),
|
791
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
792
|
+
ui.SelectItem,
|
793
|
+
{
|
794
|
+
value: "false",
|
795
|
+
children: " No "
|
796
|
+
}
|
797
|
+
),
|
798
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
799
|
+
ui.SelectItem,
|
800
|
+
{
|
801
|
+
value: "own",
|
802
|
+
children: " Only his/her own "
|
803
|
+
}
|
804
|
+
)
|
805
|
+
]
|
806
|
+
}
|
807
|
+
),
|
808
|
+
/* @__PURE__ */ jsxRuntime.jsx(core.FieldCaption, { children: touched.config && Boolean(errors.config) ? errors.config : "Can the user delete collections" })
|
809
|
+
] })
|
810
|
+
] })
|
811
|
+
] }),
|
812
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.DialogActions, { position: "sticky", children: [
|
813
|
+
savingError && /* @__PURE__ */ jsxRuntime.jsx(ui.Typography, { className: "text-red-500", children: "There was an error saving this role" }),
|
814
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
815
|
+
ui.Button,
|
816
|
+
{
|
817
|
+
variant: "text",
|
818
|
+
onClick: () => {
|
819
|
+
handleClose();
|
820
|
+
},
|
821
|
+
children: "Cancel"
|
822
|
+
}
|
823
|
+
),
|
824
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
825
|
+
ui.LoadingButton,
|
826
|
+
{
|
827
|
+
variant: "filled",
|
828
|
+
color: "primary",
|
829
|
+
type: "submit",
|
830
|
+
disabled: !dirty,
|
831
|
+
loading: isSubmitting,
|
832
|
+
startIcon: /* @__PURE__ */ jsxRuntime.jsx(ui.DoneIcon, {}),
|
833
|
+
children: isNewRole ? "Create role" : "Update"
|
834
|
+
}
|
835
|
+
)
|
836
|
+
] })
|
837
|
+
]
|
838
|
+
}
|
839
|
+
) })
|
840
|
+
}
|
841
|
+
);
|
842
|
+
}
|
843
|
+
const DEFAULT_ROLES = [
|
844
|
+
{
|
845
|
+
id: "admin",
|
846
|
+
name: "Admin",
|
847
|
+
isAdmin: true
|
848
|
+
},
|
849
|
+
{
|
850
|
+
id: "editor",
|
851
|
+
name: "Editor",
|
852
|
+
isAdmin: false,
|
853
|
+
defaultPermissions: {
|
854
|
+
read: true,
|
855
|
+
create: true,
|
856
|
+
edit: true,
|
857
|
+
delete: true
|
858
|
+
},
|
859
|
+
config: {
|
860
|
+
createCollections: true,
|
861
|
+
editCollections: "own",
|
862
|
+
deleteCollections: "own"
|
863
|
+
}
|
864
|
+
},
|
865
|
+
{
|
866
|
+
id: "viewer",
|
867
|
+
name: "Viewer",
|
868
|
+
isAdmin: false,
|
869
|
+
defaultPermissions: {
|
870
|
+
read: true,
|
871
|
+
create: false,
|
872
|
+
edit: false,
|
873
|
+
delete: false
|
874
|
+
}
|
875
|
+
}
|
876
|
+
];
|
877
|
+
function RolesTable({
|
878
|
+
onRoleClicked,
|
879
|
+
editable
|
880
|
+
}) {
|
881
|
+
const {
|
882
|
+
roles,
|
883
|
+
saveRole,
|
884
|
+
deleteRole,
|
885
|
+
allowDefaultRolesCreation
|
886
|
+
} = useUserManagement();
|
887
|
+
const [roleToBeDeleted, setRoleToBeDeleted] = React.useState(void 0);
|
888
|
+
const [deleteInProgress, setDeleteInProgress] = React.useState(false);
|
889
|
+
return /* @__PURE__ */ jsxRuntime.jsxs(
|
890
|
+
"div",
|
891
|
+
{
|
892
|
+
className: "w-full overflow-auto",
|
893
|
+
children: [
|
894
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.Table, { children: [
|
895
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.TableHeader, { children: [
|
896
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { header: true, className: "w-16" }),
|
897
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { header: true, children: "Role" }),
|
898
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { header: true, className: "items-center", children: "Is Admin" }),
|
899
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { header: true, children: "Default permissions" })
|
900
|
+
] }),
|
901
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.TableBody, { children: [
|
902
|
+
roles && roles.map((role) => {
|
903
|
+
const canCreateAll = role.isAdmin || role.defaultPermissions?.create;
|
904
|
+
const canReadAll = role.isAdmin || role.defaultPermissions?.read;
|
905
|
+
const canUpdateAll = role.isAdmin || role.defaultPermissions?.edit;
|
906
|
+
const canDeleteAll = role.isAdmin || role.defaultPermissions?.delete;
|
907
|
+
return /* @__PURE__ */ jsxRuntime.jsxs(
|
908
|
+
ui.TableRow,
|
909
|
+
{
|
910
|
+
onClick: () => {
|
911
|
+
onRoleClicked(role);
|
912
|
+
},
|
913
|
+
children: [
|
914
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { style: { width: "64px" }, children: !role.isAdmin && /* @__PURE__ */ jsxRuntime.jsx(ui.Tooltip, { title: "Delete this role", children: /* @__PURE__ */ jsxRuntime.jsx(
|
915
|
+
ui.IconButton,
|
916
|
+
{
|
917
|
+
size: "small",
|
918
|
+
disabled: !editable,
|
919
|
+
onClick: (event) => {
|
920
|
+
event.stopPropagation();
|
921
|
+
return setRoleToBeDeleted(role);
|
922
|
+
},
|
923
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(ui.DeleteIcon, {})
|
924
|
+
}
|
925
|
+
) }) }),
|
926
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { children: /* @__PURE__ */ jsxRuntime.jsx(RoleChip, { role }) }),
|
927
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { className: "items-center", children: /* @__PURE__ */ jsxRuntime.jsx(ui.Checkbox, { checked: role.isAdmin ?? false }) }),
|
928
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { children: /* @__PURE__ */ jsxRuntime.jsxs("ul", { children: [
|
929
|
+
canCreateAll && /* @__PURE__ */ jsxRuntime.jsx("li", { children: "Create" }),
|
930
|
+
canReadAll && /* @__PURE__ */ jsxRuntime.jsx("li", { children: "Read" }),
|
931
|
+
canUpdateAll && /* @__PURE__ */ jsxRuntime.jsx("li", { children: "Update" }),
|
932
|
+
canDeleteAll && /* @__PURE__ */ jsxRuntime.jsx("li", { children: "Delete" })
|
933
|
+
] }) })
|
934
|
+
]
|
935
|
+
},
|
936
|
+
role.name
|
937
|
+
);
|
938
|
+
}),
|
939
|
+
(!roles || roles.length === 0) && /* @__PURE__ */ jsxRuntime.jsx(ui.TableRow, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { colspan: 4, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.CenteredView, { className: "flex flex-col gap-4 my-8 items-center", children: [
|
940
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.Typography, { variant: "label", children: "You don't have any roles yet." }),
|
941
|
+
allowDefaultRolesCreation && /* @__PURE__ */ jsxRuntime.jsx(
|
942
|
+
ui.Button,
|
943
|
+
{
|
944
|
+
variant: "outlined",
|
945
|
+
onClick: () => {
|
946
|
+
DEFAULT_ROLES.forEach((role) => {
|
947
|
+
saveRole(role);
|
948
|
+
});
|
949
|
+
},
|
950
|
+
children: "Create default roles"
|
951
|
+
}
|
952
|
+
)
|
953
|
+
] }) }) })
|
954
|
+
] })
|
955
|
+
] }),
|
956
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
957
|
+
core.DeleteConfirmationDialog,
|
958
|
+
{
|
959
|
+
open: Boolean(roleToBeDeleted),
|
960
|
+
loading: deleteInProgress,
|
961
|
+
onAccept: () => {
|
962
|
+
if (roleToBeDeleted) {
|
963
|
+
setDeleteInProgress(true);
|
964
|
+
deleteRole(roleToBeDeleted).then(() => {
|
965
|
+
setRoleToBeDeleted(void 0);
|
966
|
+
}).finally(() => {
|
967
|
+
setDeleteInProgress(false);
|
968
|
+
});
|
969
|
+
}
|
970
|
+
},
|
971
|
+
onCancel: () => {
|
972
|
+
setRoleToBeDeleted(void 0);
|
973
|
+
},
|
974
|
+
title: /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: "Delete?" }),
|
975
|
+
body: /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: "Are you sure you want to delete this role?" })
|
976
|
+
}
|
977
|
+
)
|
978
|
+
]
|
979
|
+
}
|
980
|
+
);
|
981
|
+
}
|
982
|
+
const RolesView = React.memo(
|
983
|
+
function RolesView2({ children }) {
|
984
|
+
const { collections } = core.useNavigationController();
|
985
|
+
const [dialogOpen, setDialogOpen] = React.useState(false);
|
986
|
+
const [selectedRole, setSelectedRole] = React.useState();
|
987
|
+
const { canEditRoles } = useUserManagement();
|
988
|
+
const onRoleClicked = React.useCallback((user) => {
|
989
|
+
setDialogOpen(true);
|
990
|
+
setSelectedRole(user);
|
991
|
+
}, []);
|
992
|
+
const handleClose = () => {
|
993
|
+
setSelectedRole(void 0);
|
994
|
+
setDialogOpen(false);
|
995
|
+
};
|
996
|
+
return /* @__PURE__ */ jsxRuntime.jsxs(ui.Container, { className: "w-full flex flex-col py-4 gap-4", maxWidth: "6xl", children: [
|
997
|
+
children,
|
998
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center mt-12", children: [
|
999
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1000
|
+
ui.Typography,
|
1001
|
+
{
|
1002
|
+
gutterBottom: true,
|
1003
|
+
variant: "h4",
|
1004
|
+
className: "flex-grow",
|
1005
|
+
component: "h4",
|
1006
|
+
children: "Roles"
|
1007
|
+
}
|
1008
|
+
),
|
1009
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.Tooltip, { title: !canEditRoles ? "Update plans to customise roles" : void 0, children: /* @__PURE__ */ jsxRuntime.jsx(
|
1010
|
+
ui.Button,
|
1011
|
+
{
|
1012
|
+
size: "large",
|
1013
|
+
disabled: !canEditRoles,
|
1014
|
+
startIcon: /* @__PURE__ */ jsxRuntime.jsx(ui.AddIcon, {}),
|
1015
|
+
onClick: () => setDialogOpen(true),
|
1016
|
+
children: "Add role"
|
1017
|
+
}
|
1018
|
+
) })
|
1019
|
+
] }),
|
1020
|
+
/* @__PURE__ */ jsxRuntime.jsx(RolesTable, { onRoleClicked, editable: Boolean(canEditRoles) }),
|
1021
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1022
|
+
RolesDetailsForm,
|
1023
|
+
{
|
1024
|
+
open: dialogOpen,
|
1025
|
+
role: selectedRole,
|
1026
|
+
editable: canEditRoles,
|
1027
|
+
collections,
|
1028
|
+
handleClose
|
1029
|
+
},
|
1030
|
+
selectedRole?.id ?? "new"
|
1031
|
+
)
|
1032
|
+
] });
|
1033
|
+
}
|
1034
|
+
);
|
1035
|
+
const UserYupSchema = Yup__namespace.object().shape({
|
1036
|
+
displayName: Yup__namespace.string().required("Required"),
|
1037
|
+
email: Yup__namespace.string().email().required("Required"),
|
1038
|
+
roles: Yup__namespace.array().min(1)
|
1039
|
+
});
|
1040
|
+
function canUserBeEdited(loggedUser, user, users, roles, prevUser) {
|
1041
|
+
const admins = users.filter((u) => u.roles?.map((r) => r.id).includes("admin"));
|
1042
|
+
const loggedUserIsAdmin = loggedUser.roles?.map((r) => r.id).includes("admin");
|
1043
|
+
const didRolesChange = !prevUser || !areRolesEqual(prevUser.roles ?? [], user.roles ?? []);
|
1044
|
+
if (didRolesChange && !loggedUserIsAdmin) {
|
1045
|
+
throw new Error("Only admins can change roles");
|
1046
|
+
}
|
1047
|
+
const adminRoleRemoved = prevUser && prevUser.roles?.map((r) => r.id).includes("admin") && !user.roles?.map((r) => r.id).includes("admin");
|
1048
|
+
if (adminRoleRemoved && admins.length === 1) {
|
1049
|
+
throw new Error("There must be at least one admin");
|
1050
|
+
}
|
1051
|
+
return true;
|
1052
|
+
}
|
1053
|
+
function UserDetailsForm({
|
1054
|
+
open,
|
1055
|
+
user: userProp,
|
1056
|
+
handleClose
|
1057
|
+
}) {
|
1058
|
+
const snackbarController = core.useSnackbarController();
|
1059
|
+
const {
|
1060
|
+
user: loggedInUser
|
1061
|
+
} = core.useAuthController();
|
1062
|
+
const {
|
1063
|
+
saveUser,
|
1064
|
+
users,
|
1065
|
+
roles
|
1066
|
+
} = useUserManagement();
|
1067
|
+
const isNewUser = !userProp;
|
1068
|
+
const onUserUpdated = React.useCallback((savedUser) => {
|
1069
|
+
if (!loggedInUser) {
|
1070
|
+
throw new Error("Logged user not found");
|
1071
|
+
}
|
1072
|
+
try {
|
1073
|
+
canUserBeEdited(loggedInUser, savedUser, users, roles, userProp);
|
1074
|
+
return saveUser(savedUser);
|
1075
|
+
} catch (e) {
|
1076
|
+
return Promise.reject(e);
|
1077
|
+
}
|
1078
|
+
}, [roles, saveUser, userProp, users, loggedInUser]);
|
1079
|
+
const formex$1 = formex.useCreateFormex({
|
1080
|
+
initialValues: userProp ?? {
|
1081
|
+
displayName: "",
|
1082
|
+
email: "",
|
1083
|
+
roles: roles.filter((r) => r.id === "editor")
|
1084
|
+
},
|
1085
|
+
validation: (values2) => {
|
1086
|
+
return UserYupSchema.validate(values2, { abortEarly: false }).then(() => {
|
1087
|
+
return {};
|
1088
|
+
}).catch((e) => {
|
1089
|
+
return e.inner.reduce((acc, error) => {
|
1090
|
+
acc[error.path] = error.message;
|
1091
|
+
return acc;
|
1092
|
+
}, {});
|
1093
|
+
});
|
1094
|
+
},
|
1095
|
+
onSubmit: (user, formexController) => {
|
1096
|
+
return onUserUpdated(user).then(() => {
|
1097
|
+
handleClose();
|
1098
|
+
formexController.resetForm({
|
1099
|
+
values: user
|
1100
|
+
});
|
1101
|
+
}).catch((e) => {
|
1102
|
+
snackbarController.open({
|
1103
|
+
type: "error",
|
1104
|
+
message: e.message
|
1105
|
+
});
|
1106
|
+
});
|
1107
|
+
}
|
1108
|
+
});
|
1109
|
+
const {
|
1110
|
+
isSubmitting,
|
1111
|
+
touched,
|
1112
|
+
handleChange,
|
1113
|
+
values,
|
1114
|
+
errors,
|
1115
|
+
setFieldValue,
|
1116
|
+
dirty,
|
1117
|
+
handleSubmit,
|
1118
|
+
submitCount
|
1119
|
+
} = formex$1;
|
1120
|
+
return /* @__PURE__ */ jsxRuntime.jsx(
|
1121
|
+
ui.Dialog,
|
1122
|
+
{
|
1123
|
+
open,
|
1124
|
+
onOpenChange: (open2) => !open2 ? handleClose() : void 0,
|
1125
|
+
maxWidth: "4xl",
|
1126
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(formex.Formex, { value: formex$1, children: /* @__PURE__ */ jsxRuntime.jsxs(
|
1127
|
+
"form",
|
1128
|
+
{
|
1129
|
+
onSubmit: handleSubmit,
|
1130
|
+
autoComplete: "off",
|
1131
|
+
noValidate: true,
|
1132
|
+
style: {
|
1133
|
+
display: "flex",
|
1134
|
+
flexDirection: "column",
|
1135
|
+
position: "relative",
|
1136
|
+
height: "100%"
|
1137
|
+
},
|
1138
|
+
children: [
|
1139
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.DialogContent, { className: "h-full flex-grow", children: [
|
1140
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1141
|
+
"div",
|
1142
|
+
{
|
1143
|
+
className: "flex flex-row pt-4 pb-4",
|
1144
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(
|
1145
|
+
ui.Typography,
|
1146
|
+
{
|
1147
|
+
variant: "h4",
|
1148
|
+
className: "flex-grow",
|
1149
|
+
children: "User"
|
1150
|
+
}
|
1151
|
+
)
|
1152
|
+
}
|
1153
|
+
),
|
1154
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-12 gap-8", children: [
|
1155
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "col-span-12", children: [
|
1156
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1157
|
+
ui.TextField,
|
1158
|
+
{
|
1159
|
+
name: "displayName",
|
1160
|
+
required: true,
|
1161
|
+
error: submitCount > 0 && Boolean(errors.displayName),
|
1162
|
+
value: values.displayName ?? "",
|
1163
|
+
onChange: handleChange,
|
1164
|
+
"aria-describedby": "name-helper-text",
|
1165
|
+
label: "Name"
|
1166
|
+
}
|
1167
|
+
),
|
1168
|
+
/* @__PURE__ */ jsxRuntime.jsx(core.FieldCaption, { children: submitCount > 0 && Boolean(errors.displayName) ? errors.displayName : "Name of this user" })
|
1169
|
+
] }),
|
1170
|
+
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "col-span-12", children: [
|
1171
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1172
|
+
ui.TextField,
|
1173
|
+
{
|
1174
|
+
required: true,
|
1175
|
+
error: submitCount > 0 && Boolean(errors.email),
|
1176
|
+
name: "email",
|
1177
|
+
value: values.email ?? "",
|
1178
|
+
onChange: handleChange,
|
1179
|
+
"aria-describedby": "email-helper-text",
|
1180
|
+
label: "Email"
|
1181
|
+
}
|
1182
|
+
),
|
1183
|
+
/* @__PURE__ */ jsxRuntime.jsx(core.FieldCaption, { children: submitCount > 0 && Boolean(errors.email) ? errors.email : "Email of this user" })
|
1184
|
+
] }),
|
1185
|
+
/* @__PURE__ */ jsxRuntime.jsx("div", { className: "col-span-12", children: /* @__PURE__ */ jsxRuntime.jsx(
|
1186
|
+
ui.MultiSelect,
|
1187
|
+
{
|
1188
|
+
label: "Roles",
|
1189
|
+
value: values.roles?.map((r) => r.id) ?? [],
|
1190
|
+
onMultiValueChange: (value) => setFieldValue("roles", value.map((id) => roles.find((r) => r.id === id))),
|
1191
|
+
renderValue: (value) => {
|
1192
|
+
const userRole = roles.find((role) => role.id === value);
|
1193
|
+
if (!userRole) return null;
|
1194
|
+
return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-wrap space-x-2 space-y-2", children: /* @__PURE__ */ jsxRuntime.jsx(RoleChip, { role: userRole }, userRole?.id) });
|
1195
|
+
},
|
1196
|
+
children: roles.map((userRole) => /* @__PURE__ */ jsxRuntime.jsx(
|
1197
|
+
ui.MultiSelectItem,
|
1198
|
+
{
|
1199
|
+
value: userRole.id,
|
1200
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(RoleChip, { role: userRole }, userRole?.id)
|
1201
|
+
},
|
1202
|
+
userRole.id
|
1203
|
+
))
|
1204
|
+
}
|
1205
|
+
) })
|
1206
|
+
] })
|
1207
|
+
] }),
|
1208
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.DialogActions, { children: [
|
1209
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1210
|
+
ui.Button,
|
1211
|
+
{
|
1212
|
+
variant: "text",
|
1213
|
+
onClick: () => {
|
1214
|
+
handleClose();
|
1215
|
+
},
|
1216
|
+
children: "Cancel"
|
1217
|
+
}
|
1218
|
+
),
|
1219
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1220
|
+
ui.LoadingButton,
|
1221
|
+
{
|
1222
|
+
variant: "filled",
|
1223
|
+
color: "primary",
|
1224
|
+
type: "submit",
|
1225
|
+
disabled: !dirty,
|
1226
|
+
loading: isSubmitting,
|
1227
|
+
startIcon: /* @__PURE__ */ jsxRuntime.jsx(ui.DoneIcon, {}),
|
1228
|
+
children: isNewUser ? "Create user" : "Update"
|
1229
|
+
}
|
1230
|
+
)
|
1231
|
+
] })
|
1232
|
+
]
|
1233
|
+
}
|
1234
|
+
) })
|
1235
|
+
}
|
1236
|
+
);
|
1237
|
+
}
|
1238
|
+
function UsersTable({ onUserClicked }) {
|
1239
|
+
const {
|
1240
|
+
users,
|
1241
|
+
saveUser,
|
1242
|
+
deleteUser
|
1243
|
+
} = useUserManagement();
|
1244
|
+
const authController = core.useAuthController();
|
1245
|
+
const snackbarController = core.useSnackbarController();
|
1246
|
+
const customizationController = core.useCustomizationController();
|
1247
|
+
const dateUtilsLocale = customizationController?.locale ? locales__namespace[customizationController?.locale] : void 0;
|
1248
|
+
const dateFormat = customizationController?.dateTimeFormat ?? core.defaultDateFormat;
|
1249
|
+
const [userToBeDeleted, setUserToBeDeleted] = React.useState(void 0);
|
1250
|
+
const [deleteInProgress, setDeleteInProgress] = React.useState(false);
|
1251
|
+
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "overflow-auto", children: [
|
1252
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.Table, { children: [
|
1253
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.TableHeader, { children: [
|
1254
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { className: "truncate w-16" }),
|
1255
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { children: "ID" }),
|
1256
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { children: "Email" }),
|
1257
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { children: "Name" }),
|
1258
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { children: "Roles" }),
|
1259
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { children: "Created on" })
|
1260
|
+
] }),
|
1261
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.TableBody, { children: [
|
1262
|
+
users && users.map((user) => {
|
1263
|
+
const userRoles = user.roles;
|
1264
|
+
const formattedDate = user.created_on ? dateFns.format(user.created_on, dateFormat, { locale: dateUtilsLocale }) : "";
|
1265
|
+
return /* @__PURE__ */ jsxRuntime.jsxs(
|
1266
|
+
ui.TableRow,
|
1267
|
+
{
|
1268
|
+
onClick: () => {
|
1269
|
+
onUserClicked(user);
|
1270
|
+
},
|
1271
|
+
children: [
|
1272
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { className: "w-10", children: /* @__PURE__ */ jsxRuntime.jsx(ui.Tooltip, { title: "Delete this user", children: /* @__PURE__ */ jsxRuntime.jsx(
|
1273
|
+
ui.IconButton,
|
1274
|
+
{
|
1275
|
+
size: "small",
|
1276
|
+
onClick: (event) => {
|
1277
|
+
event.stopPropagation();
|
1278
|
+
return setUserToBeDeleted(user);
|
1279
|
+
},
|
1280
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(ui.DeleteIcon, {})
|
1281
|
+
}
|
1282
|
+
) }) }),
|
1283
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { children: user.uid }),
|
1284
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { children: user.email }),
|
1285
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { className: "font-medium align-left", children: user.displayName }),
|
1286
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { className: "align-left", children: userRoles ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-wrap gap-2", children: userRoles.map(
|
1287
|
+
(userRole) => /* @__PURE__ */ jsxRuntime.jsx(RoleChip, { role: userRole }, userRole?.id)
|
1288
|
+
) }) : null }),
|
1289
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { children: formattedDate })
|
1290
|
+
]
|
1291
|
+
},
|
1292
|
+
"row_" + user.uid
|
1293
|
+
);
|
1294
|
+
}),
|
1295
|
+
(!users || users.length === 0) && /* @__PURE__ */ jsxRuntime.jsx(ui.TableRow, { children: /* @__PURE__ */ jsxRuntime.jsx(ui.TableCell, { colspan: 6, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.CenteredView, { className: "flex flex-col gap-4 my-8 items-center", children: [
|
1296
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.Typography, { variant: "label", children: "There are no users yet" }),
|
1297
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1298
|
+
ui.Button,
|
1299
|
+
{
|
1300
|
+
variant: "outlined",
|
1301
|
+
onClick: () => {
|
1302
|
+
if (!authController.user?.uid) {
|
1303
|
+
throw Error("UsersTable, authController misconfiguration");
|
1304
|
+
}
|
1305
|
+
saveUser({
|
1306
|
+
uid: authController.user?.uid,
|
1307
|
+
email: authController.user?.email,
|
1308
|
+
displayName: authController.user?.displayName,
|
1309
|
+
photoURL: authController.user?.photoURL,
|
1310
|
+
providerId: authController.user?.providerId,
|
1311
|
+
isAnonymous: authController.user?.isAnonymous,
|
1312
|
+
roles: [{ id: "admin", name: "Admin" }],
|
1313
|
+
created_on: /* @__PURE__ */ new Date()
|
1314
|
+
}).then(() => {
|
1315
|
+
snackbarController.open({
|
1316
|
+
type: "success",
|
1317
|
+
message: "User added successfully"
|
1318
|
+
});
|
1319
|
+
}).catch((error) => {
|
1320
|
+
snackbarController.open({
|
1321
|
+
type: "error",
|
1322
|
+
message: "Error adding user: " + error.message
|
1323
|
+
});
|
1324
|
+
});
|
1325
|
+
},
|
1326
|
+
children: "Add the logged user as an admin"
|
1327
|
+
}
|
1328
|
+
)
|
1329
|
+
] }) }) })
|
1330
|
+
] })
|
1331
|
+
] }),
|
1332
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1333
|
+
core.DeleteConfirmationDialog,
|
1334
|
+
{
|
1335
|
+
open: Boolean(userToBeDeleted),
|
1336
|
+
loading: deleteInProgress,
|
1337
|
+
onAccept: () => {
|
1338
|
+
if (userToBeDeleted) {
|
1339
|
+
setDeleteInProgress(true);
|
1340
|
+
deleteUser(userToBeDeleted).then(() => {
|
1341
|
+
setUserToBeDeleted(void 0);
|
1342
|
+
}).catch((error) => {
|
1343
|
+
snackbarController.open({
|
1344
|
+
type: "error",
|
1345
|
+
message: "Error deleting user: " + error.message
|
1346
|
+
});
|
1347
|
+
}).finally(() => {
|
1348
|
+
setDeleteInProgress(false);
|
1349
|
+
});
|
1350
|
+
}
|
1351
|
+
},
|
1352
|
+
onCancel: () => {
|
1353
|
+
setUserToBeDeleted(void 0);
|
1354
|
+
},
|
1355
|
+
title: /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: "Delete?" }),
|
1356
|
+
body: /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: "Are you sure you want to delete this user?" })
|
1357
|
+
}
|
1358
|
+
)
|
1359
|
+
] });
|
1360
|
+
}
|
1361
|
+
const UsersView = function UsersView2({ children }) {
|
1362
|
+
const [dialogOpen, setDialogOpen] = React.useState();
|
1363
|
+
const [selectedUser, setSelectedUser] = React.useState();
|
1364
|
+
const { users, usersLimit } = useUserManagement();
|
1365
|
+
const reachedUsersLimit = usersLimit !== void 0 && (users && users.length >= usersLimit);
|
1366
|
+
const onUserClicked = React.useCallback((user) => {
|
1367
|
+
setSelectedUser(user);
|
1368
|
+
setDialogOpen(true);
|
1369
|
+
}, []);
|
1370
|
+
const handleClose = React.useCallback(() => {
|
1371
|
+
setDialogOpen(false);
|
1372
|
+
setSelectedUser(void 0);
|
1373
|
+
}, []);
|
1374
|
+
return /* @__PURE__ */ jsxRuntime.jsxs(ui.Container, { className: "w-full flex flex-col py-4 gap-4", maxWidth: "6xl", children: [
|
1375
|
+
children,
|
1376
|
+
/* @__PURE__ */ jsxRuntime.jsxs(
|
1377
|
+
"div",
|
1378
|
+
{
|
1379
|
+
className: "flex items-center mt-12",
|
1380
|
+
children: [
|
1381
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1382
|
+
ui.Typography,
|
1383
|
+
{
|
1384
|
+
gutterBottom: true,
|
1385
|
+
variant: "h4",
|
1386
|
+
className: "flex-grow",
|
1387
|
+
component: "h4",
|
1388
|
+
children: "Users"
|
1389
|
+
}
|
1390
|
+
),
|
1391
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1392
|
+
ui.Button,
|
1393
|
+
{
|
1394
|
+
size: "large",
|
1395
|
+
disabled: reachedUsersLimit,
|
1396
|
+
startIcon: /* @__PURE__ */ jsxRuntime.jsx(ui.AddIcon, {}),
|
1397
|
+
onClick: () => setDialogOpen(true),
|
1398
|
+
children: "Add user"
|
1399
|
+
}
|
1400
|
+
)
|
1401
|
+
]
|
1402
|
+
}
|
1403
|
+
),
|
1404
|
+
/* @__PURE__ */ jsxRuntime.jsx(UsersTable, { onUserClicked }),
|
1405
|
+
/* @__PURE__ */ jsxRuntime.jsx(
|
1406
|
+
UserDetailsForm,
|
1407
|
+
{
|
1408
|
+
open: dialogOpen ?? false,
|
1409
|
+
user: selectedUser,
|
1410
|
+
handleClose
|
1411
|
+
},
|
1412
|
+
selectedUser?.uid ?? "new"
|
1413
|
+
)
|
1414
|
+
] });
|
1415
|
+
};
|
1416
|
+
function useUserManagementPlugin({ userManagement }) {
|
1417
|
+
const noUsers = userManagement.users.length === 0;
|
1418
|
+
const noRoles = userManagement.roles.length === 0;
|
1419
|
+
return {
|
1420
|
+
key: "user_management",
|
1421
|
+
loading: userManagement.loading,
|
1422
|
+
homePage: {
|
1423
|
+
additionalChildrenStart: noUsers || noRoles ? /* @__PURE__ */ jsxRuntime.jsx(
|
1424
|
+
IntroWidget,
|
1425
|
+
{
|
1426
|
+
noUsers,
|
1427
|
+
noRoles,
|
1428
|
+
userManagement
|
1429
|
+
}
|
1430
|
+
) : void 0
|
1431
|
+
},
|
1432
|
+
provider: {
|
1433
|
+
Component: UserManagementProvider,
|
1434
|
+
props: {
|
1435
|
+
userManagement
|
1436
|
+
}
|
1437
|
+
}
|
1438
|
+
};
|
1439
|
+
}
|
1440
|
+
function IntroWidget({
|
1441
|
+
noUsers,
|
1442
|
+
noRoles,
|
1443
|
+
userManagement
|
1444
|
+
}) {
|
1445
|
+
const authController = core.useAuthController();
|
1446
|
+
const snackbarController = core.useSnackbarController();
|
1447
|
+
const buttonLabel = noUsers && noRoles ? "Create default roles and add current user as admin" : noUsers ? "Add current user as admin" : noRoles ? "Create default roles" : void 0;
|
1448
|
+
return /* @__PURE__ */ jsxRuntime.jsxs(
|
1449
|
+
ui.Paper,
|
1450
|
+
{
|
1451
|
+
className: "my-4 flex flex-col px-4 py-6 bg-white dark:bg-slate-800 gap-2",
|
1452
|
+
children: [
|
1453
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.Typography, { variant: "subtitle2", className: "uppercase", children: "Create your users and roles" }),
|
1454
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.Typography, { children: "You have no users or roles defined. You can create default roles and add the current user as admin." }),
|
1455
|
+
/* @__PURE__ */ jsxRuntime.jsxs(ui.Button, { onClick: () => {
|
1456
|
+
if (!authController.user?.uid) {
|
1457
|
+
throw Error("UsersTable, authController misconfiguration");
|
1458
|
+
}
|
1459
|
+
if (noUsers) {
|
1460
|
+
userManagement.saveUser({
|
1461
|
+
uid: authController.user?.uid,
|
1462
|
+
email: authController.user?.email,
|
1463
|
+
displayName: authController.user?.displayName,
|
1464
|
+
photoURL: authController.user?.photoURL,
|
1465
|
+
providerId: authController.user?.providerId,
|
1466
|
+
isAnonymous: authController.user?.isAnonymous,
|
1467
|
+
roles: [{
|
1468
|
+
id: "admin",
|
1469
|
+
name: "Admin"
|
1470
|
+
}],
|
1471
|
+
created_on: /* @__PURE__ */ new Date()
|
1472
|
+
}).then(() => {
|
1473
|
+
snackbarController.open({
|
1474
|
+
type: "success",
|
1475
|
+
message: "User added successfully"
|
1476
|
+
});
|
1477
|
+
}).catch((error) => {
|
1478
|
+
snackbarController.open({
|
1479
|
+
type: "error",
|
1480
|
+
message: "Error adding user: " + error.message
|
1481
|
+
});
|
1482
|
+
});
|
1483
|
+
}
|
1484
|
+
if (noRoles) {
|
1485
|
+
DEFAULT_ROLES.forEach((role) => {
|
1486
|
+
userManagement.saveRole(role);
|
1487
|
+
});
|
1488
|
+
}
|
1489
|
+
}, children: [
|
1490
|
+
/* @__PURE__ */ jsxRuntime.jsx(ui.AddIcon, {}),
|
1491
|
+
buttonLabel
|
1492
|
+
] })
|
1493
|
+
]
|
1494
|
+
}
|
1495
|
+
);
|
1496
|
+
}
|
1497
|
+
const userManagementAdminViews = [
|
1498
|
+
{
|
1499
|
+
path: "users",
|
1500
|
+
name: "CMS Users",
|
1501
|
+
group: "Admin",
|
1502
|
+
icon: "face",
|
1503
|
+
view: /* @__PURE__ */ jsxRuntime.jsx(UsersView, {})
|
1504
|
+
},
|
1505
|
+
{
|
1506
|
+
path: "roles",
|
1507
|
+
name: "Roles",
|
1508
|
+
group: "Admin",
|
1509
|
+
icon: "gpp_good",
|
1510
|
+
view: /* @__PURE__ */ jsxRuntime.jsx(RolesView, {})
|
1511
|
+
}
|
1512
|
+
];
|
1513
|
+
exports2.IntroWidget = IntroWidget;
|
1514
|
+
exports2.RESERVED_GROUPS = RESERVED_GROUPS;
|
1515
|
+
exports2.RoleChip = RoleChip;
|
1516
|
+
exports2.RoleYupSchema = RoleYupSchema;
|
1517
|
+
exports2.RolesDetailsForm = RolesDetailsForm;
|
1518
|
+
exports2.RolesTable = RolesTable;
|
1519
|
+
exports2.RolesView = RolesView;
|
1520
|
+
exports2.UserDetailsForm = UserDetailsForm;
|
1521
|
+
exports2.UserManagementContext = UserManagementContext;
|
1522
|
+
exports2.UserManagementProvider = UserManagementProvider;
|
1523
|
+
exports2.UserYupSchema = UserYupSchema;
|
1524
|
+
exports2.UsersTable = UsersTable;
|
1525
|
+
exports2.UsersView = UsersView;
|
1526
|
+
exports2.areRolesEqual = areRolesEqual;
|
1527
|
+
exports2.cacheDelegatedLoginToken = cacheDelegatedLoginToken;
|
1528
|
+
exports2.clearDelegatedLoginTokensCache = clearDelegatedLoginTokensCache;
|
1529
|
+
exports2.darkenColor = darkenColor;
|
1530
|
+
exports2.getDelegatedLoginTokenFromCache = getDelegatedLoginTokenFromCache;
|
1531
|
+
exports2.getUserRoles = getUserRoles;
|
1532
|
+
exports2.hexToRgbaWithOpacity = hexToRgbaWithOpacity;
|
1533
|
+
exports2.resolveUserRolePermissions = resolveUserRolePermissions;
|
1534
|
+
exports2.useFirestoreUserManagement = useFirestoreUserManagement;
|
1535
|
+
exports2.useUserManagement = useUserManagement;
|
1536
|
+
exports2.useUserManagementPlugin = useUserManagementPlugin;
|
1537
|
+
exports2.userManagementAdminViews = userManagementAdminViews;
|
1538
|
+
Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
|
1539
|
+
});
|
2
1540
|
//# sourceMappingURL=index.umd.js.map
|