35 lines
1.2 KiB
TypeScript
Executable File
35 lines
1.2 KiB
TypeScript
Executable File
import React, { createContext, useContext, useMemo } from 'react';
|
|
import { canEditSub, canReadSub, isScopeOwn } from '../constants/permissions';
|
|
|
|
interface PermissionsContextValue {
|
|
permissions: string[] | null;
|
|
}
|
|
|
|
const PermissionsContext = createContext<PermissionsContextValue>({ permissions: null });
|
|
|
|
export const PermissionsProvider: React.FC<{ permissions: string[] | null; children: React.ReactNode }> = ({
|
|
permissions,
|
|
children,
|
|
}) => {
|
|
const value = useMemo(() => ({ permissions }), [permissions]);
|
|
return <PermissionsContext.Provider value={value}>{children}</PermissionsContext.Provider>;
|
|
};
|
|
|
|
export function usePermissions() {
|
|
return useContext(PermissionsContext);
|
|
}
|
|
|
|
/** Права на подраздел: можно ли читать, редактировать, только своё */
|
|
export function useSubPermission(section: string, subId: string) {
|
|
const { permissions } = usePermissions();
|
|
const list = permissions ?? [];
|
|
return useMemo(
|
|
() => ({
|
|
canRead: canReadSub(list, section, subId),
|
|
canEdit: canEditSub(list, section, subId),
|
|
scopeOwn: isScopeOwn(list, section, subId),
|
|
}),
|
|
[list, section, subId]
|
|
);
|
|
}
|