style: fix linting issues met Prettier

This commit is contained in:
Lint Action 2025-03-10 11:20:14 +00:00
parent 394deba56d
commit 464dcbf73c
25 changed files with 5861 additions and 5062 deletions

View file

@ -18,8 +18,8 @@ import { getLogger, Logger } from './logging/initalize.js';
import { responseTimeLogger } from './logging/responseTimeLogger.js';
import responseTime from 'response-time';
import { EnvVars, getNumericEnvVar } from './util/envvars.js';
import swaggerMiddleware from "./swagger";
import swaggerUi from "swagger-ui-express";
import swaggerMiddleware from './swagger';
import swaggerUi from 'swagger-ui-express';
const logger: Logger = getLogger();
@ -50,8 +50,14 @@ app.use('/question', questionRouter /* #swagger.tags = ['Question'] */);
app.use('/auth', authRouter /* #swagger.tags = ['Auth'] */);
app.use('/theme', themeRoutes /* #swagger.tags = ['Theme'] */);
app.use('/learningPath', learningPathRoutes /* #swagger.tags = ['Learning Path'] */);
app.use('/learningObject', learningObjectRoutes /* #swagger.tags = ['Learning Object'] */);
app.use(
'/learningPath',
learningPathRoutes /* #swagger.tags = ['Learning Path'] */
);
app.use(
'/learningObject',
learningObjectRoutes /* #swagger.tags = ['Learning Object'] */
);
// Swagger UI for API documentation
app.use('/api-docs', swaggerUi.serve, swaggerMiddleware);

View file

@ -1,19 +1,19 @@
import {EnvVars, getEnvVar} from "../util/envvars.js";
import { EnvVars, getEnvVar } from '../util/envvars.js';
type FrontendIdpConfig = {
authority: string,
clientId: string,
scope: string,
responseType: string
}
authority: string;
clientId: string;
scope: string;
responseType: string;
};
type FrontendAuthConfig = {
student: FrontendIdpConfig,
teacher: FrontendIdpConfig
}
student: FrontendIdpConfig;
teacher: FrontendIdpConfig;
};
const SCOPE = "openid profile email";
const RESPONSE_TYPE = "code";
const SCOPE = 'openid profile email';
const RESPONSE_TYPE = 'code';
export function getFrontendAuthConfig(): FrontendAuthConfig {
return {
@ -21,13 +21,13 @@ export function getFrontendAuthConfig(): FrontendAuthConfig {
authority: getEnvVar(EnvVars.IdpStudentUrl),
clientId: getEnvVar(EnvVars.IdpStudentClientId),
scope: SCOPE,
responseType: RESPONSE_TYPE
responseType: RESPONSE_TYPE,
},
teacher: {
authority: getEnvVar(EnvVars.IdpTeacherUrl),
clientId: getEnvVar(EnvVars.IdpTeacherClientId),
scope: SCOPE,
responseType: RESPONSE_TYPE
responseType: RESPONSE_TYPE,
},
};
}

View file

