Files
Nest-Intranet/stores/auth.ts

32 lines
827 B
TypeScript

import { defineStore } from 'pinia';
interface AuthUser {
id: string;
email: string;
username: string;
role: 'ADMIN' | 'DEV' | 'MEMBER';
}
export const useAuthStore = defineStore('auth', () => {
const user = ref<AuthUser | null>(null);
const token = ref<string | null>(null);
const isAuthenticated = computed(() => !!token.value);
async function login(credentials: { email: string; password: string }) {
const config = useRuntimeConfig();
const data = await $fetch<{ token: string; user: AuthUser }>(
`${config.public.apiBaseUrl}/auth/login`,
{ method: 'POST', body: credentials },
);
token.value = data.token;
user.value = data.user;
}
function logout() {
token.value = null;
user.value = null;
}
return { user, token, isAuthenticated, login, logout };
});