From e2aef5b1214af8edec5a1d807d269e29dcc09880 Mon Sep 17 00:00:00 2001 From: Olanite Olalekan Date: Mon, 14 Apr 2025 22:27:58 +0100 Subject: [PATCH] fix: improve authentication middleware by handling exempt paths before token validation --- src/middleware/auth.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/middleware/auth.ts b/src/middleware/auth.ts index 954dd3b..2cb78df 100644 --- a/src/middleware/auth.ts +++ b/src/middleware/auth.ts @@ -19,13 +19,15 @@ export class AuthMiddleware implements ExpressMiddlewareInterface { ) {} async use(request: Request, response: Response, next: (err?: any) => any): Promise { - const token = request.headers.authorization?.split(' ')[1]; - if (!token) { - return response.status(401).json({ message: 'You must be authenticated to call this API' }); + // todo : find a better fix for this + const exemptPaths = ['/auth/login', '/auth/register', '/auth/refresh']; + const isExemptPath = exemptPaths.some((path) => request.path.startsWith(path)); + if (isExemptPath) { + return next(); } - + const token = request.headers.authorization?.split(' ')[1]; try { - const authData = await this.authService.getCurrentUser(token); + const authData = await this.authService.getCurrentUser(token!); request.auth = authData; } catch (error) { this.logger.error(`An error occurred while validating token, ${error}`);