From 0310a3678d9acc10a35cc124f8419db2cb68e85e Mon Sep 17 00:00:00 2001 From: w01gng Date: Wed, 11 Aug 2021 12:29:45 +0200 Subject: [PATCH] :sparkles: expose validator function --- Readme.md | 30 ++++++++++++++++++++++++++++++ src/index.tsx | 17 ++++++++++++++--- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index f9b556a..0c6f952 100644 --- a/Readme.md +++ b/Readme.md @@ -54,3 +54,33 @@ const { permission: showComponentName, role, rulesMap, } = usePermission('compon ... {showComponentName &&
Component available for authorized user
} ``` +### Advanced usage +A validator function can be provided +```javascript +import { PermissionGateProvider } from 'permission-gate'; +... + +// define or get from api rules and freeze them +const rules = Object.freeze({ + componentName: ['admin', 'user', 'other-role'], + anotherComponentName: ['admin'], +}); + +function validator({ role, rulesMap, name }) { + // default validator implementation + const scope = rulesMap[name]; + if (!scope) return true; + + return scope.includes(role); +} + +function MyApp() { + const role = 'user'; // get from authenticated user + + return ( + + + + ) +} +``` \ No newline at end of file diff --git a/src/index.tsx b/src/index.tsx index 500ee3f..bf4cb31 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,8 +1,19 @@ -import React, { useContext, createContext, cloneElement, forwardRef, isValidElement, Context, Ref, ReactChild, ReactElement } from "react"; +import React, { + useContext, + createContext, + cloneElement, + forwardRef, + isValidElement, + Context, + Ref, + ReactChild, + ReactElement, +} from "react"; export type Rules = { rulesMap: { [key: string]: string[] }, role: string, + validator?: ({ role, rulesMap, name }: Rules & { name: string }) => boolean, }; const RoleContext: Context = createContext({ @@ -35,9 +46,9 @@ const hasPermission = ({ role, rulesMap, name }: Rules & { name: string }): bool }; export function usePermission(name: string): Rules & { granted: boolean } { - const { role, rulesMap }: Rules = useContext(RoleContext); + const { role, rulesMap, validator = hasPermission }: Rules = useContext(RoleContext); - const granted = hasPermission({ role, rulesMap, name }); + const granted = validator({ role, rulesMap, name }); return { granted, role, rulesMap }; }