@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.
@@ -1,271 +0,0 @@
1
- import React, { useCallback, useEffect, useRef } from "react";
2
- import {
3
- addDoc,
4
- collection,
5
- deleteDoc,
6
- doc,
7
- DocumentSnapshot,
8
- Firestore,
9
- getFirestore,
10
- onSnapshot,
11
- setDoc
12
- } from "firebase/firestore";
13
- import { FirebaseApp } from "firebase/app";
14
- import { UserManagement } from "../types";
15
- import { Authenticator, PermissionsBuilder, Role, User } from "@firecms/core";
16
- import { resolveUserRolePermissions } from "../utils";
17
-
18
- type UserWithRoleIds = User & { roles: string[] };
19
-
20
- export interface UserManagementParams {
21
- /**
22
- * The Firebase app to use for the user management. The config will be saved in the Firestore
23
- * collection indicated by `configPath`.
24
- */
25
- firebaseApp?: FirebaseApp;
26
- /**
27
- * Path where the plugin users configuration is stored.
28
- * Default: __FIRECMS/config/users
29
- * You can specify a different path if you want to store the user management configuration in a different place.
30
- * Please keep in mind that the FireCMS users are not necessarily the same as the Firebase users (but they can be).
31
- * The path should be relative to the root of the Firestore database, and should always have an odd number of segments.
32
- */
33
- usersPath?: string;
34
-
35
- /**
36
- * Path where the plugin roles configuration is stored.
37
- * Default: __FIRECMS/config/roles
38
- */
39
- rolesPath?: string;
40
-
41
- usersLimit?: number;
42
-
43
- canEditRoles?: boolean;
44
-
45
- /**
46
- * If there are no roles in the database, provide a button to create the default roles.
47
- */
48
- allowDefaultRolesCreation?: boolean;
49
-
50
- /**
51
- * Include the collection config permissions in the user management system.
52
- */
53
- includeCollectionConfigPermissions?: boolean;
54
-
55
- }
56
-
57
- /**
58
- * This hook is used to build a user management object that can be used to
59
- * manage users and roles in a Firestore backend.
60
- * @param backendFirebaseApp
61
- * @param usersPath
62
- * @param rolesPath
63
- * @param usersLimit
64
- * @param canEditRoles
65
- */
66
- export function useBuildFirestoreUserManagement({
67
- firebaseApp,
68
- usersPath = "__FIRECMS/config/users",
69
- rolesPath = "__FIRECMS/config/roles",
70
- usersLimit,
71
- canEditRoles = true,
72
- allowDefaultRolesCreation,
73
- includeCollectionConfigPermissions
74
- }: UserManagementParams): UserManagement {
75
-
76
- const firestoreRef = useRef<Firestore>();
77
-
78
- const [rolesLoading, setRolesLoading] = React.useState<boolean>(true);
79
- const [usersLoading, setUsersLoading] = React.useState<boolean>(true);
80
- const [roles, setRoles] = React.useState<Role[]>([]);
81
- const [usersWithRoleIds, setUsersWithRoleIds] = React.useState<UserWithRoleIds[]>([]);
82
-
83
- const users = usersWithRoleIds.map(u => ({
84
- ...u,
85
- roles: roles.filter(r => u.roles?.includes(r.id))
86
- }) as User);
87
-
88
- const [rolesError, setRolesError] = React.useState<Error | undefined>();
89
- const [usersError, setUsersError] = React.useState<Error | undefined>();
90
-
91
- const loading = rolesLoading || usersLoading;
92
-
93
- useEffect(() => {
94
- if (!firebaseApp) return;
95
- firestoreRef.current = getFirestore(firebaseApp);
96
- }, [firebaseApp]);
97
-
98
- useEffect(() => {
99
- if (!firebaseApp || !rolesPath) return;
100
- const firestore = getFirestore(firebaseApp);
101
-
102
- return onSnapshot(collection(firestore, rolesPath),
103
- {
104
- next: (snapshot) => {
105
- setRolesError(undefined);
106
- try {
107
- const newRoles = docsToRoles(snapshot.docs);
108
- setRoles(newRoles);
109
- } catch (e) {
110
- // console.error(e);
111
- setRolesError(e as Error);
112
- }
113
- setRolesLoading(false);
114
- },
115
- error: (e) => {
116
- setRolesError(e);
117
- setRolesLoading(false);
118
- }
119
- }
120
- );
121
- }, [firebaseApp, rolesPath]);
122
-
123
- useEffect(() => {
124
- if (!firebaseApp || !usersPath) return;
125
- const firestore = getFirestore(firebaseApp);
126
-
127
- return onSnapshot(collection(firestore, usersPath),
128
- {
129
- next: (snapshot) => {
130
- setUsersError(undefined);
131
- try {
132
- const newUsers = docsToUsers(snapshot.docs);
133
- setUsersWithRoleIds(newUsers);
134
- } catch (e) {
135
- setUsersError(e as Error);
136
- }
137
- setUsersLoading(false);
138
- },
139
- error: (e) => {
140
- setUsersError(e);
141
- setUsersLoading(false);
142
- }
143
- }
144
- );
145
- }, [firebaseApp, usersPath]);
146
-
147
- const saveUser = useCallback(async (user: User): Promise<User> => {
148
- const firestore = firestoreRef.current;
149
- if (!firestore || !usersPath) throw Error("useFirestoreConfigurationPersistence Firestore not initialised");
150
- console.debug("Persisting user", user);
151
- const roleIds = user.roles?.map(r => r.id);
152
- const {
153
- uid,
154
- ...userData
155
- } = user;
156
- const data = {
157
- ...userData,
158
- roles: roleIds
159
- };
160
- if (uid) {
161
- return setDoc(doc(firestore, usersPath, uid), data, { merge: true }).then(() => user);
162
- } else {
163
- return addDoc(collection(firestore, usersPath), data).then(() => user);
164
- }
165
- }, [usersPath]);
166
-
167
- const saveRole = useCallback((role: Role): Promise<void> => {
168
- const firestore = firestoreRef.current;
169
- if (!firestore || !rolesPath) throw Error("useFirestoreConfigurationPersistence Firestore not initialised");
170
- console.debug("Persisting role", role);
171
- const {
172
- id,
173
- ...roleData
174
- } = role;
175
- const ref = doc(firestore, rolesPath, id);
176
- return setDoc(ref, roleData, { merge: true });
177
- }, [rolesPath]);
178
-
179
- const deleteUser = useCallback(async (user: User): Promise<void> => {
180
- const firestore = firestoreRef.current;
181
- if (!firestore || !usersPath) throw Error("useFirestoreConfigurationPersistence Firestore not initialised");
182
- console.debug("Deleting", user);
183
- const { uid } = user;
184
- return deleteDoc(doc(firestore, usersPath, uid));
185
- }, [usersPath]);
186
-
187
- const deleteRole = useCallback((role: Role): Promise<void> => {
188
- const firestore = firestoreRef.current;
189
- if (!firestore || !rolesPath) throw Error("useFirestoreConfigurationPersistence Firestore not initialised");
190
- console.debug("Deleting", role);
191
- const { id } = role;
192
- const ref = doc(firestore, rolesPath, id);
193
- return deleteDoc(ref);
194
- }, [rolesPath]);
195
-
196
- const collectionPermissions: PermissionsBuilder = useCallback(({
197
- collection,
198
- user
199
- }) => resolveUserRolePermissions({
200
- collection,
201
- user
202
- }), []);
203
-
204
- const userIds = users.map(u => u.uid);
205
- const defineRolesFor: ((user: User) => Role[] | undefined) = useCallback((user) => {
206
- if (!users) throw Error("Users not loaded");
207
- const mgmtUser = users.find(u => u.email?.toLowerCase() === user?.email?.toLowerCase());
208
- return mgmtUser?.roles;
209
- }, [userIds]);
210
-
211
- const authenticator: Authenticator = useCallback(({ user }) => {
212
- console.log("Authenticating user", user);
213
- // return true;"
214
-
215
- // console.log("authentication", user, userManagement);
216
- if (loading) {
217
- console.log("User management is still loading");
218
- return false;
219
- }
220
-
221
- // This is an example of how you can link the access system to the user management plugin
222
- if (users.length === 0) {
223
- return true; // If there are no users created yet, we allow access to every user
224
- }
225
-
226
- const mgmtUser = users.find(u => u.email?.toLowerCase() === user?.email?.toLowerCase());
227
- if (mgmtUser) {
228
- // authController.setRoles(mgmtUser.roles ?? [])
229
- return true;
230
- }
231
-
232
- throw Error("Could not find a user with the provided email");
233
- }, [loading, users])
234
-
235
- return {
236
- loading,
237
- roles,
238
- users,
239
- saveUser,
240
- saveRole,
241
- deleteUser,
242
- deleteRole,
243
- usersLimit,
244
- canEditRoles: canEditRoles === undefined ? true : canEditRoles,
245
- allowDefaultRolesCreation: allowDefaultRolesCreation === undefined ? true : allowDefaultRolesCreation,
246
- includeCollectionConfigPermissions: Boolean(includeCollectionConfigPermissions),
247
- collectionPermissions,
248
- defineRolesFor,
249
- authenticator
250
- }
251
- }
252
-
253
- const docsToUsers = (docs: DocumentSnapshot[]): (UserWithRoleIds)[] => {
254
- return docs.map((doc) => {
255
- const data = doc.data() as any;
256
- const newVar = {
257
- uid: doc.id,
258
- ...data,
259
- created_on: data?.created_on?.toDate(),
260
- updated_on: data?.updated_on?.toDate()
261
- };
262
- return newVar as (UserWithRoleIds);
263
- });
264
- }
265
-
266
- const docsToRoles = (docs: DocumentSnapshot[]): Role[] => {
267
- return docs.map((doc) => ({
268
- id: doc.id,
269
- ...doc.data()
270
- } as Role));
271
- }