From 2b3aa9c3eed4a11593b1d75035acc81be3faf4ee Mon Sep 17 00:00:00 2001 From: ValdiANS Date: Sat, 18 Oct 2025 13:40:32 +0700 Subject: [PATCH] feat(FE-113): create permissionCheck helper function --- src/services/hooks/useAuth.tsx | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/src/services/hooks/useAuth.tsx b/src/services/hooks/useAuth.tsx index 86bf43ed..79fa8981 100644 --- a/src/services/hooks/useAuth.tsx +++ b/src/services/hooks/useAuth.tsx @@ -6,22 +6,43 @@ type AuthStore = { isLoadingUser?: boolean; setUser: (newUserData?: UserWithRoles) => void; setIsLoadingUser: (isLoading?: boolean) => void; + permissionCheck: (permissionName: string) => boolean; }; -const useAuthStore = create()((set) => ({ +const useAuthStore = create()((set, get) => ({ user: undefined, isLoadingUser: false, setUser: (newUserData) => set({ user: newUserData }), setIsLoadingUser: (isLoading) => set({ isLoadingUser: Boolean(isLoading) }), + + permissionCheck: (name) => { + const { user, isLoadingUser } = get(); + + if (!isLoadingUser && user) { + const isAllowed = user.roles.some((role) => { + const isPermissionNameAllowed = role.permissions.some( + (permission) => permission.name === name + ); + + return isPermissionNameAllowed; + }); + + return isAllowed; + } + + return false; + }, })); export const useAuth = () => { - const { user, setUser, isLoadingUser, setIsLoadingUser } = useAuthStore(); + const { user, setUser, isLoadingUser, setIsLoadingUser, permissionCheck } = + useAuthStore(); return { user, setUser, isLoadingUser, setIsLoadingUser, + permissionCheck, }; };