@firecms/user_management 3.0.0-canary.23 → 3.0.0-canary.231

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.
@@ -0,0 +1,333 @@
1
+ import React, { useCallback, useEffect } from "react";
2
+ import equal from "react-fast-compare"
3
+
4
+ import { UserManagement } from "../types";
5
+ import {
6
+ AuthController,
7
+ Authenticator,
8
+ DataSourceDelegate,
9
+ Entity,
10
+ PermissionsBuilder,
11
+ removeUndefined,
12
+ Role,
13
+ User
14
+ } from "@firecms/core";
15
+ import { resolveUserRolePermissions } from "../utils";
16
+
17
+ type UserWithRoleIds<USER extends User = any> = Omit<USER, "roles"> & { roles: string[] };
18
+
19
+ export interface UserManagementParams<CONTROLLER extends AuthController<any> = AuthController<any>> {
20
+
21
+ authController: CONTROLLER;
22
+
23
+ /**
24
+ * The delegate in charge of persisting the data.
25
+ */
26
+ dataSourceDelegate?: DataSourceDelegate;
27
+
28
+ /**
29
+ * Path where the plugin users configuration is stored.
30
+ * Default: __FIRECMS/config/users
31
+ * You can specify a different path if you want to store the user management configuration in a different place.
32
+ * Please keep in mind that the FireCMS users are not necessarily the same as the Firebase users (but they can be).
33
+ * The path should be relative to the root of the database, and should always have an odd number of segments.
34
+ */
35
+ usersPath?: string;
36
+
37
+ /**
38
+ * Path where the plugin roles configuration is stored.
39
+ * Default: __FIRECMS/config/roles
40
+ */
41
+ rolesPath?: string;
42
+
43
+ /**
44
+ * If there are no roles in the database, provide a button to create the default roles.
45
+ */
46
+ allowDefaultRolesCreation?: boolean;
47
+
48
+ /**
49
+ * Include the collection config permissions in the user management system.
50
+ */
51
+ includeCollectionConfigPermissions?: boolean;
52
+
53
+ }
54
+
55
+ /**
56
+ * This hook is used to build a user management object that can be used to
57
+ * manage users and roles in a Firestore backend.
58
+ * @param authController
59
+ * @param dataSourceDelegate
60
+ * @param usersPath
61
+ * @param rolesPath
62
+ * @param allowDefaultRolesCreation
63
+ * @param includeCollectionConfigPermissions
64
+ */
65
+ export function useBuildUserManagement<CONTROLLER extends AuthController<any> = AuthController<any>,
66
+ USER extends User = CONTROLLER extends AuthController<infer U> ? U : any>
67
+ ({
68
+ authController,
69
+ dataSourceDelegate,
70
+ usersPath = "__FIRECMS/config/users",
71
+ rolesPath = "__FIRECMS/config/roles",
72
+ allowDefaultRolesCreation,
73
+ includeCollectionConfigPermissions
74
+ }: UserManagementParams<CONTROLLER>): UserManagement<USER> & CONTROLLER {
75
+
76
+ if (!authController) {
77
+ throw Error("useBuildUserManagement: You need to provide an authController since version 3.0.0-beta.11. Check https://firecms.co/docs/pro/migrating_from_v3_beta");
78
+ }
79
+
80
+ const [rolesLoading, setRolesLoading] = React.useState<boolean>(true);
81
+ const [usersLoading, setUsersLoading] = React.useState<boolean>(true);
82
+ const [roles, setRoles] = React.useState<Role[]>([]);
83
+ const [usersWithRoleIds, setUsersWithRoleIds] = React.useState<UserWithRoleIds<USER>[]>([]);
84
+
85
+ const users = usersWithRoleIds.map(u => ({
86
+ ...u,
87
+ roles: roles.filter(r => u.roles?.includes(r.id))
88
+ }) as USER);
89
+
90
+ const [rolesError, setRolesError] = React.useState<Error | undefined>();
91
+ const [usersError, setUsersError] = React.useState<Error | undefined>();
92
+
93
+ const _usersLoading = usersLoading;
94
+ const _rolesLoading = rolesLoading;
95
+
96
+ const loading = _rolesLoading || _usersLoading;
97
+
98
+ useEffect(() => {
99
+ if (!dataSourceDelegate || !rolesPath) return;
100
+ if (dataSourceDelegate.initialised !== undefined && !dataSourceDelegate.initialised) return;
101
+ if (authController?.initialLoading) return;
102
+ // if (authController.user === null) {
103
+ // setRolesLoading(false);
104
+ // return;
105
+ // }
106
+
107
+ setRolesLoading(true);
108
+ return dataSourceDelegate.listenCollection?.({
109
+ path: rolesPath,
110
+ onUpdate(entities: Entity<any>[]): void {
111
+ setRolesError(undefined);
112
+ try {
113
+ const newRoles = entityToRoles(entities);
114
+ if (!equal(newRoles, roles)) {
115
+ setRoles(newRoles);
116
+ }
117
+ } catch (e) {
118
+ setRoles([]);
119
+ console.error("Error loading roles", e);
120
+ setRolesError(e as Error);
121
+ }
122
+ setRolesLoading(false);
123
+ },
124
+ onError(e: any): void {
125
+ setRoles([]);
126
+ console.error("Error loading roles", e);
127
+ setRolesError(e);
128
+ setRolesLoading(false);
129
+ }
130
+ });
131
+
132
+ }, [dataSourceDelegate?.initialised, authController?.initialLoading, authController?.user?.uid, rolesPath]);
133
+
134
+ useEffect(() => {
135
+ if (!dataSourceDelegate || !usersPath) return;
136
+ if (dataSourceDelegate.initialised !== undefined && !dataSourceDelegate.initialised) {
137
+ return;
138
+ }
139
+ if (authController?.initialLoading) {
140
+ return;
141
+ }
142
+
143
+ setUsersLoading(true);
144
+ return dataSourceDelegate.listenCollection?.({
145
+ path: usersPath,
146
+ onUpdate(entities: Entity<any>[]): void {
147
+ console.debug("Updating users", entities);
148
+ setUsersError(undefined);
149
+ try {
150
+ const newUsers = entitiesToUsers(entities);
151
+ // if (!equal(newUsers, usersWithRoleIds))
152
+ setUsersWithRoleIds(newUsers);
153
+ } catch (e) {
154
+ setUsersWithRoleIds([]);
155
+ console.error("Error loading users", e);
156
+ setUsersError(e as Error);
157
+ }
158
+ setUsersLoading(false);
159
+ },
160
+ onError(e: any): void {
161
+ console.error("Error loading users", e);
162
+ setUsersWithRoleIds([]);
163
+ setUsersError(e);
164
+ setUsersLoading(false);
165
+ }
166
+ });
167
+
168
+ }, [dataSourceDelegate?.initialised, authController?.initialLoading, authController?.user?.uid, usersPath]);
169
+
170
+ const saveUser = useCallback(async (user: USER): Promise<USER> => {
171
+ if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
172
+ if (!usersPath) throw Error("useBuildUserManagement Firestore not initialised");
173
+
174
+ console.debug("Persisting user", user);
175
+
176
+ const roleIds = user.roles?.map(r => r.id);
177
+ const email = user.email?.toLowerCase().trim();
178
+ if (!email) throw Error("Email is required");
179
+
180
+ const userExists = users.find(u => u.email?.toLowerCase() === email);
181
+ const data = {
182
+ ...user,
183
+ roles: roleIds ?? []
184
+ };
185
+ if (!userExists) {
186
+ // @ts-ignore
187
+ data.created_on = new Date();
188
+ }
189
+
190
+ return dataSourceDelegate.saveEntity({
191
+ status: "existing",
192
+ path: usersPath,
193
+ entityId: email,
194
+ values: removeUndefined(data)
195
+ }).then(() => user);
196
+ }, [usersPath, dataSourceDelegate?.initialised]);
197
+
198
+ const saveRole = useCallback((role: Role): Promise<void> => {
199
+ if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
200
+ if (!rolesPath) throw Error("useBuildUserManagement Firestore not initialised");
201
+ console.debug("Persisting role", role);
202
+ const {
203
+ id,
204
+ ...roleData
205
+ } = role;
206
+ return dataSourceDelegate.saveEntity({
207
+ status: "existing",
208
+ path: rolesPath,
209
+ entityId: id,
210
+ values: removeUndefined(roleData)
211
+ }).then(() => {
212
+ return;
213
+ });
214
+ }, [rolesPath, dataSourceDelegate?.initialised]);
215
+
216
+ const deleteUser = useCallback(async (user: User): Promise<void> => {
217
+ if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
218
+ if (!usersPath) throw Error("useBuildUserManagement Firestore not initialised");
219
+ console.debug("Deleting", user);
220
+ const { uid } = user;
221
+ const entity: Entity<any> = {
222
+ path: usersPath,
223
+ id: uid,
224
+ values: {}
225
+ };
226
+ await dataSourceDelegate.deleteEntity({ entity })
227
+ }, [usersPath, dataSourceDelegate?.initialised]);
228
+
229
+ const deleteRole = useCallback(async (role: Role): Promise<void> => {
230
+ if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
231
+ if (!rolesPath) throw Error("useBuildUserManagement Firestore not initialised");
232
+ console.debug("Deleting", role);
233
+ const { id } = role;
234
+ const entity: Entity<any> = {
235
+ path: rolesPath,
236
+ id: id,
237
+ values: {}
238
+ };
239
+ await dataSourceDelegate.deleteEntity({ entity })
240
+ }, [rolesPath, dataSourceDelegate?.initialised]);
241
+
242
+ const collectionPermissions: PermissionsBuilder = useCallback(({
243
+ collection,
244
+ user
245
+ }) =>
246
+ resolveUserRolePermissions({
247
+ collection,
248
+ user
249
+ }), []);
250
+
251
+ const defineRolesFor: ((user: User) => Role[] | undefined) = useCallback((user) => {
252
+ if (!usersWithRoleIds) throw Error("Users not loaded");
253
+ const users = usersWithRoleIds.map(u => ({
254
+ ...u,
255
+ roles: roles.filter(r => u.roles?.includes(r.id))
256
+ }) as User);
257
+ const mgmtUser = users.find(u => u.email?.toLowerCase() === user?.email?.toLowerCase());
258
+ return mgmtUser?.roles;
259
+ }, [roles, usersWithRoleIds]);
260
+
261
+ const authenticator: Authenticator<USER> = useCallback(({ user }) => {
262
+ if (loading) {
263
+ return false;
264
+ }
265
+
266
+ if (users.length === 0) {
267
+ console.warn("No users created yet");
268
+ return true; // If there are no users created yet, we allow access to every user
269
+ }
270
+
271
+ const mgmtUser = users.find(u => u.email?.toLowerCase() === user?.email?.toLowerCase());
272
+ if (mgmtUser) {
273
+ console.debug("User found in user management system", mgmtUser);
274
+ return true;
275
+ }
276
+
277
+ throw Error("Could not find a user with the provided email in the user management system.");
278
+ }, [loading, users]);
279
+
280
+ const userRoles = authController.user ? defineRolesFor(authController.user) : undefined;
281
+ const isAdmin = (userRoles ?? []).some(r => r.id === "admin");
282
+
283
+ const userRoleIds = userRoles?.map(r => r.id);
284
+ useEffect(() => {
285
+ console.debug("Setting roles", userRoles);
286
+ authController.setUserRoles?.(userRoles ?? []);
287
+ }, [userRoleIds]);
288
+
289
+ return {
290
+ loading,
291
+ roles,
292
+ users,
293
+ saveUser,
294
+ saveRole,
295
+ rolesError,
296
+ deleteUser,
297
+ deleteRole,
298
+ usersError,
299
+ isAdmin,
300
+ allowDefaultRolesCreation: allowDefaultRolesCreation === undefined ? true : allowDefaultRolesCreation,
301
+ includeCollectionConfigPermissions: Boolean(includeCollectionConfigPermissions),
302
+ collectionPermissions,
303
+ defineRolesFor,
304
+ authenticator,
305
+ ...authController,
306
+ initialLoading: authController.initialLoading || loading,
307
+ userRoles: userRoles,
308
+ user: authController.user ? {
309
+ ...authController.user,
310
+ roles: userRoles
311
+ } : null
312
+ }
313
+ }
314
+
315
+ const entitiesToUsers = (docs: Entity<Omit<UserWithRoleIds, "id">>[]): (UserWithRoleIds)[] => {
316
+ return docs.map((doc) => {
317
+ const data = doc.values as any;
318
+ const newVar = {
319
+ uid: doc.id,
320
+ ...data,
321
+ created_on: data?.created_on,
322
+ updated_on: data?.updated_on
323
+ };
324
+ return newVar as (UserWithRoleIds);
325
+ });
326
+ }
327
+
328
+ const entityToRoles = (entities: Entity<Omit<Role, "id">>[]): Role[] => {
329
+ return entities.map((doc) => ({
330
+ id: doc.id,
331
+ ...doc.values
332
+ } as Role));
333
+ }
@@ -2,6 +2,8 @@ import { Authenticator, PermissionsBuilder, Role, User } from "@firecms/core";
2
2
 
