diff --git a/lib/permissions.test.ts b/lib/permissions.test.ts new file mode 100644 index 0000000..3b45233 --- /dev/null +++ b/lib/permissions.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest'; +import { hasPermission } from './permissions'; + +describe('hasPermission', () => { + it('returns false (not a crash) for a "user" role on an admin-only resource', () => { + expect(() => hasPermission('user', 'admin', 'access')).not.toThrow(); + expect(hasPermission('user', 'admin', 'access')).toBe(false); + }); + + it('returns true for "admin" role on an admin-gated resource', () => { + expect(hasPermission('admin', 'admin', 'access')).toBe(true); + }); + + it('returns true for "super-admin" role on an admin-gated resource', () => { + expect(hasPermission('super-admin', 'admin', 'access')).toBe(true); + }); + + it('returns true for "user" role on a permitted resource', () => { + expect(hasPermission('user', 'tickets', 'read')).toBe(true); + }); + + it('returns false for an unknown role', () => { + expect(hasPermission('bogus-role', 'admin', 'access')).toBe(false); + }); +}); diff --git a/lib/permissions.ts b/lib/permissions.ts index 008b7ef..c11d963 100644 --- a/lib/permissions.ts +++ b/lib/permissions.ts @@ -74,17 +74,17 @@ export const userRole = ac.newRole({ // Helper function to check if a user has a specific permission export function hasPermission( - userRole: string, + roleName: string, resource: keyof typeof statement, action: string ): boolean { const roles: Record> = { "super-admin": superAdminRole, admin: adminRole, - user: userRole as unknown as ReturnType, + user: userRole, }; - const role = roles[userRole]; + const role = roles[roleName]; if (!role) return false; // Check if the role has the permission