Files
kittyBE/src/middleware/requireAdmin.ts

39 lines
1.2 KiB
TypeScript

import { Request, Response, NextFunction } from 'express';
import { ErrorDTO } from '../schemas/miscSchema';
import * as jwt from '../tools/jwt';
/**
* Checks if user has administrative privileges.
*
* This needs to happen AFTER ensuring this is not a guest session.
* So: use requireUser first, and after that requireAdmin to enforce
* admin privilege requirement.
*
* @param {Request} req The request
* @param {Response} res The resource
* @param {(Function|NextFunction)} next The next
* @return {any} Next function on success, unauthorized error otherwise
*/
const requireAdmin = (req: Request, res: Response, next: NextFunction) => {
const user: jwt.JwtStatus = res.locals.user;
let error: ErrorDTO | null = null;
// Check if role is set to 1 (1 = admin, 0 = standard user).
if (user.decoded?.role !== 1)
error = {
status: 'error',
error: 'Unauthorized, admin access required',
code: 'unauthorized_non_admin'
};
// It is? Send 401 unauthorized.
if (error !== null)
return res.status(401)
.send(error);
// Otherwise jump to next endpoint.
return next();
};
export default requireAdmin;