3
3
  export type UserManagement<USER extends User = User> = {
4
4
 
5
+ authenticator?: Authenticator<USER>;
6
+
5
7
  loading: boolean;
6
8
 
7
9
  users: USER[];
@@ -13,14 +15,9 @@ export type UserManagement<USER extends User = User> = {
13
15
  deleteRole: (role: Role) => Promise<void>;
14
16
 
15
17
  /**
16
- * Maximum number of users that can be created.
17
- */
18
- usersLimit?: number;
19
-
20
- /**
21
- * Can the logged user edit roles?
18
+ * Is the logged user Admin?
22
19
  */
23
- canEditRoles?: boolean;
20
+ isAdmin?: boolean;
24
21
 
25
22
  /**
26
23
  * Include a button to create default roles, in case there are no roles in the system.
@@ -42,12 +39,9 @@ export type UserManagement<USER extends User = User> = {
42
39
  * Define the roles for a given user. You will typically want to plug this into your auth controller.
43
40
  * @param user
44
41
  */
45
- defineRolesFor: (user: User) => Promise<Role[]> | Role[] | undefined;
42
+ defineRolesFor: (user: User) => Promise<Role[] | undefined> | Role[] | undefined;
46
43
 
47
- /**
48
- * You can build an authenticator callback from the current configuration of the user management.
49
- * It will only allow access to users with the required roles.
50
- */
51
- authenticator?: Authenticator;
44
+ rolesError?: Error;
45
+ usersError?: Error;
52
46
 
53
47
  };
@@ -1,13 +1,28 @@
1
- import { FireCMSPlugin } from "@firecms/core";
1
+ import { FireCMSPlugin, useAuthController, User, useSnackbarController } from "@firecms/core";
2
2
  import { UserManagementProvider } from "./UserManagementProvider";
3
3
  import { UserManagement } from "./types";
4
+ import { AddIcon, Button, Paper, Typography } from "@firecms/ui";
5
+ import { DEFAULT_ROLES } from "./components/roles/default_roles";
4
6
 
5
- export function useUserManagementPlugin({ userManagement }: {
6
- userManagement: UserManagement,
7
+ export function useUserManagementPlugin<USER extends User = any>({ userManagement }: {
8
+ userManagement: UserManagement<USER>,
7
9
  }): FireCMSPlugin {
10
+
11
+ const noUsers = userManagement.users.length === 0;
12
+ const noRoles = userManagement.roles.length === 0;
13
+
8
14
  return {
9
15
  key: "user_management",
10
16
  loading: userManagement.loading,
17
+
18
+ homePage: {
19
+ additionalChildrenStart: noUsers || noRoles
20
+ ? <IntroWidget
21
+ noUsers={noUsers}
22
+ noRoles={noRoles}
23
+ userManagement={userManagement}/>
24
+ : undefined
25
+ },
11
26
  provider: {
12
27
  Component: UserManagementProvider,
13
28
  props: {
@@ -16,3 +31,74 @@ export function useUserManagementPlugin({ userManagement }: {
16
31
  }
17
32
  }
18
33
  }
34
+
35
+ export function IntroWidget({
36
+ noUsers,
37
+ noRoles,
38
+ userManagement
39
+ }: {
40
+ noUsers: boolean;
41
+ noRoles: boolean;
42
+ userManagement: UserManagement<any>;
43
+ }) {
44
+
45
+ const authController = useAuthController();
46
+ const snackbarController = useSnackbarController();
47
+
48
+ const buttonLabel = noUsers && noRoles
49
+ ? "Create default roles and add current user as admin"
50
+ : noUsers
51
+ ? "Add current user as admin"
52
+ : noRoles ? "Create default roles" : undefined;
53
+
54
+ return (
55
+ <Paper
56
+ className={"my-4 flex flex-col px-4 py-6 bg-white dark:bg-surface-accent-800 gap-2"}>
57
+ <Typography variant={"subtitle2"} className={"uppercase"}>Create your users and roles</Typography>
58
+ <Typography>
59
+ You have no users or roles defined. You can create default roles and add the current user as admin.
60
+ </Typography>
61
+ <Button onClick={() => {
62
+ if (!authController.user?.uid) {
63
+ throw Error("UsersTable, authController misconfiguration");
64
+ }
65
+ if (noUsers) {
66
+ userManagement.saveUser({
67
+ uid: authController.user?.uid,
68
+ email: authController.user?.email,
69
+ displayName: authController.user?.displayName,
70
+ photoURL: authController.user?.photoURL,
71
+ providerId: authController.user?.providerId,
72
+ isAnonymous: authController.user?.isAnonymous,
73
+ roles: [{
74
+ id: "admin",
75
+ name: "Admin"
76
+ }],
77
+ created_on: new Date()
78
+ })
79
+ .then(() => {
80
+ snackbarController.open({
81
+ type: "success",
82
+ message: "User added successfully"
83
+ })
84
+ })
85
+ .catch((error) => {
86
+ snackbarController.open({
87
+ type: "error",
88
+ message: "Error adding user: " + error.message
89
+ })
90
+ });
91
+ }
92
+ if (noRoles) {
93
+ DEFAULT_ROLES.forEach((role) => {
94
+ userManagement.saveRole(role);
95
+ });
96
+ }
97
+ }}>
98
+ <AddIcon/>
99
+ {buttonLabel}
100
+ </Button>
101
+ </Paper>
102
+ );
103
+
104
+ }
@@ -9,13 +9,13 @@ const DEFAULT_PERMISSIONS = {
9
9
  delete: false
10
10
  };
11
11
 
12
- export function resolveUserRolePermissions<UserType extends User>
12
+ export function resolveUserRolePermissions<USER extends User>
13
13
  ({
14
14
  collection,
15
15
  user
16
16
  }: {
17
17
  collection: EntityCollection<any>,
18
- user: UserType | null
18
+ user: USER | null
19
19
  }): Permissions {
20
20
 
21
21
  const roles = user?.roles;
@@ -45,13 +45,14 @@ export function resolveUserRolePermissions<UserType extends User>
45
45
  function resolveCollectionRole(role: Role, id: string): Permissions {
46
46
 
47
47
  const basePermissions = {
48
- read: role.isAdmin || role.defaultPermissions?.read,
49
- create: role.isAdmin || role.defaultPermissions?.create,
50
- edit: role.isAdmin || role.defaultPermissions?.edit,
51
- delete: role.isAdmin || role.defaultPermissions?.delete
48
+ read: (role.isAdmin || role.defaultPermissions?.read) ?? false,
49
+ create: (role.isAdmin || role.defaultPermissions?.create) ?? false,
50
+ edit: (role.isAdmin || role.defaultPermissions?.edit) ?? false,
51
+ delete: (role.isAdmin || role.defaultPermissions?.delete) ?? false
52
52
  };
53
- if (role.collectionPermissions && role.collectionPermissions[id]) {
54
- return mergePermissions(role.collectionPermissions[id], basePermissions);
53
+ const thisCollectionPermissions = role.collectionPermissions?.[id];
54
+ if (thisCollectionPermissions) {
55
+ return mergePermissions(thisCollectionPermissions, basePermissions);
55
56
  } else if (role.defaultPermissions) {
56
57
  return mergePermissions(role.defaultPermissions, basePermissions);
57
58
  } else {