import { validateJwtToken } from '#util/jwtUtils.js'; import { DbUser, UserType } from '#db/schemas/index.js'; /** * @param options {AuthValidationOptions} * @returns {(function(*, *, *): void)|*} */ export function validateAuth(options) { return async function (req, res, next) { const auth = (req.auth = validateJwtToken(req.headers.authorization)); if (!auth) { res.status(401).send('Unauthorized'); return; } const user = (req.user = await DbUser.findById(auth.id).exec()); // admin can do everything if (user.type == UserType.ADMIN) { next(); return; } if (options.roles && !options.roles.includes(user.type)) { res.status(401).send('Unauthorized'); return; } next(); }; } export const requireAuth = validateAuth({}); export const requireAdmin = validateAuth({ roles: [UserType.ADMIN] }); export const requireMonitor = validateAuth({ roles: [UserType.MONITOR] }); export const requireUser = validateAuth({ roles: [UserType.USER] }); export const requireUserOrMonitor = validateAuth({ roles: [UserType.USER, UserType.MONITOR] }); class AuthValidationOptions { roles; }