From ea65ae3a11e03fa66f809be89f86baabf627ad82 Mon Sep 17 00:00:00 2001 From: Rory& Date: Mon, 2 Jun 2025 12:16:30 +0200 Subject: Try to fix auth --- src/api/middlewares/authMiddleware.js | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) (limited to 'src/api/middlewares/authMiddleware.js') diff --git a/src/api/middlewares/authMiddleware.js b/src/api/middlewares/authMiddleware.js index 13d0d27..d67c567 100644 --- a/src/api/middlewares/authMiddleware.js +++ b/src/api/middlewares/authMiddleware.js @@ -1,6 +1,7 @@ import { validateJwtToken } from '#util/jwtUtils.js'; import { DbUser, UserType } from '#db/schemas/index.js'; import { SafeNSoundError } from '#util/error.js'; +import { getUserById } from '#db/dbAccess/index.js'; const shouldLogAuth = !!process.env['LOG_AUTH']; function logAuth(...params) { @@ -32,7 +33,9 @@ export async function useAuthentication(req, res, next) { )); logAuth('Token data:', auth); - // req.user = auth; + req.user = await getUserById(auth.sub); + logAuth('User data:', req.user); + next(); } @@ -57,22 +60,14 @@ export async function requireAuth(req, res, next) { */ export function requireRole(options) { return async function (req, res, next) { - res.status(401).send( - new SafeNSoundError({ - errCode: 'UNAUTHORIZED', - message: 'Unauthorized' - }) - ); - - const user = (req.user = await DbUser.findById(auth.id).exec()); - // admin can do everything - if (user.type == UserType.ADMIN) { + if (req.user.type === UserType.ADMIN) { next(); return; } - if (options.roles && !options.roles.includes(user.type)) { + if (options.roles && !options.roles.includes(req.user.type)) { + logAuth('User is missing roles', options.roles); res.status(401).send( new SafeNSoundError({ errCode: 'UNAUTHORIZED', -- cgit 1.5.1