Cleaned up auth logic and fixed interval for token refreshing.

This commit is contained in:
Andrew Lalis 2023-03-29 09:28:34 +02:00
parent a001ef89e9
commit 4ec30b37f8
2 changed files with 43 additions and 6 deletions

View File

@ -1,8 +1,8 @@
import { api } from 'src/api/main/index';
import {AuthStoreType, useAuthStore} from 'stores/auth-store';
import {AuthStoreType} from 'stores/auth-store';
import Timeout = NodeJS.Timeout;
import { WeightUnit } from 'src/api/main/submission';
import {Page, PaginationOptions, toQueryParams} from "src/api/main/models";
import {Page, PaginationOptions, toQueryParams} from 'src/api/main/models';
export interface User {
id: string;
@ -91,14 +91,14 @@ class AuthModule {
authStore.roles = roles;
clearTimeout(this.tokenRefreshTimer);
this.tokenRefreshTimer = setTimeout(
this.tokenRefreshTimer = setInterval(
() => this.refreshToken(authStore),
AuthModule.TOKEN_REFRESH_INTERVAL_MS
);
}
public logout(authStore: AuthStoreType) {
authStore.$reset();
authStore.logOut();
clearTimeout(this.tokenRefreshTimer);
}
@ -118,8 +118,17 @@ class AuthModule {
}
public async refreshToken(authStore: AuthStoreType) {
try {
const response = await api.get('/auth/token', authStore.axiosConfig);
authStore.token = response.data.token;
} catch (error: any) {
authStore.logOut();
if (error.response) {
console.warn('Failed to refresh token: ', error.response);
} else {
console.error(error);
}
}
}
public async getMyUser(authStore: AuthStoreType): Promise<User> {

View File

@ -43,6 +43,34 @@ export const useAuthStore = defineStore('authStore', {
},
isAdmin: state => state.roles.indexOf('admin') !== -1,
},
actions: {
/**
* Logs a user into the application.
* @param user The user who was logged in.
* @param token The token that was obtained.
* @param roles The list of the user's roles.
*/
logIn(user: User, token: string, roles: string[]) {
this.user = user;
this.token = token;
this.roles = roles;
},
/**
* Logs a user out of the application, resetting the auth state.
*/
logOut() {
this.user = null;
this.token = null;
this.roles = [];
},
/**
* Updates the token that's stored for the currently authenticated user.
* @param token The new token.
*/
updateToken(token: string) {
this.token = token;
}
}
});
export type AuthStoreType = ReturnType<typeof useAuthStore>;