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

@ -12,14 +12,14 @@ import submissionRouter from './routes/submission.js';
import classRouter from './routes/class.js';
import questionRouter from './routes/question.js';
import authRouter from './routes/auth.js';
import {authenticateUser} from './middleware/auth/auth.js';
import { authenticateUser } from './middleware/auth/auth.js';
import cors from './middleware/cors.js';
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 {expressjwt} from 'express-jwt';
import {JwtPayload} from 'jsonwebtoken'
import { EnvVars, getEnvVar } from '../../util/envvars.js';
import { expressjwt } from 'express-jwt';
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
// Require additional libraries to be added.
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;
/**