summary refs log tree commit diff
path: root/src/api/middlewares/authMiddleware.js
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2025-06-02 12:16:30 +0200
committerRory& <root@rory.gay>2025-06-02 12:16:30 +0200
commitea65ae3a11e03fa66f809be89f86baabf627ad82 (patch)
tree377af52ba925269feea603ab716fd52d950154bb /src/api/middlewares/authMiddleware.js
parentFix readme (diff)
downloadnodejs-final-assignment-ea65ae3a11e03fa66f809be89f86baabf627ad82.tar.xz
Try to fix auth
Diffstat (limited to 'src/api/middlewares/authMiddleware.js')
-rw-r--r--src/api/middlewares/authMiddleware.js19
1 files changed, 7 insertions, 12 deletions
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',