mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-20 13:32:00 +00:00
49 lines
1.2 KiB
TypeScript
49 lines
1.2 KiB
TypeScript
import { create } from 'zustand';
|
|
import { UserWithRoles } from '@/types/api/api-general';
|
|
|
|
type AuthStore = {
|
|
user?: UserWithRoles;
|
|
isLoadingUser?: boolean;
|
|
setUser: (newUserData?: UserWithRoles) => void;
|
|
setIsLoadingUser: (isLoading?: boolean) => void;
|
|
permissionCheck: (permissionName: string) => boolean;
|
|
};
|
|
|
|
const useAuthStore = create<AuthStore>()((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, permissionCheck } =
|
|
useAuthStore();
|
|
|
|
return {
|
|
user,
|
|
setUser,
|
|
isLoadingUser,
|
|
setIsLoadingUser,
|
|
permissionCheck,
|
|
};
|
|
};
|