chore(frontend): Refactoring

Refactoring zodat de structuur van de authenticatieservice in de client duidelijker is.
This commit is contained in:
Gerald Schmittinger 2025-03-02 21:02:17 +01:00
parent a28ec22f29
commit 26d5c09bb4
19 changed files with 215 additions and 183 deletions

View file

@ -1,7 +1,8 @@
import axios from "axios";
import {apiConfig} from "@/config.ts";
const apiClient = axios.create({
baseURL: window.location.hostname == "localhost" ? "http://localhost:3000" : window.location.origin,
baseURL: apiConfig.baseUrl,
headers: {
"Content-Type": "application/json",
},

View file

@ -1,106 +0,0 @@
import {User, UserManager} from "oidc-client-ts";
import apiClient from "@/services/api-client.ts";
type FrontendAuthConfig = {
student: FrontendIdpConfig,
teacher: FrontendIdpConfig
}
type FrontendIdpConfig = {
authority: string,
clientId: string,
scope: string,
responseType: string
}
export type Role = "student" | "teacher";
type UserManagersForRoles = {student: UserManager, teacher: UserManager};
class AuthService {
constructor(private userManagers: UserManagersForRoles) {}
public async loginAs(role: Role) {
// Storing it in local storage so that it won't be lost when redirecting outside of the app.
this.setActiveRole(role);
await this.userManagers[role].signinRedirect();
}
public async logout() {
const activeRole = this.getActiveRole();
if (activeRole) {
await this.userManagers[activeRole].signoutRedirect();
this.deleteActiveRole();
}
}
public async getUser(): Promise<User | null> {
const activeRole = this.getActiveRole();
if (!activeRole) {
return null;
}
return await this.userManagers[activeRole].getUser();
}
public async getAccessToken(): Promise<string | null> {
const user = await this.getUser();
return user?.access_token || null;
}
async renewToken() {
const activeRole = this.getActiveRole();
if (!activeRole) {
throw new Error("Can't renew the token: Not logged in!");
}
return this.userManagers[activeRole].signinSilent();
}
public getActiveRole(): Role | undefined {
return localStorage.getItem("activeRole") as Role | undefined;
}
public async handleRedirectCallback(): Promise<User | undefined> {
const activeRole = this.getActiveRole();
if (!activeRole) {
throw new Error("Can't renew the token: Not logged in!");
}
return this.userManagers[activeRole].signinCallback();
}
private setActiveRole(role: Role) {
localStorage.setItem("activeRole", role);
}
private deleteActiveRole() {
localStorage.removeItem("activeRole");
}
}
async function initAuthService() {
const authConfig = await apiClient.get<FrontendAuthConfig>("auth/config").then(it => it.data);
const oidcConfig = {
student: {
authority: authConfig.student.authority,
client_id: authConfig.student.clientId,
redirect_uri: window.location.origin + "/callback",
response_type: authConfig.student.responseType,
scope: authConfig.student.scope,
post_logout_redirect_uri: window.location.origin,
},
teacher: {
authority: authConfig.teacher.authority,
client_id: authConfig.teacher.clientId,
redirect_uri: window.location.origin + "/callback",
response_type: authConfig.teacher.responseType,
scope: authConfig.teacher.scope,
post_logout_redirect_uri: window.location.origin,
}
};
return new AuthService({
student: new UserManager(oidcConfig.student),
teacher: new UserManager(oidcConfig.teacher)
});
}
export default await initAuthService();

View file

@ -0,0 +1,24 @@
import apiClient from "@/services/api-client.ts";
import type {AuthState} from "@/services/auth/auth-types.ts";
export function configureApiClientAuthInterceptors(authState: AuthState, renewToken: () => Promise<any>) {
apiClient.interceptors.request.use(async (reqConfig) => {
const token = authState?.user?.access_token;
if (token) {
reqConfig.headers.Authorization = `Bearer ${token}`;
}
return reqConfig;
}, (error) => Promise.reject(error));
apiClient.interceptors.response.use(
response => response,
async (error) => {
if (error.response?.status === 401) {
console.log("Access token expired, trying to refresh...");
await renewToken();
return apiClient(error.config); // Retry the request
}
return Promise.reject(error);
}
);
}

View file

@ -0,0 +1,24 @@
import apiClient from "@/services/api-client.ts";
import type {FrontendAuthConfig} from "@/services/auth/auth-types.ts";
export async function loadAuthConfig() {
const authConfig = (await apiClient.get<FrontendAuthConfig>("auth/config")).data;
return {
student: {
authority: authConfig.student.authority,
client_id: authConfig.student.clientId,
redirect_uri: window.location.origin + "/callback",
response_type: authConfig.student.responseType,
scope: authConfig.student.scope,
post_logout_redirect_uri: window.location.origin,
},
teacher: {
authority: authConfig.teacher.authority,
client_id: authConfig.teacher.clientId,
redirect_uri: window.location.origin + "/callback",
response_type: authConfig.teacher.responseType,
scope: authConfig.teacher.scope,
post_logout_redirect_uri: window.location.origin,
}
};
}

View file

@ -0,0 +1,77 @@
/**
* Service for all authentication- and authorization-related tasks.
*/
import {computed, reactive} from "vue";
import type {AuthState, Role, UserManagersForRoles} from "@/services/auth/auth-types.ts";
import {User, UserManager} from "oidc-client-ts";
import {loadAuthConfig} from "@/services/auth/auth-config-loader.ts";
import {configureApiClientAuthInterceptors} from "@/services/auth/auth-api-client-interceptors.ts";
import authStorage from "./auth-storage.ts"
const authConfig = await loadAuthConfig();
const userManagers: UserManagersForRoles = {
student: new UserManager(authConfig.student),
teacher: new UserManager(authConfig.teacher),
};
async function loadUser(): Promise<User | null> {
const activeRole = authStorage.getActiveRole();
if (!activeRole) {
return null;
}
let user = await userManagers[activeRole].getUser();
authState.user = user;
authState.accessToken = user?.access_token || null;
authState.activeRole = activeRole || null;
return user;
}
const authState = reactive<AuthState>({
user: null,
accessToken: null,
activeRole: authStorage.getActiveRole() || null
});
const isLoggedIn = computed(() => authState.user !== null);
async function loginAs(role: Role): Promise<void> {
// Storing it in local storage so that it won't be lost when redirecting outside of the app.
authStorage.setActiveRole(role);
await userManagers[role].signinRedirect();
}
async function handleLoginCallback(): Promise<void> {
const activeRole = authStorage.getActiveRole();
if (!activeRole) {
throw new Error("Can't renew the token: Not logged in!");
}
authState.user = await userManagers[activeRole].signinCallback() || null;
}
async function renewToken() {
const activeRole = authStorage.getActiveRole();
if (!activeRole) {
throw new Error("Can't renew the token: Not logged in!");
}
try {
return await userManagers[activeRole].signinSilent();
} catch (error) {
console.log("Can't renew the token:");
console.log(error);
await loginAs(activeRole);
}
}
async function logout(): Promise<void> {
const activeRole = authStorage.getActiveRole();
if (activeRole) {
await userManagers[activeRole].signoutRedirect();
authStorage.deleteActiveRole();
}
}
configureApiClientAuthInterceptors(authState, renewToken);
export default {authState, isLoggedIn, loadUser, handleLoginCallback, loginAs, logout};

View file

@ -0,0 +1,13 @@
import type {Role} from "@/services/auth/auth-types.ts";
export default {
getActiveRole(): Role | undefined {
return localStorage.getItem("activeRole") as Role | undefined;
},
setActiveRole(role: Role) {
localStorage.setItem("activeRole", role);
},
deleteActiveRole() {
localStorage.removeItem("activeRole");
}
}

View file

@ -0,0 +1,22 @@
import {type User, UserManager} from "oidc-client-ts";
export type AuthState = {
user: User | null,
accessToken: string | null,
activeRole: Role | null
};
export type FrontendAuthConfig = {
student: FrontendIdpConfig,
teacher: FrontendIdpConfig
};
export type FrontendIdpConfig = {
authority: string,
clientId: string,
scope: string,
responseType: string
};
export type Role = "student" | "teacher";
export type UserManagersForRoles = {student: UserManager, teacher: UserManager};