refactor: extract shared hasPermission helper (MODSetter/SurfSense#1366)

- Add canPerform() helper function to members-query.atoms.ts
- Add usePermissionGate() hook for convenience
- Update team-content.tsx to use canPerform()
- Update roles-manager.tsx to use canPerform()
- Eliminates duplicated permission check logic
- Centralizes permission policy in one location

Fixes #1366
This commit is contained in:
guangyang1206 2026-05-22 12:08:00 +08:00
parent 334729754f
commit a66d65a835
3 changed files with 41 additions and 8 deletions

View file

@ -39,3 +39,38 @@ export const myAccessAtom = atomWithQuery((get) => {
},
};
});
/**
* Helper function to check if the current user has a specific permission.
*
* @param access - The access object from useAtomValue(myAccessAtom)
* @param permission - The permission string to check
* @returns boolean indicating if the user has the permission
*
* @example
* const access = useAtomValue(myAccessAtom);
* if (canPerform(access, 'manage_members')) { ... }
*/
export function canPerform(
access: { is_owner: boolean; permissions?: string[] } | null | undefined,
permission: string
): boolean {
if (!access) return false;
if (access.is_owner) return true;
return access.permissions?.includes(permission) ?? false;
}
/**
* Hook wrapper for canPerform that reads from myAccessAtom internally.
* Use this if you want to avoid calling useAtomValue(myAccessAtom) separately.
*
* @param permission - The permission string to check
* @returns boolean indicating if the user has the permission
*
* @example
* const canManageMembers = usePermissionGate('manage_members');
*/
export function usePermissionGate(permission: string): boolean {
const access = useAtomValue(myAccessAtom);
return canPerform(access, permission);
}