Skip to content

Instantly share code, notes, and snippets.

@createdbymahmood
Last active November 13, 2020 00:23
Show Gist options
  • Save createdbymahmood/358db86c75a44fdd8160e8457507aef2 to your computer and use it in GitHub Desktop.
Save createdbymahmood/358db86c75a44fdd8160e8457507aef2 to your computer and use it in GitHub Desktop.
This is how I handle ACL in React apps
import React, { FC, Fragment } from "react";
import { usePermissions } from "services/rbac";
import { get } from "lodash";
export type AclProps = {
permission: string;
};
export const AclService: FC<AclProps> = ({ permission, children }) => {
const { role, permissions } = usePermissions();
const canPerform = get(permissions, `${role}.${permission}`);
return <Fragment>{canPerform ? children : null}</Fragment>;
};
import { atom } from "recoil";
type RoleUnionType = "guest" | "admin" | "user" | "author";
export const roleState = atom<RoleUnionType>({
key: "roleState",
default: "guest",
});
export const permissions = {
guest: {
books: {
read: true,
create: false,
update: false,
delete: false,
like: false,
},
comments: {
read: true,
create: true,
update: false,
delete: true,
},
bookComments: {},
profile: {
read: false,
update: false,
image: false,
name: false,
biography: false,
username: {
update: false,
},
comments: {
read: false,
delete: false,
},
},
publisher: {
submissionRequest: false,
},
},
};
import React, { FC } from "react";
/* components */
import { AclService } from "services/rbac";
const Book: FC = () => {
return (
<AclService permission="comments.read">
{/* now this part is available only if the user has the permission of comments.read in permissions.ts file */}
</AclService>
);
};
export default Book;
import { useRecoilState } from "recoil";
import { permissions } from "services/rbac";
import { roleState } from "services/recoil/user/atoms";
export function usePermissions() {
const [role] = useRecoilState(roleState);
return {
permissions,
role,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment