Merge branch 'dev' into chore/docker
This commit is contained in:
		
						commit
						ef3d2b67c3
					
				
					 30 changed files with 5615 additions and 43 deletions
				
			
		|  | @ -11,7 +11,9 @@ import assignmentRouter from './routes/assignment.js'; | |||
| import submissionRouter from './routes/submission.js'; | ||||
| import classRouter from './routes/class.js'; | ||||
| import questionRouter from './routes/question.js'; | ||||
| import loginRouter from './routes/login.js'; | ||||
| import authRouter from './routes/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'; | ||||
|  | @ -22,8 +24,10 @@ const logger: Logger = getLogger(); | |||
| const app: Express = express(); | ||||
| const port: string | number = getNumericEnvVar(EnvVars.Port); | ||||
| 
 | ||||
| app.use(cors); | ||||
| app.use(express.json()); | ||||
| app.use(responseTime(responseTimeLogger)); | ||||
| app.use(authenticateUser); | ||||
| 
 | ||||
| // TODO Replace with Express routes
 | ||||
| app.get('/', (_, res: Response) => { | ||||
|  | @ -39,8 +43,7 @@ app.use('/assignment', assignmentRouter); | |||
| app.use('/submission', submissionRouter); | ||||
| app.use('/class', classRouter); | ||||
| app.use('/question', questionRouter); | ||||
| app.use('/login', loginRouter); | ||||
| 
 | ||||
| app.use('/auth', authRouter); | ||||
| app.use('/theme', themeRoutes); | ||||
| app.use('/learningPath', learningPathRoutes); | ||||
| app.use('/learningObject', learningObjectRoutes); | ||||
|  |  | |||
							
								
								
									
										33
									
								
								backend/src/controllers/auth.ts
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										33
									
								
								backend/src/controllers/auth.ts
									
										
									
									
									
										Normal file
									
								
							|  | @ -0,0 +1,33 @@ | |||
| import { EnvVars, getEnvVar } from '../util/envvars.js'; | ||||
| 
 | ||||
| type FrontendIdpConfig = { | ||||
|     authority: string; | ||||
|     clientId: string; | ||||
|     scope: string; | ||||
|     responseType: string; | ||||
| }; | ||||
| 
 | ||||
| type FrontendAuthConfig = { | ||||
|     student: FrontendIdpConfig; | ||||
|     teacher: FrontendIdpConfig; | ||||
| }; | ||||
| 
 | ||||
| const SCOPE = 'openid profile email'; | ||||
| const RESPONSE_TYPE = 'code'; | ||||
| 
 | ||||
| export function getFrontendAuthConfig(): FrontendAuthConfig { | ||||
|     return { | ||||
|         student: { | ||||
|             authority: getEnvVar(EnvVars.IdpStudentUrl), | ||||
|             clientId: getEnvVar(EnvVars.IdpStudentClientId), | ||||
|             scope: SCOPE, | ||||
|             responseType: RESPONSE_TYPE, | ||||
|         }, | ||||
|         teacher: { | ||||
|             authority: getEnvVar(EnvVars.IdpTeacherUrl), | ||||
|             clientId: getEnvVar(EnvVars.IdpTeacherClientId), | ||||
|             scope: SCOPE, | ||||
|             responseType: RESPONSE_TYPE, | ||||
|         }, | ||||
|     }; | ||||
| } | ||||
							
								
								
									
										13
									
								
								backend/src/exceptions.ts
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										13
									
								
								backend/src/exceptions.ts
									
										
									
									
									
										Normal file
									
								
							|  | @ -0,0 +1,13 @@ | |||
| export class UnauthorizedException extends Error { | ||||
|     status = 401; | ||||
|     constructor(message: string = 'Unauthorized') { | ||||
|         super(message); | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| export class ForbiddenException extends Error { | ||||
|     status = 403; | ||||
|     constructor(message: string = 'Forbidden') { | ||||
|         super(message); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										141
									
								
								backend/src/middleware/auth/auth.ts
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										141
									
								
								backend/src/middleware/auth/auth.ts
									
										
									
									
									
										Normal file
									
								
							|  | @ -0,0 +1,141 @@ | |||
| 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'; | ||||
| 
 | ||||
| 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 JWT_PROPERTY_NAMES = { | ||||
|     username: 'preferred_username', | ||||
|     firstName: 'given_name', | ||||
|     lastName: 'family_name', | ||||
|     name: 'name', | ||||
|     email: 'email', | ||||
| }; | ||||
| 
 | ||||
| function createJwksClient(uri: string): jwksClient.JwksClient { | ||||
|     return jwksClient({ | ||||
|         cache: JWKS_CACHE, | ||||
|         rateLimit: JWKS_RATE_LIMIT, | ||||
|         jwksUri: uri, | ||||
|     }); | ||||
| } | ||||
| 
 | ||||
| const idpConfigs = { | ||||
|     student: { | ||||
|         issuer: getEnvVar(EnvVars.IdpStudentUrl), | ||||
|         jwksClient: createJwksClient(getEnvVar(EnvVars.IdpStudentJwksEndpoint)), | ||||
|     }, | ||||
|     teacher: { | ||||
|         issuer: getEnvVar(EnvVars.IdpTeacherUrl), | ||||
|         jwksClient: createJwksClient(getEnvVar(EnvVars.IdpTeacherJwksEndpoint)), | ||||
|     }, | ||||
| }; | ||||
| 
 | ||||
| /** | ||||
|  * Express middleware which verifies the JWT Bearer token if one is given in the request. | ||||
|  */ | ||||
| const verifyJwtToken = expressjwt({ | ||||
|     secret: async (_: express.Request, token: jwt.Jwt | undefined) => { | ||||
|         if (!token?.payload || !(token.payload as JwtPayload).iss) { | ||||
|             throw new Error('Invalid token'); | ||||
|         } | ||||
| 
 | ||||
|         const issuer = (token.payload as JwtPayload).iss; | ||||
| 
 | ||||
|         const idpConfig = Object.values(idpConfigs).find((config) => config.issuer === issuer); | ||||
|         if (!idpConfig) { | ||||
|             throw new Error('Issuer not accepted.'); | ||||
|         } | ||||
| 
 | ||||
|         const signingKey = await idpConfig.jwksClient.getSigningKey(token.header.kid); | ||||
|         if (!signingKey) { | ||||
|             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, | ||||
| }); | ||||
| 
 | ||||
| /** | ||||
|  * Get an object with information about the authenticated user from a given authenticated request. | ||||
|  */ | ||||
| function getAuthenticationInfo(req: AuthenticatedRequest): AuthenticationInfo | undefined { | ||||
|     if (!req.jwtPayload) { | ||||
|         return; | ||||
|     } | ||||
|     const issuer = req.jwtPayload.iss; | ||||
|     let accountType: 'student' | 'teacher'; | ||||
| 
 | ||||
|     if (issuer === idpConfigs.student.issuer) { | ||||
|         accountType = 'student'; | ||||
|     } else if (issuer === idpConfigs.teacher.issuer) { | ||||
|         accountType = 'teacher'; | ||||
|     } else { | ||||
|         return; | ||||
|     } | ||||
|     return { | ||||
|         accountType: accountType, | ||||
|         username: req.jwtPayload[JWT_PROPERTY_NAMES.username]!, | ||||
|         name: req.jwtPayload[JWT_PROPERTY_NAMES.name], | ||||
|         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) => { | ||||
|     req.auth = getAuthenticationInfo(req); | ||||
|     next(); | ||||
| }; | ||||
| 
 | ||||
| export const authenticateUser = [verifyJwtToken, addAuthenticationInfo]; | ||||
| 
 | ||||
| /** | ||||
|  * Middleware which rejects unauthenticated users (with HTTP 401) and authenticated users which do not fulfill | ||||
|  * the given access condition. | ||||
|  * @param accessCondition Predicate over the current AuthenticationInfo. Access is only granted when this evaluates | ||||
|  *                        to true. | ||||
|  */ | ||||
| export const authorize = | ||||
|     (accessCondition: (auth: AuthenticationInfo) => boolean) => | ||||
|     (req: AuthenticatedRequest, res: express.Response, next: express.NextFunction): void => { | ||||
|         if (!req.auth) { | ||||
|             throw new UnauthorizedException(); | ||||
|         } else if (!accessCondition(req.auth)) { | ||||
|             throw new ForbiddenException(); | ||||
|         } else { | ||||
|             next(); | ||||
|         } | ||||
|     }; | ||||
| 
 | ||||
| /** | ||||
|  * Middleware which rejects all unauthenticated users, but accepts all authenticated users. | ||||
|  */ | ||||
| export const authenticatedOnly = authorize((_) => true); | ||||
| 
 | ||||
| /** | ||||
|  * Middleware which rejects requests from unauthenticated users or users that aren't students. | ||||
|  */ | ||||
| export const studentsOnly = authorize((auth) => auth.accountType === 'student'); | ||||
| 
 | ||||
| /** | ||||
|  * Middleware which rejects requests from unauthenticated users or users that aren't teachers. | ||||
|  */ | ||||
| export const teachersOnly = authorize((auth) => auth.accountType === 'teacher'); | ||||
							
								
								
									
										9
									
								
								backend/src/middleware/auth/authenticated-request.d.ts
									
										
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										9
									
								
								backend/src/middleware/auth/authenticated-request.d.ts
									
										
									
									
										vendored
									
									
										Normal file
									
								
							|  | @ -0,0 +1,9 @@ | |||
| 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.
 | ||||
|     jwtPayload?: JwtPayload; | ||||
|     auth?: AuthenticationInfo; | ||||
| } | ||||
							
								
								
									
										11
									
								
								backend/src/middleware/auth/authentication-info.d.ts
									
										
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										11
									
								
								backend/src/middleware/auth/authentication-info.d.ts
									
										
									
									
										vendored
									
									
										Normal file
									
								
							|  | @ -0,0 +1,11 @@ | |||
| /** | ||||
|  * 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; | ||||
| }; | ||||
							
								
								
									
										7
									
								
								backend/src/middleware/cors.ts
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										7
									
								
								backend/src/middleware/cors.ts
									
										
									
									
									
										Normal file
									
								
							|  | @ -0,0 +1,7 @@ | |||
| import cors from 'cors'; | ||||
| import { EnvVars, getEnvVar } from '../util/envvars.js'; | ||||
| 
 | ||||
| export default cors({ | ||||
|     origin: getEnvVar(EnvVars.CorsAllowedOrigins).split(','), | ||||
|     allowedHeaders: getEnvVar(EnvVars.CorsAllowedHeaders).split(','), | ||||
| }); | ||||
							
								
								
									
										23
									
								
								backend/src/routes/auth.ts
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										23
									
								
								backend/src/routes/auth.ts
									
										
									
									
									
										Normal file
									
								
							|  | @ -0,0 +1,23 @@ | |||
| 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
 | ||||
| router.get('/config', (req, res) => { | ||||
|     res.json(getFrontendAuthConfig()); | ||||
| }); | ||||
| 
 | ||||
| router.get('/testAuthenticatedOnly', authenticatedOnly, (req, res) => { | ||||
|     res.json({ message: 'If you see this, you should be authenticated!' }); | ||||
| }); | ||||
| 
 | ||||
| router.get('/testStudentsOnly', studentsOnly, (req, res) => { | ||||
|     res.json({ message: 'If you see this, you should be a student!' }); | ||||
| }); | ||||
| 
 | ||||
| router.get('/testTeachersOnly', teachersOnly, (req, res) => { | ||||
|     res.json({ message: 'If you see this, you should be a teacher!' }); | ||||
| }); | ||||
| 
 | ||||
| export default router; | ||||
|  | @ -1,14 +0,0 @@ | |||
| import express from 'express'; | ||||
| const router = express.Router(); | ||||
| 
 | ||||
| // Returns login paths for IDP
 | ||||
| router.get('/', (req, res) => { | ||||
|     res.json({ | ||||
|         // Dummy variables, needs to be changed
 | ||||
|         // With IDP endpoints
 | ||||
|         leerkracht: '/login-leerkracht', | ||||
|         leerling: '/login-leerling', | ||||
|     }); | ||||
| }); | ||||
| 
 | ||||
| export default router; | ||||
|  | @ -1,5 +1,9 @@ | |||
| const PREFIX = 'DWENGO_'; | ||||
| const DB_PREFIX = PREFIX + 'DB_'; | ||||
| const IDP_PREFIX = PREFIX + 'AUTH_'; | ||||
| const STUDENT_IDP_PREFIX = IDP_PREFIX + 'STUDENT_'; | ||||
| const TEACHER_IDP_PREFIX = IDP_PREFIX + 'TEACHER_'; | ||||
| const CORS_PREFIX = PREFIX + 'CORS_'; | ||||
| 
 | ||||
| type EnvVar = { key: string; required?: boolean; defaultValue?: any }; | ||||
| 
 | ||||
|  | @ -11,6 +15,15 @@ export const EnvVars: { [key: string]: EnvVar } = { | |||
|     DbUsername: { key: DB_PREFIX + 'USERNAME', required: true }, | ||||
|     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 }, | ||||
|     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 }, | ||||
|     IdpAudience: { key: IDP_PREFIX + 'AUDIENCE', defaultValue: 'account' }, | ||||
|     CorsAllowedOrigins: { key: CORS_PREFIX + 'ALLOWED_ORIGINS', defaultValue: '' }, | ||||
|     CorsAllowedHeaders: { key: CORS_PREFIX + 'ALLOWED_HEADERS', defaultValue: 'Authorization,Content-Type' }, | ||||
| } as const; | ||||
| 
 | ||||
| /** | ||||
|  |  | |||
		Reference in a new issue
	
	 Timo De Meyst
						Timo De Meyst