@firecms/user_management 3.0.0-canary.9 → 3.0.0-canary.90

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