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