feat(backend): Endpoints voor studenten beschermd
This commit is contained in:
parent
bc60c18938
commit
6cb8a1b98f
7 changed files with 93 additions and 52 deletions
|
@ -1,13 +1,11 @@
|
|||
import { envVars, getEnvVar } from '../../util/envVars.js';
|
||||
import { expressjwt } from 'express-jwt';
|
||||
import {envVars, getEnvVar} from '../../util/envVars.js';
|
||||
import {expressjwt} from 'express-jwt';
|
||||
import * as jwt from 'jsonwebtoken';
|
||||
import { JwtPayload } from 'jsonwebtoken';
|
||||
import {JwtPayload} from 'jsonwebtoken';
|
||||
import jwksClient from 'jwks-rsa';
|
||||
import * as express from 'express';
|
||||
import { AuthenticatedRequest } from './authenticated-request.js';
|
||||
import { AuthenticationInfo } from './authentication-info.js';
|
||||
import { UnauthorizedException } from '../../exceptions/unauthorized-exception.js';
|
||||
import { ForbiddenException } from '../../exceptions/forbidden-exception.js';
|
||||
import {AuthenticatedRequest} from './authenticated-request.js';
|
||||
import {AuthenticationInfo} from './authentication-info.js';
|
||||
|
||||
const JWKS_CACHE = true;
|
||||
const JWKS_RATE_LIMIT = true;
|
||||
|
@ -108,36 +106,3 @@ function addAuthenticationInfo(req: AuthenticatedRequest, _res: express.Response
|
|||
}
|
||||
|
||||
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 function 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)) {
|
||||
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');
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue