65 lines
1.5 KiB
TypeScript
65 lines
1.5 KiB
TypeScript
import type { AuthState } from '~/utils/types';
|
|
|
|
export const useAuth = () => {
|
|
const authState = useState<AuthState>('auth.state', () => ({
|
|
authenticated: false,
|
|
user: null,
|
|
groups: [],
|
|
}));
|
|
|
|
const login = () => {
|
|
return navigateTo('/api/auth/login');
|
|
};
|
|
|
|
const logout = async () => {
|
|
try {
|
|
await $fetch('/api/auth/logout', { method: 'POST' });
|
|
authState.value = {
|
|
authenticated: false,
|
|
user: null,
|
|
groups: [],
|
|
};
|
|
await navigateTo('/login');
|
|
} catch (error) {
|
|
console.error('Logout error:', error);
|
|
await navigateTo('/login');
|
|
}
|
|
};
|
|
|
|
const checkAuth = async () => {
|
|
try {
|
|
const response = await $fetch<AuthState>('/api/auth/session');
|
|
authState.value = response;
|
|
return response.authenticated;
|
|
} catch (error) {
|
|
console.error('Auth check error:', error);
|
|
authState.value = {
|
|
authenticated: false,
|
|
user: null,
|
|
groups: [],
|
|
};
|
|
return false;
|
|
}
|
|
};
|
|
|
|
const isAdmin = computed(() => {
|
|
return authState.value.groups?.includes('admin') || false;
|
|
});
|
|
|
|
const hasRole = (role: string) => {
|
|
return authState.value.groups?.includes(role) || false;
|
|
};
|
|
|
|
return {
|
|
authState: readonly(authState),
|
|
user: computed(() => authState.value.user),
|
|
authenticated: computed(() => authState.value.authenticated),
|
|
groups: computed(() => authState.value.groups),
|
|
isAdmin,
|
|
hasRole,
|
|
login,
|
|
logout,
|
|
checkAuth,
|
|
};
|
|
};
|