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',
diff --git a/src/api/middlewares/errorMiddleware.js b/src/api/middlewares/errorMiddleware.js
index b8de68e..72b6166 100644
--- a/src/api/middlewares/errorMiddleware.js
+++ b/src/api/middlewares/errorMiddleware.js
@@ -1,5 +1,6 @@
import { SafeNSoundError } from '#util/error.js';
import { MongoServerError } from 'mongodb';
+import * as joi from 'joi';
export function handleErrors(err, req, res, _next) {
if (err instanceof MongoServerError) {
@@ -14,6 +15,13 @@ export function handleErrors(err, req, res, _next) {
err = newErr;
}
+ } else if (err instanceof joi.ValidationError) {
+ const newErr = new SafeNSoundError({
+ errCode: 'JOI_VALIDATION_ERROR',
+ message: err.message,
+ validation_details: err.details
+ });
+ err = newErr;
}
if (err instanceof SafeNSoundError) {
|