77 lines
1.9 KiB
TypeScript
77 lines
1.9 KiB
TypeScript
import {defineStore} from 'pinia';
|
|
import {useApi} from "~/composables/fetch-api";
|
|
|
|
export interface Auth {
|
|
token: {
|
|
type: string;
|
|
value: string;
|
|
expireAt: Date;
|
|
},
|
|
refreshToken: string;
|
|
}
|
|
|
|
export interface User {
|
|
id: number
|
|
email: string;
|
|
username: string;
|
|
}
|
|
|
|
export const useAuthStore = defineStore('auth', {
|
|
state: () => ({
|
|
authenticated: ref<boolean>(useCookie("auth").value !== undefined),
|
|
auth: ref<Auth>(useCookie("auth").value),
|
|
user: ref<User>(useCookie("user").value)
|
|
}),
|
|
getters: {
|
|
},
|
|
actions: {
|
|
async login(email: string, password: string) {
|
|
return useApi('auth/login', {
|
|
method: 'post',
|
|
body: {
|
|
email,
|
|
password,
|
|
},
|
|
}, false).then(data => {
|
|
useCookie('auth').value = JSON.stringify(data);
|
|
this.authenticated = true;
|
|
this.auth = data;
|
|
useApi('auth/me').then(data => {
|
|
this.user = data;
|
|
useCookie("user").value = JSON.stringify(data)
|
|
});
|
|
});
|
|
},
|
|
logout() {
|
|
useApi('auth/logout', {
|
|
method: 'post',
|
|
body: {
|
|
userId: this.user.id,
|
|
},
|
|
}).finally(() => {
|
|
this.authenticated = false;
|
|
useCookie('auth').value = undefined;
|
|
useCookie("user").value = undefined;
|
|
});
|
|
},
|
|
refreshSession() {
|
|
// Use useFetch to not call
|
|
return useFetch('auth/refresh-token', {
|
|
baseURL: useRuntimeConfig().public.baseURL,
|
|
method: 'post',
|
|
body: {
|
|
refreshToken: this.auth.refreshToken,
|
|
},
|
|
}, false).then((response) => {
|
|
this.authenticated = true;
|
|
this.auth.token = response.data;
|
|
useCookie('auth').value = JSON.stringify(this.auth);
|
|
}).catch(() => {
|
|
this.authenticated = false;
|
|
useCookie('auth').value = undefined;
|
|
useCookie("user").value = undefined;
|
|
});
|
|
}
|
|
},
|
|
});
|