@ -1,13 +1,13 @@
export class UnauthorizedException extends Error {
status = 401;
constructor(message: string = "Unauthorized") {
constructor(message: string = 'Unauthorized') {
super(message);
}
}
export class ForbiddenException extends Error {
status = 403;
constructor(message: string = "Forbidden") {
constructor(message: string = 'Forbidden') {
super(message);
}
}

View file

@ -1,25 +1,25 @@
import {EnvVars, getEnvVar} from "../../util/envvars.js";
import { EnvVars, getEnvVar } from '../../util/envvars.js';
import { expressjwt } from 'express-jwt';
import {JwtPayload} from 'jsonwebtoken'
import { JwtPayload } from 'jsonwebtoken';
import jwksClient from 'jwks-rsa';
import * as express from "express";
import * as jwt from "jsonwebtoken";
import {AuthenticatedRequest} from "./authenticated-request.js";
import {AuthenticationInfo} from "./authentication-info.js";
import {ForbiddenException, UnauthorizedException} from "../../exceptions";
import * as express from 'express';
import * as jwt from 'jsonwebtoken';
import { AuthenticatedRequest } from './authenticated-request.js';
import { AuthenticationInfo } from './authentication-info.js';
import { ForbiddenException, UnauthorizedException } from '../../exceptions';
const JWKS_CACHE = true;
const JWKS_RATE_LIMIT = true;
const REQUEST_PROPERTY_FOR_JWT_PAYLOAD = "jwtPayload";
const JWT_ALGORITHM = "RS256"; // Not configurable via env vars since supporting other algorithms would
const REQUEST_PROPERTY_FOR_JWT_PAYLOAD = 'jwtPayload';
const JWT_ALGORITHM = 'RS256'; // Not configurable via env vars since supporting other algorithms would
// Require additional libraries to be added.
const JWT_PROPERTY_NAMES = {
username: "preferred_username",
firstName: "given_name",
lastName: "family_name",
name: "name",
email: "email"
username: 'preferred_username',
firstName: 'given_name',
lastName: 'family_name',
name: 'name',
email: 'email',
};
function createJwksClient(uri: string): jwksClient.JwksClient {
@ -38,7 +38,7 @@ const idpConfigs = {
teacher: {
issuer: getEnvVar(EnvVars.IdpTeacherUrl),
jwksClient: createJwksClient(getEnvVar(EnvVars.IdpTeacherJwksEndpoint)),
}
},
};
/**
@ -47,42 +47,48 @@ const idpConfigs = {
const verifyJwtToken = expressjwt({
secret: async (_: express.Request, token: jwt.Jwt | undefined) => {
if (!token?.payload || !(token.payload as JwtPayload).iss) {
throw new Error("Invalid token");
throw new Error('Invalid token');
}
const issuer = (token.payload as JwtPayload).iss;
const idpConfig = Object.values(idpConfigs).find(config => {return config.issuer === issuer});
const idpConfig = Object.values(idpConfigs).find((config) => {
return config.issuer === issuer;
});
if (!idpConfig) {
throw new Error("Issuer not accepted.");
throw new Error('Issuer not accepted.');
}
const signingKey = await idpConfig.jwksClient.getSigningKey(token.header.kid);
const signingKey = await idpConfig.jwksClient.getSigningKey(
token.header.kid
);
if (!signingKey) {
throw new Error("Signing key not found.");
throw new Error('Signing key not found.');
}
return signingKey.getPublicKey();
},
audience: getEnvVar(EnvVars.IdpAudience),
algorithms: [JWT_ALGORITHM],
credentialsRequired: false,
requestProperty: REQUEST_PROPERTY_FOR_JWT_PAYLOAD
requestProperty: REQUEST_PROPERTY_FOR_JWT_PAYLOAD,
});
/**
* Get an object with information about the authenticated user from a given authenticated request.
*/
function getAuthenticationInfo(req: AuthenticatedRequest): AuthenticationInfo | undefined {
function getAuthenticationInfo(
req: AuthenticatedRequest
): AuthenticationInfo | undefined {
if (!req.jwtPayload) {
return;
}
const issuer = req.jwtPayload.iss;
let accountType: "student" | "teacher";
let accountType: 'student' | 'teacher';
if (issuer === idpConfigs.student.issuer) {
accountType = "student";
accountType = 'student';
} else if (issuer === idpConfigs.teacher.issuer) {
accountType = "teacher";
accountType = 'teacher';
} else {
return;
}
@ -93,14 +99,18 @@ function getAuthenticationInfo(req: AuthenticatedRequest): AuthenticationInfo |
firstName: req.jwtPayload[JWT_PROPERTY_NAMES.firstName],
lastName: req.jwtPayload[JWT_PROPERTY_NAMES.lastName],
email: req.jwtPayload[JWT_PROPERTY_NAMES.email],
}
};
}
/**
* Add the AuthenticationInfo object with the information about the current authentication to the request in order
* to avoid that the routers have to deal with the JWT token.
*/
const addAuthenticationInfo = (req: AuthenticatedRequest, res: express.Response, next: express.NextFunction) => {
const addAuthenticationInfo = (
req: AuthenticatedRequest,
res: express.Response,
next: express.NextFunction
) => {
req.auth = getAuthenticationInfo(req);
next();
};
@ -113,8 +123,14 @@ export const authenticateUser = [verifyJwtToken, addAuthenticationInfo];
* @param accessCondition Predicate over the current AuthenticationInfo. Access is only granted when this evaluates
* to true.
*/
export const authorize = (accessCondition: (auth: AuthenticationInfo) => boolean) => {
return (req: AuthenticatedRequest, res: express.Response, next: express.NextFunction): void => {
export const authorize = (
accessCondition: (auth: AuthenticationInfo) => boolean
) => {
return (
req: AuthenticatedRequest,
res: express.Response,
next: express.NextFunction
): void => {
if (!req.auth) {
throw new UnauthorizedException();
} else if (!accessCondition(req.auth)) {
@ -122,20 +138,26 @@ export const authorize = (accessCondition: (auth: AuthenticationInfo) => boolean
} else {
next();
}
}
}
};
};
/**
* Middleware which rejects all unauthenticated users, but accepts all authenticated users.
*/
export const authenticatedOnly = authorize(_ => {return true});
export const authenticatedOnly = authorize((_) => {
return true;
});
/**
* Middleware which rejects requests from unauthenticated users or users that aren't students.
*/
export const studentsOnly = authorize(auth => {return auth.accountType === "student"});
export const studentsOnly = authorize((auth) => {
return auth.accountType === 'student';
});
/**
* Middleware which rejects requests from unauthenticated users or users that aren't teachers.
*/
export const teachersOnly = authorize(auth => {return auth.accountType === "teacher"});
export const teachersOnly = authorize((auth) => {
return auth.accountType === 'teacher';
});

View file

@ -1,6 +1,6 @@
import { Request } from "express";
import { JwtPayload } from "jsonwebtoken";
import {AuthenticationInfo} from "./authentication-info.js";
import { Request } from 'express';
import { JwtPayload } from 'jsonwebtoken';
import { AuthenticationInfo } from './authentication-info.js';
export interface AuthenticatedRequest extends Request {
// Properties are optional since the user is not necessarily authenticated.

View file

@ -2,10 +2,10 @@
* Object with information about the user who is currently logged in.
*/
export type AuthenticationInfo = {
accountType: "student" | "teacher",
username: string,
name?: string,
firstName?: string,
lastName?: string,
email?: string
accountType: 'student' | 'teacher';
username: string;
name?: string;
firstName?: string;
lastName?: string;
email?: string;
};

View file

@ -1,7 +1,7 @@
import cors from "cors";
import {EnvVars, getEnvVar} from "../util/envvars.js";
import cors from 'cors';
import { EnvVars, getEnvVar } from '../util/envvars.js';
export default cors({
origin: getEnvVar(EnvVars.CorsAllowedOrigins).split(','),
allowedHeaders: getEnvVar(EnvVars.CorsAllowedHeaders).split(',')
allowedHeaders: getEnvVar(EnvVars.CorsAllowedHeaders).split(','),
});

View file

@ -1,6 +1,10 @@
import express from 'express'
import {getFrontendAuthConfig} from "../controllers/auth.js";
import {authenticatedOnly, studentsOnly, teachersOnly} from "../middleware/auth/auth.js";
import express from 'express';
import { getFrontendAuthConfig } from '../controllers/auth.js';
import {
authenticatedOnly,
studentsOnly,
teachersOnly,
} from '../middleware/auth/auth.js';
const router = express.Router();
// Returns auth configuration for frontend
@ -10,17 +14,17 @@ router.get('/config', (req, res) => {
router.get('/testAuthenticatedOnly', authenticatedOnly, (req, res) => {
/* #swagger.security = [{ "student": [ ] }, { "teacher": [ ] }] */
res.json({message: "If you see this, you should be authenticated!"});
res.json({ message: 'If you see this, you should be authenticated!' });
});
router.get('/testStudentsOnly', studentsOnly, (req, res) => {
/* #swagger.security = [{ "student": [ ] }] */
res.json({message: "If you see this, you should be a student!"});
res.json({ message: 'If you see this, you should be a student!' });
});
router.get('/testTeachersOnly', teachersOnly, (req, res) => {
/* #swagger.security = [{ "teacher": [ ] }] */
res.json({message: "If you see this, you should be a teacher!"});
res.json({ message: 'If you see this, you should be a teacher!' });
});
export default router;

View file

@ -16,14 +16,32 @@ export const EnvVars: { [key: string]: EnvVar } = {
DbPassword: { key: DB_PREFIX + 'PASSWORD', required: true },
DbUpdate: { key: DB_PREFIX + 'UPDATE', defaultValue: false },
IdpStudentUrl: { key: STUDENT_IDP_PREFIX + 'URL', required: true },
IdpStudentClientId: { key: STUDENT_IDP_PREFIX + 'CLIENT_ID', required: true },
IdpStudentJwksEndpoint: { key: STUDENT_IDP_PREFIX + 'JWKS_ENDPOINT', required: true },
IdpStudentClientId: {
key: STUDENT_IDP_PREFIX + 'CLIENT_ID',
required: true,
},
IdpStudentJwksEndpoint: {
key: STUDENT_IDP_PREFIX + 'JWKS_ENDPOINT',
required: true,
},
IdpTeacherUrl: { key: TEACHER_IDP_PREFIX + 'URL', required: true },
IdpTeacherClientId: { key: TEACHER_IDP_PREFIX + 'CLIENT_ID', required: true },
IdpTeacherJwksEndpoint: { key: TEACHER_IDP_PREFIX + 'JWKS_ENDPOINT', required: true },
IdpTeacherClientId: {
key: TEACHER_IDP_PREFIX + 'CLIENT_ID',
required: true,
},
IdpTeacherJwksEndpoint: {
key: TEACHER_IDP_PREFIX + 'JWKS_ENDPOINT',
required: true,
},
IdpAudience: { key: IDP_PREFIX + 'AUDIENCE', defaultValue: 'account' },
CorsAllowedOrigins: { key: CORS_PREFIX + 'ALLOWED_ORIGINS', defaultValue: ''},
CorsAllowedHeaders: { key: CORS_PREFIX + 'ALLOWED_HEADERS', defaultValue: 'Authorization,Content-Type'}
CorsAllowedOrigins: {
key: CORS_PREFIX + 'ALLOWED_ORIGINS',
defaultValue: '',
},
CorsAllowedHeaders: {
key: CORS_PREFIX + 'ALLOWED_HEADERS',
defaultValue: 'Authorization,Content-Type',
},
} as const;
/**

View file

@ -27,11 +27,14 @@ services:
interval: 15s
timeout: 2s
retries: 15
command: [
command:
[
'start-dev',
'--http-port', '7080',
'--https-port', '7443',
'--import-realm'
'--http-port',
'7080',
'--https-port',
'7443',
'--import-realm',
]
ports:
- '7080:7080'

View file

@ -1,4 +1,4 @@
import swaggerAutogen from "swagger-autogen";
import swaggerAutogen from 'swagger-autogen';
const doc = {
info: {
@ -7,18 +7,18 @@ const doc = {
description: 'Dwengo-1 Backend API using Express, based on VZW Dwengo',
license: {
name: 'MIT',
url: 'https://github.com/SELab-2/Dwengo-1/blob/336496ab6352ee3f8bf47490c90b5cf81526cef6/LICENSE'
}
url: 'https://github.com/SELab-2/Dwengo-1/blob/336496ab6352ee3f8bf47490c90b5cf81526cef6/LICENSE',
},
},
servers: [
{
url: 'http://localhost:3000/',
description: 'Development server'
description: 'Development server',
},
{
url: 'https://sel2-1.ugent.be/api',
description: 'Production server'
}
description: 'Production server',
},
],
components: {
securitySchemes: {
@ -26,35 +26,35 @@ const doc = {
type: 'oauth2',
flows: {
implicit: {
authorizationUrl: 'http://localhost:7080/realms/student/protocol/openid-connect/auth',
authorizationUrl:
'http://localhost:7080/realms/student/protocol/openid-connect/auth',
scopes: {
openid: 'openid',
profile: 'profile',
email: 'email'
}
}
}
email: 'email',
},
},
},
},
teacher: {
type: 'oauth2',
flows: {
implicit: {
authorizationUrl: 'http://localhost:7080/realms/teacher/protocol/openid-connect/auth',
authorizationUrl:
'http://localhost:7080/realms/teacher/protocol/openid-connect/auth',
scopes: {
openid: 'openid',
profile: 'profile',
email: 'email'
}
}
}
}
}
}
email: 'email',
},
},
},
},
},
},
};
const outputFile = './swagger.json';
const routes = [
'../../backend/src/app.ts'
];
const routes = ['../../backend/src/app.ts'];
swaggerAutogen({ openapi: '3.1.0' })(outputFile, routes, doc);

View file

@ -32,9 +32,7 @@
},
"/student/": {
"get": {
"tags": [
"Student"
],
"tags": ["Student"],
"description": "",
"responses": {
"200": {
@ -45,9 +43,7 @@
},
"/student/{id}": {
"get": {
"tags": [
"Student"
],
"tags": ["Student"],
"description": "",
"parameters": [
{
@ -68,9 +64,7 @@
},
"/student/{id}/classes": {
"get": {
"tags": [
"Student"
],
"tags": ["Student"],
"description": "",
"parameters": [
{
@ -91,9 +85,7 @@
},
"/student/{id}/submissions": {
"get": {
"tags": [
"Student"
],
"tags": ["Student"],
"description": "",
"parameters": [
{
@ -114,9 +106,7 @@
},
"/student/{id}/assignments": {
"get": {
"tags": [
"Student"
],
"tags": ["Student"],
"description": "",
"parameters": [
{
@ -137,9 +127,7 @@
},
"/student/{id}/groups": {
"get": {
"tags": [
"Student"
],
"tags": ["Student"],
"description": "",
"parameters": [
{
@ -160,9 +148,7 @@
},
"/group/": {
"get": {
"tags": [
"Group"
],
"tags": ["Group"],
"description": "",
"responses": {
"200": {
@ -173,9 +159,7 @@
},
"/group/{id}": {
"get": {
"tags": [
"Group"
],
"tags": ["Group"],
"description": "",
"parameters": [
{
@ -196,9 +180,7 @@
},
"/group/{id}/question": {
"get": {
"tags": [
"Group"
],
"tags": ["Group"],
"description": "",
"parameters": [
{
@ -219,9 +201,7 @@
},
"/assignment/": {
"get": {
"tags": [
"Assignment"
],
"tags": ["Assignment"],
"description": "",
"responses": {
"200": {
@ -232,9 +212,7 @@
},
"/assignment/{id}": {
"get": {
"tags": [
"Assignment"
],
"tags": ["Assignment"],
"description": "",
"parameters": [
{
@ -255,9 +233,7 @@
},
"/assignment/{id}/submissions": {
"get": {
"tags": [
"Assignment"
],
"tags": ["Assignment"],
"description": "",
"parameters": [
{
@ -278,9 +254,7 @@
},
"/assignment/{id}/groups": {
"get": {
"tags": [
"Assignment"
],
"tags": ["Assignment"],
"description": "",
"parameters": [
{
@ -301,9 +275,7 @@
},
"/assignment/{id}/questions": {
"get": {
"tags": [
"Assignment"
],
"tags": ["Assignment"],
"description": "",
"parameters": [
{
@ -324,9 +296,7 @@
},
"/submission/": {
"get": {
"tags": [
"Submission"
],
"tags": ["Submission"],
"description": "",
"responses": {
"200": {
@ -337,9 +307,7 @@
},
"/submission/{id}": {
"get": {
"tags": [
"Submission"
],
"tags": ["Submission"],
"description": "",
"parameters": [
{
@ -360,9 +328,7 @@
},
"/class/": {
"get": {
"tags": [
"Class"
],
"tags": ["Class"],
"description": "",
"responses": {
"200": {
@ -373,9 +339,7 @@
},
"/class/{id}": {
"get": {
"tags": [
"Class"
],
"tags": ["Class"],
"description": "",
"parameters": [
{
@ -396,9 +360,7 @@
},
"/class/{id}/invitations": {
"get": {
"tags": [
"Class"
],
"tags": ["Class"],
"description": "",
"parameters": [
{
@ -419,9 +381,7 @@
},
"/class/{id}/assignments": {
"get": {
"tags": [
"Class"
],
"tags": ["Class"],
"description": "",
"parameters": [
{
@ -442,9 +402,7 @@
},
"/class/{id}/students": {
"get": {
"tags": [
"Class"
],
"tags": ["Class"],
"description": "",
"parameters": [
{
@ -465,9 +423,7 @@
},
"/question/": {
"get": {
"tags": [
"Question"
],
"tags": ["Question"],
"description": "",
"responses": {
"200": {
@ -478,9 +434,7 @@
},
"/question/{id}": {
"get": {
"tags": [
"Question"
],
"tags": ["Question"],
"description": "",
"parameters": [
{
@ -501,9 +455,7 @@
},
"/question/{id}/answers": {
"get": {
"tags": [
"Question"
],
"tags": ["Question"],
"description": "",
"parameters": [
{
@ -524,9 +476,7 @@
},
"/auth/config": {
"get": {
"tags": [
"Auth"
],
"tags": ["Auth"],
"description": "",
"responses": {
"200": {
@ -537,9 +487,7 @@
},
"/auth/testAuthenticatedOnly": {
"get": {
"tags": [
"Auth"
],
"tags": ["Auth"],
"description": "",
"responses": {
"200": {
@ -558,9 +506,7 @@
},
"/auth/testStudentsOnly": {
"get": {
"tags": [
"Auth"
],
"tags": ["Auth"],
"description": "",
"responses": {
"200": {
@ -576,9 +522,7 @@
},
"/auth/testTeachersOnly": {
"get": {
"tags": [
"Auth"
],
"tags": ["Auth"],
"description": "",
"responses": {
"200": {
@ -594,9 +538,7 @@
},
"/theme/": {
"get": {
"tags": [
"Theme"
],
"tags": ["Theme"],
"description": "",
"parameters": [
{
@ -616,9 +558,7 @@
},
"/theme/{theme}": {
"get": {
"tags": [
"Theme"
],
"tags": ["Theme"],
"description": "",
"parameters": [
{
@ -642,9 +582,7 @@
},
"/learningPath/": {
"get": {
"tags": [
"Learning Path"
],
"tags": ["Learning Path"],
"description": "",
"parameters": [
{
@ -691,9 +629,7 @@
},
"/learningObject/": {
"get": {
"tags": [
"Learning Object"
],
"tags": ["Learning Object"],
"description": "",
"parameters": [
{
@ -733,9 +669,7 @@
},
"/learningObject/{hruid}": {
"get": {
"tags": [
"Learning Object"
],
"tags": ["Learning Object"],
"description": "",
"parameters": [
{

View file

@ -1,5 +1,5 @@
export const apiConfig = {
baseUrl: window.location.hostname == "localhost" ? "http://localhost:3000" : window.location.origin
}
baseUrl: window.location.hostname == "localhost" ? "http://localhost:3000" : window.location.origin,
};
export const loginRoute = "/login";

View file

@ -36,7 +36,7 @@ const router = createRouter({
},
{
path: "/callback",
component: CallbackPage
component: CallbackPage,
},
{
path: "/student/:id",

View file

@ -22,6 +22,6 @@ export async function loadAuthConfig() {
response_type: authConfig.teacher.responseType,
scope: authConfig.teacher.scope,
post_logout_redirect_uri: window.location.origin,
}
},
};
}

View file

@ -6,7 +6,7 @@ import {computed, reactive} from "vue";
import type { AuthState, Role, UserManagersForRoles } from "@/services/auth/auth.d.ts";
import { User, UserManager } from "oidc-client-ts";
import { loadAuthConfig } from "@/services/auth/auth-config-loader.ts";
import authStorage from "./auth-storage.ts"
import authStorage from "./auth-storage.ts";
import { loginRoute } from "@/config.ts";
import apiClient from "@/services/api-client.ts";
import router from "@/router";
@ -40,10 +40,12 @@ async function loadUser(): Promise<User | null> {
const authState = reactive<AuthState>({
user: null,
accessToken: null,
activeRole: authStorage.getActiveRole() || null
activeRole: authStorage.getActiveRole() || null,
});
const isLoggedIn = computed(() => {return authState.user !== null});
const isLoggedIn = computed(() => {
return authState.user !== null;
});
/**
* Redirect the user to the login page where he/she can choose whether to log in as a student or teacher.
@ -70,7 +72,7 @@ async function handleLoginCallback(): Promise<void> {
if (!activeRole) {
throw new Error("Login callback received, but the user is not logging in!");
}
authState.user = await userManagers[activeRole].signinCallback() || null;
authState.user = (await userManagers[activeRole].signinCallback()) || null;
}
/**
@ -104,17 +106,24 @@ async function logout(): Promise<void> {
}
// Registering interceptor to add the authorization header to each request when the user is logged in.
apiClient.interceptors.request.use(async (reqConfig) => {
apiClient.interceptors.request.use(
async (reqConfig) => {
const token = authState?.user?.access_token;
if (token) {
reqConfig.headers.Authorization = `Bearer ${token}`;
}
return reqConfig;
}, (error) => {return Promise.reject(error)});
},
(error) => {
return Promise.reject(error);
},
);
// Registering interceptor to refresh the token when a request failed because it was expired.
apiClient.interceptors.response.use(
response => {return response},
(response) => {
return response;
},
async (error: AxiosError<{ message?: string }>) => {
if (error.response?.status === 401) {
if (error.response!.data.message === "token_expired") {
@ -122,11 +131,10 @@ apiClient.interceptors.response.use(
await renewToken();
return apiClient(error.config!); // Retry the request
} // Apparently, the user got a 401 because he was not logged in yet at all. Redirect him to login.
await initiateLogin()
await initiateLogin();
}
return Promise.reject(error);
}
},
);
export default { authState, isLoggedIn, initiateLogin, loadUser, handleLoginCallback, loginAs, logout };

View file

@ -22,5 +22,5 @@ export default {
*/
deleteActiveRole() {
localStorage.removeItem("activeRole");
}
}
},
};

View file

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

View file

@ -1,7 +1,7 @@
<script setup lang="ts">
import { useRouter } from "vue-router";
import { onMounted } from "vue";
import auth from "../services/auth/auth-service.ts"
import auth from "../services/auth/auth-service.ts";
const router = useRouter();
@ -19,6 +19,4 @@
<p>Logging you in...</p>
</template>
<style scoped>
</style>
<style scoped></style>

View file

@ -6,7 +6,7 @@
const testResponse = ref(null);
async function testAuthenticated() {
testResponse.value = await apiClient.get("/auth/testAuthenticatedOnly")
testResponse.value = await apiClient.get("/auth/testAuthenticatedOnly");
}
</script>
@ -16,7 +16,9 @@
<b>Welcome to the dwengo homepage</b>
<div v-if="auth.isLoggedIn.value">
<p>Hello {{ auth.authState.user?.profile.name }}!</p>
<p>Your access token for the backend is: <code>{{auth.authState.user?.access_token}}</code></p>
<p>
Your access token for the backend is: <code>{{ auth.authState.user?.access_token }}</code>
</p>
</div>
<v-btn @click="testAuthenticated">Send test request</v-btn>

View file

@ -23,7 +23,9 @@
<v-btn @click="loginAsTeacher">Login as teacher</v-btn>
</div>
<div v-if="auth.isLoggedIn.value">
<p>You are currently logged in as {{ auth.authState.user!.profile.name }} ({{ auth.authState.activeRole }})</p>
<p>
You are currently logged in as {{ auth.authState.user!.profile.name }} ({{ auth.authState.activeRole }})
</p>
<v-btn @click="performLogout">Logout</v-btn>
</div>
</main>

View file

@ -1,7 +1,9 @@
# Testdata in de IDP
De IDP in `docker-compose.yml` is zo geconfigureerd dat hij automatisch bij het starten een testconfiguratie inlaadt. Deze houdt in:
* Een realm `student` die de IDP voor leerlingen representeert.
* Hierin de gebruiker met username `testleerling1`, wachtwoord `password`.
* Een realm `teacher` die de IDP voor leerkrachten representeert.
* Hierin de gebruiker met username `testleerkracht1`, wachtwoord `password`.
* De admin-account (in de realm `master`) heeft username `admin` en wachtwoord `admin`.
- Een realm `student` die de IDP voor leerlingen representeert.
- Hierin de gebruiker met username `testleerling1`, wachtwoord `password`.
- Een realm `teacher` die de IDP voor leerkrachten representeert.
- Hierin de gebruiker met username `testleerkracht1`, wachtwoord `password`.
- De admin-account (in de realm `master`) heeft username `admin` en wachtwoord `admin`.

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff