Merge branch 'fix/verschillende-authenticatieproblemen' of https://github.com/SELab-2/Dwengo-1 into fix/verschillende-authenticatieproblemen

This commit is contained in:
Gerald Schmittinger 2025-04-19 17:06:50 +02:00
commit 58884ade3d
9 changed files with 23 additions and 15 deletions

View file

@ -4,7 +4,7 @@ import { AuthenticatedRequest } from '../middleware/auth/authenticated-request.j
import { createOrUpdateStudent } from '../services/students.js'; import { createOrUpdateStudent } from '../services/students.js';
import { createOrUpdateTeacher } from '../services/teachers.js'; import { createOrUpdateTeacher } from '../services/teachers.js';
import { envVars, getEnvVar } from '../util/envVars.js'; import { envVars, getEnvVar } from '../util/envVars.js';
import { Response } from "express"; import { Response } from 'express';
interface FrontendIdpConfig { interface FrontendIdpConfig {
authority: string; authority: string;
@ -43,20 +43,20 @@ export function getFrontendAuthConfig(): FrontendAuthConfig {
export async function postHelloHandler(req: AuthenticatedRequest, res: Response): Promise<void> { export async function postHelloHandler(req: AuthenticatedRequest, res: Response): Promise<void> {
const auth = req.auth; const auth = req.auth;
if (!auth) { if (!auth) {
throw new UnauthorizedException("Cannot say hello when not authenticated."); throw new UnauthorizedException('Cannot say hello when not authenticated.');
} }
const userData = { const userData = {
id: auth.username, id: auth.username,
username: auth.username, username: auth.username,
firstName: auth.firstName ?? '', firstName: auth.firstName ?? '',
lastName: auth.lastName ?? '' lastName: auth.lastName ?? '',
}; };
if (auth.accountType === "student") { if (auth.accountType === 'student') {
await createOrUpdateStudent(userData); await createOrUpdateStudent(userData);
logger.debug(`Synchronized student ${userData.username} with IDP`); logger.debug(`Synchronized student ${userData.username} with IDP`);
} else { } else {
await createOrUpdateTeacher(userData); await createOrUpdateTeacher(userData);
logger.debug(`Synchronized teacher ${userData.username} with IDP`); logger.debug(`Synchronized teacher ${userData.username} with IDP`);
} }
res.status(200).send({ message: "Welcome!" }); res.status(200).send({ message: 'Welcome!' });
} }

View file

@ -1,4 +1,4 @@
import { HasStatusCode } from "./has-status-code"; import { HasStatusCode } from './has-status-code';
/** /**
* Exceptions which are associated with a HTTP error code. * Exceptions which are associated with a HTTP error code.

View file

@ -1,5 +1,5 @@
export interface HasStatusCode { export interface HasStatusCode {
status: number status: number;
} }
export function hasStatusCode(err: unknown): err is HasStatusCode { export function hasStatusCode(err: unknown): err is HasStatusCode {
return typeof err === 'object' && err !== null && 'status' in err && typeof (err as HasStatusCode)?.status === 'number'; return typeof err === 'object' && err !== null && 'status' in err && typeof (err as HasStatusCode)?.status === 'number';

View file

@ -48,7 +48,7 @@ const idpConfigs = {
const verifyJwtToken = expressjwt({ const verifyJwtToken = expressjwt({
secret: async (_: express.Request, token: jwt.Jwt | undefined) => { secret: async (_: express.Request, token: jwt.Jwt | undefined) => {
if (!token?.payload || !(token.payload as JwtPayload).iss) { if (!token?.payload || !(token.payload as JwtPayload).iss) {
throw new UnauthorizedException("Invalid token.") throw new UnauthorizedException('Invalid token.');
} }
const issuer = (token.payload as JwtPayload).iss; const issuer = (token.payload as JwtPayload).iss;

View file

@ -71,7 +71,7 @@ export async function createOrUpdateStudent(userData: StudentDTO): Promise<Stude
await getStudentRepository().upsert({ await getStudentRepository().upsert({
username: userData.username, username: userData.username,
firstName: userData.firstName, firstName: userData.firstName,
lastName: userData.lastName lastName: userData.lastName,
}); });
return userData; return userData;
} }

View file

@ -70,7 +70,7 @@ export async function createOrUpdateTeacher(userData: TeacherDTO): Promise<Teach
await getTeacherRepository().upsert({ await getTeacherRepository().upsert({
username: userData.username, username: userData.username,
firstName: userData.firstName, firstName: userData.firstName,
lastName: userData.lastName lastName: userData.lastName,
}); });
return userData; return userData;
} }

View file

@ -139,7 +139,7 @@ const router = createRouter({
component: NotFound, component: NotFound,
meta: { requiresAuth: false }, meta: { requiresAuth: false },
}, },
] ],
}); });
router.beforeEach(async (to, _from, next) => { router.beforeEach(async (to, _from, next) => {

View file

@ -141,7 +141,7 @@ apiClient.interceptors.request.use(
// Registering interceptor to refresh the token when a request failed because it was expired. // Registering interceptor to refresh the token when a request failed because it was expired.
apiClient.interceptors.response.use( apiClient.interceptors.response.use(
(response) => response, (response) => response,
async (error: AxiosError<{ message?: string, inner?: {message?: string} }>) => { async (error: AxiosError<{ message?: string; inner?: { message?: string } }>) => {
if (error.response?.status === 401) { if (error.response?.status === 401) {
// If the user should already be logged in, his token is probably just expired. // If the user should already be logged in, his token is probably just expired.
if (isLoggedIn.value) { if (isLoggedIn.value) {

View file

@ -15,18 +15,26 @@
await auth.handleLoginCallback(); await auth.handleLoginCallback();
await router.replace("/user"); // Redirect to theme page await router.replace("/user"); // Redirect to theme page
} catch (error) { } catch (error) {
errorMessage.value = `${ t('loginUnexpectedError') }: ${error}`; errorMessage.value = `${t("loginUnexpectedError")}: ${error}`;
} }
}); });
</script> </script>
<template> <template>
<div class="callback"> <div class="callback">
<div class="callback-loading" v-if="!errorMessage"> <div
class="callback-loading"
v-if="!errorMessage"
>
<v-progress-circular indeterminate></v-progress-circular> <v-progress-circular indeterminate></v-progress-circular>
<p>{{ t("callbackLoading") }}</p> <p>{{ t("callbackLoading") }}</p>
</div> </div>
<v-alert icon="mdi-alert-circle" type="error" variant="elevated" v-if="errorMessage"> <v-alert
icon="mdi-alert-circle"
type="error"
variant="elevated"
v-if="errorMessage"
>
{{ errorMessage }} {{ errorMessage }}
</v-alert> </v-alert>
</div> </div>