forked from openedx/frontend-app-authoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.ts
More file actions
71 lines (65 loc) · 2.36 KB
/
hooks.ts
File metadata and controls
71 lines (65 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { useWaffleFlags } from '@src/data/apiHooks';
import { useUserPermissions } from '@src/authz/data/apiHooks';
import { PermissionValidationAnswer, PermissionValidationQuery } from '@src/authz/types';
type UseCourseUserPermissionsReturn<Query extends PermissionValidationQuery> = {
isLoading: boolean;
isAuthzEnabled: boolean;
} & PermissionValidationAnswer<Query>;
/**
* Custom hook to retrieve and evaluate user permissions for the current course using the openedx-authz service.
*
* The hook:
* 1. Validate if authz is enabled via waffle flag
* 2. Fetch user permissions when authz is enabled
* 3. Fallback all permissions to 'true' when authz is disabled
* 4. Provide fallback values for undefined permissions
*
* @param courseId - The course ID to check permissions for
* @param permissions - Object mapping permission names to their action/scope definitions
* @returns Object containing loading state, permissions results, and authz status
*
* @example
* ```tsx
* const { isLoading, canViewGradingSettings, canEditGradingSettings, isAuthzEnabled } = useCourseUserPermissions(
* courseId,
* {
* canViewGradingSettings: {
* action: COURSE_PERMISSIONS.VIEW_GRADING_SETTINGS,
* scope: courseId,
* },
* canEditGradingSettings: {
* action: COURSE_PERMISSIONS.EDIT_GRADING_SETTINGS,
* scope: courseId,
* },
* }
* );
* ```
*/
export const useCourseUserPermissions = <Query extends PermissionValidationQuery>(
courseId: string,
permissions: Query,
): UseCourseUserPermissionsReturn<Query> => {
const waffleFlags = useWaffleFlags(courseId);
const isAuthzEnabled: boolean = waffleFlags?.enableAuthzCourseAuthoring ?? false;
const {
isLoading: isLoadingUserPermissions,
data: userPermissions,
} = useUserPermissions(permissions, isAuthzEnabled);
const resolvePermission = (key: string): boolean => {
if (!isAuthzEnabled) {
return true;
}
return userPermissions?.[key] ?? false;
};
const permissionResults: Record<string, boolean> = isLoadingUserPermissions
? {}
: Object.keys(permissions).reduce<Record<string, boolean>>((acc, key) => {
acc[key] = resolvePermission(key);
return acc;
}, {});
return {
isLoading: isAuthzEnabled ? isLoadingUserPermissions : false,
isAuthzEnabled,
...permissionResults as PermissionValidationAnswer<Query>,
};
};