Created
March 28, 2025 23:09
-
-
Save gikdev/016fb9600263b0acec0ea949c6486782 to your computer and use it in GitHub Desktop.
Sample TS file for authorization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ACTIONS = ["view" , "edit" , "remove" , "create"] as const | |
type Action = typeof ACTIONS[number] | |
const RESOURCES = ["post", "product"] as const | |
type Resource = typeof RESOURCES[number] | |
const makePermission = (action: Action, resource: Resource) => `${action}:${resource}` | |
const PERMISSIONS = { | |
viewer: [ | |
makePermission("view", "product"), | |
], | |
editor: [ | |
makePermission("view", "post"), | |
makePermission("create", "post"), | |
makePermission("edit", "post"), | |
], | |
admin: [ | |
makePermission("view", "post"), | |
makePermission("create", "post"), | |
makePermission("edit", "post"), | |
makePermission("remove", "post"), | |
], | |
} | |
type Role = keyof typeof PERMISSIONS | |
export function checkPermission(role: Role, action: Action, resource: Resource): boolean { | |
const permissions = PERMISSIONS[role] | |
if (!permissions?.length) return false | |
const permissionToCheck = makePermission(action, resource) | |
return permissions.includes(permissionToCheck) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment