diff --git a/api/middlewares/authenticate.ts b/api/middlewares/authenticate.ts index 39fdad2..2c57d23 100644 --- a/api/middlewares/authenticate.ts +++ b/api/middlewares/authenticate.ts @@ -1,5 +1,5 @@ import {IToken, Token} from "../../models/Token"; -import {IUser, User} from "../../models/User"; +import {IUser, Rank, User} from "../../models/User"; import {NextFunction, Request, Response} from "express"; export interface AuthenticatedRequest extends Request { @@ -7,6 +7,7 @@ export interface AuthenticatedRequest extends Request { user: IUser } +/** Authenticate the user using the authorization header */ module.exports.authenticate = async (req: AuthenticatedRequest, res: Response, next: NextFunction) => { // Get the token header const authHeader = req.headers["authorization"]; @@ -25,4 +26,17 @@ module.exports.authenticate = async (req: AuthenticatedRequest, res: Response, n if (req.user == null) return res.status(401).json({message: "The provided token is wrong"}); next(); +} + +/** + * Check if the current user has the provided rank + * @param rank The rank which is required to use the route + */ +export const hasRank = (rank: Rank) => (req: AuthenticatedRequest, res: Response, next: NextFunction) => { + // Admins have access to all routes + if (req.user.rank === Rank.ADMIN) return next(); + + if (req.user.rank === rank) return next(); + + res.status(401).json({message: "You don't have the permission to use this route"}); } \ No newline at end of file