boussole-pluss/frontend/store/auth.ts

87 lines
2.2 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: {
isSessionExpired: (state) => {
if (!state.auth || !state.authenticated) return true;
const token = state.auth.token;
return new Date(token.expireAt).getTime() < new Date().getTime();
},
isLoggedIn: (state) => {
return state.auth && state.authenticated;
},
},
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
useCookie('auth').value = undefined;
useCookie("user").value = undefined;
useFetch('auth/refresh-token', {
method: 'post',
body: {
refreshToken: this.auth.refreshToken,
},
}, false).then((response) => {
this.authenticated = true;
this.auth.token = response;
useCookie('auth').value = JSON.stringify(this.auth);
}).catch(() => {
this.authenticated = false;
useCookie('auth').value = undefined;
useCookie("user").value = undefined;
});
}
},
});