@rebasepro/firebase 0.0.1-canary.2 → 0.0.1-canary.eb08332
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/README.md +97 -3
- package/dist/components/FirebaseLoginView.d.ts +3 -3
- package/dist/components/RebaseFirebaseApp.d.ts +2 -1
- package/dist/components/RebaseFirebaseAppProps.d.ts +9 -13
- package/dist/components/social_icons.d.ts +6 -6
- package/dist/hooks/index.d.ts +3 -1
- package/dist/hooks/useAppCheck.d.ts +2 -2
- package/dist/hooks/useBuildUserManagement.d.ts +78 -0
- package/dist/hooks/useFirebaseAccessGate.d.ts +44 -0
- package/dist/hooks/useFirebaseAuthController.d.ts +2 -2
- package/dist/hooks/useFirebaseRealTimeDBDelegate.d.ts +2 -2
- package/dist/hooks/useFirebaseStorageSource.d.ts +1 -1
- package/dist/hooks/{useFirestoreDataSource.d.ts → useFirestoreDriver.d.ts} +9 -9
- package/dist/index.es.js +2598 -2663
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +2704 -2702
- package/dist/index.umd.js.map +1 -1
- package/dist/types/auth.d.ts +2 -2
- package/dist/types/text_search.d.ts +3 -3
- package/dist/utils/algolia.d.ts +7 -6
- package/dist/utils/collections_firestore.d.ts +4 -4
- package/package.json +75 -65
- package/src/components/FirebaseLoginView.tsx +53 -50
- package/src/components/RebaseFirebaseApp.tsx +82 -56
- package/src/components/RebaseFirebaseAppProps.tsx +10 -24
- package/src/components/social_icons.tsx +8 -8
- package/src/hooks/index.ts +3 -1
- package/src/hooks/useAppCheck.ts +5 -5
- package/src/hooks/useBuildUserManagement.tsx +366 -0
- package/src/hooks/useFirebaseAccessGate.tsx +145 -0
- package/src/hooks/useFirebaseAuthController.ts +6 -8
- package/src/hooks/useFirebaseRealTimeDBDelegate.ts +70 -79
- package/src/hooks/useFirebaseStorageSource.ts +23 -25
- package/src/hooks/useFirestoreDriver.ts +812 -0
- package/src/hooks/useInitialiseFirebase.ts +2 -2
- package/src/types/auth.tsx +2 -2
- package/src/types/text_search.ts +3 -3
- package/src/utils/algolia.ts +6 -9
- package/src/utils/collections_firestore.ts +25 -29
- package/src/utils/database.ts +2 -2
- package/src/utils/local_text_search_controller.ts +12 -12
- package/src/utils/pinecone.ts +3 -3
- package/src/utils/rebase_search_controller.ts +23 -22
- package/src/utils/text_search_controller.ts +2 -2
- package/dist/social_icons.d.ts +0 -6
- package/src/hooks/useFirestoreDataSource.ts +0 -796
- package/src/social_icons.tsx +0 -135
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import React, { useCallback, useEffect } from "react";
|
|
2
|
+
import { deepEqual as equal } from "fast-equals";
|
|
3
|
+
|
|
4
|
+
import { removeUndefined } from "@rebasepro/utils";
|
|
5
|
+
import {
|
|
6
|
+
AuthController,
|
|
7
|
+
DataDriver,
|
|
8
|
+
Entity,
|
|
9
|
+
User
|
|
10
|
+
} from "@rebasepro/types";
|
|
11
|
+
import { FirebaseAccessGate } from "./useFirebaseAccessGate";
|
|
12
|
+
|
|
13
|
+
export interface Role {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
isAdmin?: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
type UserWithRoleIds<USER extends User = User> = Omit<USER, "roles"> & { roles: string[] };
|
|
20
|
+
|
|
21
|
+
export interface UserManagementDelegateParams<CONTROLLER extends AuthController<User> = AuthController<User>> {
|
|
22
|
+
|
|
23
|
+
authController: CONTROLLER;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The delegate in charge of persisting the data.
|
|
27
|
+
*/
|
|
28
|
+
dataSourceDelegate?: DataDriver;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Path where the plugin users configuration is stored.
|
|
32
|
+
* Default: __FIRECMS/config/users
|
|
33
|
+
* You can specify a different path if you want to store the user management configuration in a different place.
|
|
34
|
+
* Please keep in mind that the FireCMS users are not necessarily the same as the Firebase users (but they can be).
|
|
35
|
+
* The path should be relative to the root of the database, and should always have an odd number of segments.
|
|
36
|
+
*/
|
|
37
|
+
usersPath?: string;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Path where the plugin roles configuration is stored.
|
|
41
|
+
* Default: __FIRECMS/config/roles
|
|
42
|
+
*/
|
|
43
|
+
rolesPath?: string;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The roles that are available in the user management system.
|
|
47
|
+
* If you provide this, the user management system will not fetch the roles from the database.
|
|
48
|
+
*/
|
|
49
|
+
roles?: Role[];
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* If there are no roles in the database, provide a button to create the default roles.
|
|
53
|
+
*/
|
|
54
|
+
allowDefaultRolesCreation?: 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 authController
|
|
62
|
+
* @param dataSourceDelegate
|
|
63
|
+
* @param usersPath
|
|
64
|
+
* @param rolesPath
|
|
65
|
+
* @param roles
|
|
66
|
+
* @param allowDefaultRolesCreation
|
|
67
|
+
*/
|
|
68
|
+
export function useBuildUserManagement<CONTROLLER extends AuthController<User> = AuthController<User>,
|
|
69
|
+
USER extends User = CONTROLLER extends AuthController<infer U> ? U : User>
|
|
70
|
+
({
|
|
71
|
+
authController,
|
|
72
|
+
dataSourceDelegate,
|
|
73
|
+
roles: rolesProp,
|
|
74
|
+
usersPath = "__FIRECMS/config/users",
|
|
75
|
+
rolesPath = "__FIRECMS/config/roles",
|
|
76
|
+
allowDefaultRolesCreation
|
|
77
|
+
}: UserManagementDelegateParams<CONTROLLER>) {
|
|
78
|
+
|
|
79
|
+
if (!authController) {
|
|
80
|
+
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");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const rolesDefinedInCode = (rolesProp ?? [])?.length > 0;
|
|
84
|
+
const [rolesLoading, setRolesLoading] = React.useState<boolean>(!rolesDefinedInCode);
|
|
85
|
+
const [usersLoading, setUsersLoading] = React.useState<boolean>(true);
|
|
86
|
+
const [roles, setRoles] = React.useState<Role[]>(rolesProp ?? []);
|
|
87
|
+
const [usersWithRoleIds, setUsersWithRoleIds] = React.useState<UserWithRoleIds<USER>[]>([]);
|
|
88
|
+
|
|
89
|
+
const users = usersWithRoleIds.map(u => ({
|
|
90
|
+
...u
|
|
91
|
+
}) as USER);
|
|
92
|
+
|
|
93
|
+
const [rolesError, setRolesError] = React.useState<Error | undefined>();
|
|
94
|
+
const [usersError, setUsersError] = React.useState<Error | undefined>();
|
|
95
|
+
|
|
96
|
+
const _usersLoading = usersLoading;
|
|
97
|
+
const _rolesLoading = rolesLoading;
|
|
98
|
+
|
|
99
|
+
const loading = _rolesLoading || _usersLoading;
|
|
100
|
+
|
|
101
|
+
useEffect(() => {
|
|
102
|
+
if (rolesDefinedInCode) return;
|
|
103
|
+
if (!dataSourceDelegate || !rolesPath) return;
|
|
104
|
+
if (dataSourceDelegate.initialised !== undefined && !dataSourceDelegate.initialised) return;
|
|
105
|
+
if (authController?.initialLoading) return;
|
|
106
|
+
|
|
107
|
+
setRolesLoading(true);
|
|
108
|
+
return dataSourceDelegate.listenCollection?.({
|
|
109
|
+
path: rolesPath,
|
|
110
|
+
onUpdate(rows: Record<string, unknown>[]): void {
|
|
111
|
+
setRolesError(undefined);
|
|
112
|
+
console.debug("Updating roles", rows);
|
|
113
|
+
try {
|
|
114
|
+
const newRoles = rowsToRoles(rows);
|
|
115
|
+
if (!equal(newRoles, roles)) {
|
|
116
|
+
setRoles(newRoles);
|
|
117
|
+
}
|
|
118
|
+
} catch (e) {
|
|
119
|
+
setRoles([]);
|
|
120
|
+
console.error("Error loading roles", e);
|
|
121
|
+
setRolesError(e as Error);
|
|
122
|
+
}
|
|
123
|
+
setRolesLoading(false);
|
|
124
|
+
},
|
|
125
|
+
onError(e: unknown): void {
|
|
126
|
+
setRoles([]);
|
|
127
|
+
console.error("Error loading roles", e);
|
|
128
|
+
setRolesError(e instanceof Error ? e : new Error(String(e)));
|
|
129
|
+
setRolesLoading(false);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
}, [rolesDefinedInCode, dataSourceDelegate?.initialised, authController?.initialLoading, authController?.user?.uid, rolesPath]);
|
|
134
|
+
|
|
135
|
+
useEffect(() => {
|
|
136
|
+
if (!dataSourceDelegate || !usersPath) return;
|
|
137
|
+
if (dataSourceDelegate.initialised !== undefined && !dataSourceDelegate.initialised) {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (authController?.initialLoading) {
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
setUsersLoading(true);
|
|
145
|
+
return dataSourceDelegate.listenCollection?.({
|
|
146
|
+
path: usersPath,
|
|
147
|
+
onUpdate(rows: Record<string, unknown>[]): void {
|
|
148
|
+
console.debug("Updating users", rows);
|
|
149
|
+
setUsersError(undefined);
|
|
150
|
+
try {
|
|
151
|
+
const newUsers = rowsToUsers(rows) as UserWithRoleIds<USER>[];
|
|
152
|
+
// if (!equal(newUsers, usersWithRoleIds))
|
|
153
|
+
setUsersWithRoleIds(newUsers);
|
|
154
|
+
} catch (e) {
|
|
155
|
+
setUsersWithRoleIds([]);
|
|
156
|
+
console.error("Error loading users", e);
|
|
157
|
+
setUsersError(e as Error);
|
|
158
|
+
}
|
|
159
|
+
setUsersLoading(false);
|
|
160
|
+
},
|
|
161
|
+
onError(e: unknown): void {
|
|
162
|
+
console.error("Error loading users", e);
|
|
163
|
+
setUsersWithRoleIds([]);
|
|
164
|
+
setUsersError(e instanceof Error ? e : new Error(String(e)));
|
|
165
|
+
setUsersLoading(false);
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
}, [dataSourceDelegate?.initialised, authController?.initialLoading, authController?.user?.uid, usersPath]);
|
|
170
|
+
|
|
171
|
+
const saveUser = useCallback(async (user: USER): Promise<USER> => {
|
|
172
|
+
if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
|
|
173
|
+
if (!usersPath) throw Error("useBuildUserManagement Firestore not initialised");
|
|
174
|
+
|
|
175
|
+
console.debug("Persisting user", user);
|
|
176
|
+
|
|
177
|
+
const roleIds = user.roles;
|
|
178
|
+
const email = user.email?.toLowerCase().trim();
|
|
179
|
+
if (!email) throw Error("Email is required");
|
|
180
|
+
|
|
181
|
+
const userExists = users.find(u => u.email?.toLowerCase() === email);
|
|
182
|
+
const data = {
|
|
183
|
+
...user,
|
|
184
|
+
roles: roleIds ?? [],
|
|
185
|
+
...(userExists ? {} : { created_on: new Date() })
|
|
186
|
+
};
|
|
187
|
+
// delete the previous user entry if it exists and the uid has changed
|
|
188
|
+
if (userExists && userExists.uid !== user.uid) {
|
|
189
|
+
const row = {
|
|
190
|
+
values: {},
|
|
191
|
+
path: usersPath,
|
|
192
|
+
id: userExists.uid
|
|
193
|
+
}
|
|
194
|
+
await dataSourceDelegate.delete({ row })
|
|
195
|
+
.then(() => {
|
|
196
|
+
console.debug("Deleted previous user", userExists);
|
|
197
|
+
})
|
|
198
|
+
.catch(e => {
|
|
199
|
+
console.error("Error deleting user", e);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return dataSourceDelegate.save({
|
|
205
|
+
status: "existing",
|
|
206
|
+
path: usersPath,
|
|
207
|
+
id: email,
|
|
208
|
+
values: removeUndefined(data) as Record<string, unknown>
|
|
209
|
+
}).then(() => user);
|
|
210
|
+
}, [usersPath, dataSourceDelegate?.initialised]);
|
|
211
|
+
|
|
212
|
+
const saveRole = useCallback((role: Role): Promise<void> => {
|
|
213
|
+
if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
|
|
214
|
+
if (!rolesPath) throw Error("useBuildUserManagement Firestore not initialised");
|
|
215
|
+
console.debug("Persisting role", role);
|
|
216
|
+
const {
|
|
217
|
+
id,
|
|
218
|
+
...roleData
|
|
219
|
+
} = role;
|
|
220
|
+
return dataSourceDelegate.save({
|
|
221
|
+
status: "existing",
|
|
222
|
+
path: rolesPath,
|
|
223
|
+
id: id,
|
|
224
|
+
values: removeUndefined(roleData) as Record<string, unknown>
|
|
225
|
+
}).then(() => {
|
|
226
|
+
return;
|
|
227
|
+
});
|
|
228
|
+
}, [rolesPath, dataSourceDelegate?.initialised]);
|
|
229
|
+
|
|
230
|
+
const deleteUser = useCallback(async (user: User): Promise<void> => {
|
|
231
|
+
if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
|
|
232
|
+
if (!usersPath) throw Error("useBuildUserManagement Firestore not initialised");
|
|
233
|
+
console.debug("Deleting", user);
|
|
234
|
+
const { uid } = user;
|
|
235
|
+
const row = {
|
|
236
|
+
path: usersPath,
|
|
237
|
+
id: uid,
|
|
238
|
+
values: {}
|
|
239
|
+
};
|
|
240
|
+
await dataSourceDelegate.delete({ row })
|
|
241
|
+
}, [usersPath, dataSourceDelegate?.initialised]);
|
|
242
|
+
|
|
243
|
+
const deleteRole = useCallback(async (role: Role): Promise<void> => {
|
|
244
|
+
if (!dataSourceDelegate) throw Error("useBuildUserManagement Firebase not initialised");
|
|
245
|
+
if (!rolesPath) throw Error("useBuildUserManagement Firestore not initialised");
|
|
246
|
+
console.debug("Deleting", role);
|
|
247
|
+
const { id } = role;
|
|
248
|
+
const row = {
|
|
249
|
+
path: rolesPath,
|
|
250
|
+
id: id,
|
|
251
|
+
values: {}
|
|
252
|
+
};
|
|
253
|
+
await dataSourceDelegate.delete({ row })
|
|
254
|
+
}, [rolesPath, dataSourceDelegate?.initialised]);
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
const defineRolesFor: ((user: User) => string[] | undefined) = useCallback((user) => {
|
|
258
|
+
if (!usersWithRoleIds) throw Error("Users not loaded");
|
|
259
|
+
const mgmtUser = usersWithRoleIds.find(u => u.email?.toLowerCase() === user?.email?.toLowerCase());
|
|
260
|
+
if (!mgmtUser || !mgmtUser.roles) return undefined;
|
|
261
|
+
return mgmtUser.roles;
|
|
262
|
+
}, [usersWithRoleIds]);
|
|
263
|
+
|
|
264
|
+
const accessGate: FirebaseAccessGate<USER> = useCallback(({ user }) => {
|
|
265
|
+
|
|
266
|
+
if (loading) {
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
if (user === null) {
|
|
270
|
+
console.warn("User is null, returning");
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (users.length === 0) {
|
|
275
|
+
console.warn("No users created yet");
|
|
276
|
+
return true; // If there are no users created yet, we allow access to every user
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const mgmtUser = users.find(u => u.email?.toLowerCase() === user?.email?.toLowerCase());
|
|
280
|
+
if (mgmtUser) {
|
|
281
|
+
// check if the uid or photoURL needs to be updated in the user management system
|
|
282
|
+
const needsUidUpdate = mgmtUser.uid !== user.uid;
|
|
283
|
+
const needsPhotoUpdate = user.photoURL && mgmtUser.photoURL !== user.photoURL;
|
|
284
|
+
|
|
285
|
+
if (needsUidUpdate || needsPhotoUpdate) {
|
|
286
|
+
const updateReason = needsUidUpdate ? "uid" : "photoURL";
|
|
287
|
+
console.debug(`User ${updateReason} has changed, updating user in user management system`);
|
|
288
|
+
saveUser({
|
|
289
|
+
...mgmtUser,
|
|
290
|
+
uid: user.uid,
|
|
291
|
+
...(needsPhotoUpdate ? { photoURL: user.photoURL } : {})
|
|
292
|
+
}).then(() => {
|
|
293
|
+
console.debug("User updated in user management system", mgmtUser);
|
|
294
|
+
}).catch(e => {
|
|
295
|
+
console.error("Error updating user in user management system", e);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
console.debug("User found in user management system", mgmtUser);
|
|
299
|
+
return true;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
throw Error("Could not find a user with the provided email in the user management system.");
|
|
303
|
+
}, [loading, users]);
|
|
304
|
+
|
|
305
|
+
const userRoles = authController.user ? defineRolesFor(authController.user) : undefined;
|
|
306
|
+
const isAdmin = (userRoles ?? []).some(r => r === "admin");
|
|
307
|
+
|
|
308
|
+
const userRoleIds = userRoles;
|
|
309
|
+
useEffect(() => {
|
|
310
|
+
console.debug("Setting user roles", {
|
|
311
|
+
userRoles,
|
|
312
|
+
roles
|
|
313
|
+
});
|
|
314
|
+
authController.setUserRoles?.(userRoles ?? []);
|
|
315
|
+
}, [userRoleIds]);
|
|
316
|
+
|
|
317
|
+
const getUser = useCallback((uid: string): USER | null => {
|
|
318
|
+
if (!users) return null;
|
|
319
|
+
const user = users.find(u => u.uid === uid);
|
|
320
|
+
return user ?? null;
|
|
321
|
+
}, [users]);
|
|
322
|
+
|
|
323
|
+
return {
|
|
324
|
+
loading,
|
|
325
|
+
roles,
|
|
326
|
+
users,
|
|
327
|
+
saveUser,
|
|
328
|
+
saveRole,
|
|
329
|
+
rolesError,
|
|
330
|
+
deleteUser,
|
|
331
|
+
deleteRole,
|
|
332
|
+
usersError,
|
|
333
|
+
isAdmin,
|
|
334
|
+
allowDefaultRolesCreation: allowDefaultRolesCreation === undefined ? true : allowDefaultRolesCreation,
|
|
335
|
+
defineRolesFor,
|
|
336
|
+
accessGate,
|
|
337
|
+
...authController,
|
|
338
|
+
initialLoading: authController.initialLoading || loading,
|
|
339
|
+
userRoles: userRoles,
|
|
340
|
+
getUser,
|
|
341
|
+
user: authController.user ? {
|
|
342
|
+
...authController.user,
|
|
343
|
+
roles: userRoles
|
|
344
|
+
} : null
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const rowsToUsers = (rows: Record<string, unknown>[]): (UserWithRoleIds)[] => {
|
|
349
|
+
return rows.map((row) => {
|
|
350
|
+
const { id, ...data } = row;
|
|
351
|
+
const newVar = {
|
|
352
|
+
...data,
|
|
353
|
+
uid: id,
|
|
354
|
+
created_on: data.created_on as Date | undefined,
|
|
355
|
+
updated_on: data.updated_on as Date | undefined
|
|
356
|
+
};
|
|
357
|
+
return newVar as unknown as UserWithRoleIds;
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const rowsToRoles = (rows: Record<string, unknown>[]): Role[] => {
|
|
362
|
+
return rows.map((row) => ({
|
|
363
|
+
...row,
|
|
364
|
+
id: row.id
|
|
365
|
+
} as unknown as Role));
|
|
366
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
|
|
2
|
+
import { useCallback, useEffect, useRef, useState, useMemo } from "react";
|
|
3
|
+
import { deepEqual as equal } from "fast-equals";
|
|
4
|
+
|
|
5
|
+
import { AuthController, RebaseData, StorageSource, User } from "@rebasepro/types";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Client-side gate that decides whether a Firebase-authenticated user
|
|
9
|
+
* is allowed to access the CMS UI.
|
|
10
|
+
*
|
|
11
|
+
* Return `true` to allow access or `false` / throw to deny.
|
|
12
|
+
* @group Firebase
|
|
13
|
+
*/
|
|
14
|
+
export type FirebaseAccessGate<USER extends User = User> = (props: {
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Logged-in user or null
|
|
18
|
+
*/
|
|
19
|
+
user: USER | null;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* AuthController
|
|
23
|
+
*/
|
|
24
|
+
authController: AuthController<USER>;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Unified data access API
|
|
28
|
+
*/
|
|
29
|
+
data: RebaseData;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Used storage implementation
|
|
33
|
+
*/
|
|
34
|
+
storageSource: StorageSource;
|
|
35
|
+
|
|
36
|
+
}) => boolean | Promise<boolean>;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Hook that evaluates a {@link FirebaseAccessGate} callback after
|
|
40
|
+
* the user logs in and gates access to the main CMS view.
|
|
41
|
+
*
|
|
42
|
+
* @group Firebase
|
|
43
|
+
*/
|
|
44
|
+
export function useFirebaseAccessGate<USER extends User = User>
|
|
45
|
+
({
|
|
46
|
+
disabled,
|
|
47
|
+
authController,
|
|
48
|
+
accessGate,
|
|
49
|
+
storageSource,
|
|
50
|
+
data
|
|
51
|
+
}:
|
|
52
|
+
{
|
|
53
|
+
disabled?: boolean,
|
|
54
|
+
authController: AuthController<USER>,
|
|
55
|
+
accessGate?: boolean | FirebaseAccessGate<USER>,
|
|
56
|
+
data: RebaseData;
|
|
57
|
+
storageSource: StorageSource;
|
|
58
|
+
}): {
|
|
59
|
+
canAccessMainView: boolean,
|
|
60
|
+
authLoading: boolean,
|
|
61
|
+
notAllowedError: unknown,
|
|
62
|
+
authVerified: boolean,
|
|
63
|
+
} {
|
|
64
|
+
|
|
65
|
+
const gateEnabled = Boolean(accessGate);
|
|
66
|
+
|
|
67
|
+
const [authLoading, setAuthLoading] = useState<boolean>(gateEnabled);
|
|
68
|
+
const [notAllowedError, setNotAllowedError] = useState<unknown>(false);
|
|
69
|
+
const [authVerified, setAuthVerified] = useState<boolean>(!gateEnabled || Boolean(authController.loginSkipped));
|
|
70
|
+
|
|
71
|
+
const canAccessMainView = (authVerified) &&
|
|
72
|
+
(!gateEnabled || Boolean(authController.user) || Boolean(authController.loginSkipped)) &&
|
|
73
|
+
!notAllowedError;
|
|
74
|
+
|
|
75
|
+
useEffect(() => {
|
|
76
|
+
if (authController.loginSkipped)
|
|
77
|
+
setAuthVerified(true);
|
|
78
|
+
}, [authController.loginSkipped]);
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* We use this ref to check the authentication only if the user has
|
|
82
|
+
* changed.
|
|
83
|
+
*/
|
|
84
|
+
const checkedUserRef = useRef<User | undefined>(undefined);
|
|
85
|
+
|
|
86
|
+
const checkAccess = useCallback(async () => {
|
|
87
|
+
|
|
88
|
+
if (disabled) {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (authController.initialLoading) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (!authController.user && !authController.loginSkipped) {
|
|
97
|
+
checkedUserRef.current = undefined;
|
|
98
|
+
setAuthLoading(false);
|
|
99
|
+
setAuthVerified(false);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const delegateUser = authController.user;
|
|
104
|
+
|
|
105
|
+
if (accessGate instanceof Function && delegateUser && !equal(checkedUserRef.current?.uid, delegateUser.uid)) {
|
|
106
|
+
setAuthLoading(true);
|
|
107
|
+
try {
|
|
108
|
+
const allowed = await accessGate({
|
|
109
|
+
user: delegateUser,
|
|
110
|
+
authController,
|
|
111
|
+
data,
|
|
112
|
+
storageSource
|
|
113
|
+
});
|
|
114
|
+
if (!allowed) {
|
|
115
|
+
authController.signOut();
|
|
116
|
+
setNotAllowedError(true);
|
|
117
|
+
}
|
|
118
|
+
} catch (e) {
|
|
119
|
+
setNotAllowedError(e);
|
|
120
|
+
authController.signOut();
|
|
121
|
+
}
|
|
122
|
+
setAuthLoading(false);
|
|
123
|
+
setAuthVerified(true);
|
|
124
|
+
checkedUserRef.current = delegateUser;
|
|
125
|
+
} else {
|
|
126
|
+
setAuthLoading(false);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (!authController.initialLoading && !delegateUser) {
|
|
130
|
+
setAuthVerified(true);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
}, [disabled, authController, accessGate, data, storageSource]);
|
|
134
|
+
|
|
135
|
+
useEffect(() => {
|
|
136
|
+
checkAccess();
|
|
137
|
+
}, [checkAccess]);
|
|
138
|
+
|
|
139
|
+
return useMemo(() => ({
|
|
140
|
+
canAccessMainView,
|
|
141
|
+
authLoading: gateEnabled && authLoading,
|
|
142
|
+
notAllowedError,
|
|
143
|
+
authVerified
|
|
144
|
+
}), [canAccessMainView, gateEnabled, authLoading, notAllowedError, authVerified]);
|
|
145
|
+
}
|
|
@@ -24,14 +24,14 @@ import {
|
|
|
24
24
|
} from "@firebase/auth";
|
|
25
25
|
import { FirebaseApp } from "@firebase/app";
|
|
26
26
|
import { FirebaseAuthController, FirebaseSignInOption, FirebaseSignInProvider, FirebaseUserWrapper } from "../types";
|
|
27
|
-
import {
|
|
27
|
+
import type { User } from "@rebasepro/types";
|
|
28
28
|
|
|
29
29
|
export interface FirebaseAuthControllerProps {
|
|
30
30
|
loading?: boolean;
|
|
31
31
|
firebaseApp?: FirebaseApp;
|
|
32
32
|
signInOptions?: Array<FirebaseSignInProvider | FirebaseSignInOption>;
|
|
33
33
|
onSignOut?: () => void;
|
|
34
|
-
defineRolesFor?: (user: User) => Promise<
|
|
34
|
+
defineRolesFor?: (user: User) => Promise<string[] | undefined> | string[] | undefined;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
/**
|
|
@@ -53,13 +53,11 @@ export const useFirebaseAuthController = <USER extends FirebaseUserWrapper = any
|
|
|
53
53
|
const [authLoading, setAuthLoading] = useState(true);
|
|
54
54
|
const [loginSkipped, setLoginSkipped] = useState<boolean>(false);
|
|
55
55
|
const [confirmationResult, setConfirmationResult] = useState<undefined | ConfirmationResult>();
|
|
56
|
-
const [userRoles, _setUserRoles] = useState<
|
|
56
|
+
const [userRoles, _setUserRoles] = useState<string[] | undefined>();
|
|
57
57
|
const [extra, setExtra] = useState<any>();
|
|
58
58
|
|
|
59
|
-
const setUserRoles = useCallback((roles:
|
|
60
|
-
|
|
61
|
-
const newRoleIds = roles?.map(r => r.id);
|
|
62
|
-
if (!equal(currentRoleIds, newRoleIds)) {
|
|
59
|
+
const setUserRoles = useCallback((roles: string[] | undefined) => {
|
|
60
|
+
if (!equal(userRoles, roles)) {
|
|
63
61
|
_setUserRoles(roles);
|
|
64
62
|
}
|
|
65
63
|
}, [userRoles]);
|
|
@@ -299,7 +297,7 @@ export const useFirebaseAuthController = <USER extends FirebaseUserWrapper = any
|
|
|
299
297
|
const firebaseUserWrapper: FirebaseUserWrapper | null = loggedUser
|
|
300
298
|
? {
|
|
301
299
|
...loggedUser,
|
|
302
|
-
roles: userRoles
|
|
300
|
+
roles: userRoles,
|
|
303
301
|
firebaseUser: loggedUser
|
|
304
302
|
}
|
|
305
303
|
: null;
|