From 68a3d327f62cd6691db4dbddab60615c500ce420 Mon Sep 17 00:00:00 2001 From: Nam Vu Date: Wed, 15 Nov 2023 19:32:01 -0500 Subject: [PATCH] Fix optional authentication (#6134) --- server/middlewares/authentication.ts | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/server/middlewares/authentication.ts b/server/middlewares/authentication.ts index 8943cd112..afdc125f4 100644 --- a/server/middlewares/authentication.ts +++ b/server/middlewares/authentication.ts @@ -57,14 +57,14 @@ export default function auth(options: AuthenticationOptions = {}) { token = ctx.cookies.get("accessToken"); } - if (!token && options.optional !== true) { - throw AuthenticationError("Authentication required"); - } + try { + if (!token) { + throw AuthenticationError("Authentication required"); + } - let user: User | null; - let type: AuthenticationType; + let user: User | null; + let type: AuthenticationType; - if (token) { if (ApiKey.match(String(token))) { type = AuthenticationType.API; let apiKey; @@ -146,8 +146,12 @@ export default function auth(options: AuthenticationOptions = {}) { getRootSpanFromRequestContext(ctx) ); } - } else { - ctx.state.auth = {}; + } catch (err) { + if (options.optional) { + ctx.state.auth = {}; + } else { + throw err; + } } return next();