|
| 1 | +import { useMemo } from "react"; |
1 | 2 | import { StaffUser } from "@/models/Staff"; |
2 | 3 | import { jwtDecode, JwtPayload } from "jwt-decode"; |
3 | 4 | import { useAuth } from "react-oidc-context"; |
@@ -25,28 +26,29 @@ export const useIsRolesAllowed = ( |
25 | 26 | users?: StaffUser[] |
26 | 27 | ): boolean => { |
27 | 28 | const { user: authUser } = useAuth(); |
28 | | - |
29 | | - if (!authUser?.access_token) { |
30 | | - return false; |
31 | | - } |
32 | 29 |
|
33 | | - const payload = jwtDecode<CustomJwtPayload>(authUser.access_token); |
34 | | - |
35 | | - // Get roles from resource_access if available |
36 | | - const resourceRoles = payload.resource_access?.[OidcConfig.client_id]?.roles || []; |
37 | | - |
38 | | - // Check if the user has any of the required roles (from groups or resource_access) |
39 | | - const isRoleAllowed = roles.some((role) => |
40 | | - resourceRoles.includes(role) |
41 | | - ); |
| 30 | + return useMemo(() => { |
| 31 | + if (!authUser?.access_token) { |
| 32 | + return false; |
| 33 | + } |
42 | 34 |
|
43 | | - // Check if the logged-in user is part of the provided users list |
44 | | - const isUserAllowed = |
45 | | - users?.some( |
46 | | - (user) => user?.auth_user_guid === authUser?.profile?.preferred_username |
47 | | - ) ?? false; |
| 35 | + const payload = jwtDecode<CustomJwtPayload>(authUser.access_token); |
48 | 36 |
|
49 | | - return isRoleAllowed || isUserAllowed; |
| 37 | + // Get roles from resource_access if available |
| 38 | + const resourceRoles = |
| 39 | + payload.resource_access?.[OidcConfig.client_id]?.roles || []; |
| 40 | + |
| 41 | + // Check if the user has any of the required roles (from groups or resource_access) |
| 42 | + const isRoleAllowed = roles.some((role) => resourceRoles.includes(role)); |
| 43 | + |
| 44 | + // Check if the logged-in user is part of the provided users list |
| 45 | + const isUserAllowed = |
| 46 | + users?.some( |
| 47 | + (user) => user?.auth_user_guid === authUser?.profile?.preferred_username |
| 48 | + ) ?? false; |
| 49 | + |
| 50 | + return isRoleAllowed || isUserAllowed; |
| 51 | + }, [authUser?.access_token, authUser?.profile?.preferred_username, roles, users]); |
50 | 52 | }; |
51 | 53 |
|
52 | 54 | export const useCurrentLoggedInUser = () => { |
|
0 commit comments