dstpabuaran.com/resources/js/hooks/use-can.ts
Yoga Pangestu 3e9776696d Refactor permissions and sidebar items; enhance user role checks
- Updated HandleInertiaRequests middleware to include user permissions in the shared data.
- Modified RolePermissionSeeder to redefine permissions and roles, adding new permissions and restructuring existing ones.
- Refactored app-sidebar component to filter menu items based on user permissions, improving sidebar visibility based on roles.
- Enhanced useCan hook to support checking multiple permissions with canAny function.
- Updated web routes to enforce permission checks on various resource routes, ensuring proper access control.
2026-08-04 23:57:00 +07:00

55 lines
1.5 KiB
TypeScript

import { usePage } from '@inertiajs/react';
type RoleOrPermission = { name: string } | string;
type User = {
id: number;
username?: string;
roles?: RoleOrPermission[];
permissions?: RoleOrPermission[];
[key: string]: unknown;
};
type PageProps = {
auth: {
user?: User;
};
};
function extractNames(items?: RoleOrPermission[]): string[] {
if (!items) return [];
return items.map((item) => (typeof item === 'string' ? item : item.name));
}
export function useCan() {
const { auth } = usePage().props as PageProps;
const user = auth.user;
const roleNames = extractNames(user?.roles);
const permissionNames = extractNames(user?.permissions);
function can(permission: string): boolean {
if (!user) return false;
if (roleNames.includes('developer') || roleNames.includes('owner')) return true;
return permissionNames.includes(permission);
}
function canAny(...permissions: string[]): boolean {
if (!user) return false;
if (roleNames.includes('developer') || roleNames.includes('owner')) return true;
return permissions.some((p) => permissionNames.includes(p));
}
function hasRole(role: string): boolean {
if (!user) return false;
return roleNames.includes(role);
}
function hasAnyRole(roles: string[]): boolean {
if (!user) return false;
return roles.some((role) => roleNames.includes(role));
}
return { can, canAny, hasRole, hasAnyRole };
}