Refactor!: Codebase

This commit is contained in:
Kamigen
2024-03-30 21:35:19 -04:00
parent af35da4557
commit abab4587d1
11 changed files with 64 additions and 66 deletions

52
src/stores/auth.js Normal file
View File

@@ -0,0 +1,52 @@
import { defineStore } from 'pinia';
const baseUrl = '/api/Users';
export const auth = defineStore({
id: 'auth',
state: () => ({
user: null,
refreshTokenTimeout: null
}),
actions: {
async login(client, email, password) {
const requestBody = {
email: email,
password: password
};
try {
const response = await client.post(`${baseUrl}/login`, requestBody)
this.user = {
accessToken: response.data.accessToken,
refreshToken: response.data.refreshToken,
email: email
}
localStorage.setItem('jwt', this.user.accessToken);
this.startRefreshTokenTimer();
} catch (error) {
throw new Error('Login failed.')
}
},
logout() {
localStorage.setItem('jwt', '');
this.stopRefreshTokenTimer();
this.user = null;
},
async refreshToken(client) {
const response = await client.post(`${baseUrl}/refresh`, {});
this.user.accessToken = response.accessToken;
localStorage.setItem('jwt', this.user.accessToken);
this.startRefreshTokenTimer();
},
startRefreshTokenTimer() {
const timeout = 50 * 1000;
this.refreshTokenTimeout = setTimeout(this.refreshToken, timeout);
},
stopRefreshTokenTimer() {
clearTimeout(this.refreshTokenTimeout);
}
}
});