Skip to content

Commit

Permalink
✨ expose validator function
Browse files Browse the repository at this point in the history
  • Loading branch information
w01fgang committed Aug 11, 2021
1 parent 5796654 commit 0310a36
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
30 changes: 30 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,33 @@ const { permission: showComponentName, role, rulesMap, } = usePermission('compon
...
{showComponentName && <div>Component available for authorized user</div>}
```
### 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 (
<PermissionGateProvider role={role} rulesMap={rules} validator={validator}>
<App />
</PermissionGateProvider>
)
}
```
17 changes: 14 additions & 3 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -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<Rules> = createContext({
Expand Down Expand Up @@ -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 };
}

Expand Down

0 comments on commit 0310a36

Please sign in to comment.