Skip to content

Instantly share code, notes, and snippets.

@gikdev
Created March 28, 2025 23:09
Show Gist options
  • Save gikdev/016fb9600263b0acec0ea949c6486782 to your computer and use it in GitHub Desktop.
Save gikdev/016fb9600263b0acec0ea949c6486782 to your computer and use it in GitHub Desktop.
Sample TS file for authorization
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