From dac5529b6c7a53fcebcd8083229c82c47e225cf7 Mon Sep 17 00:00:00 2001 From: Daniel Hougaard <62331820+DanielHougaard@users.noreply.github.com> Date: Tue, 12 Mar 2024 14:22:35 +0100 Subject: [PATCH] Feat: Scoped JWT to organization, require organization on all requests by default on JWT requests --- backend/src/server/plugins/auth/verify-auth.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/backend/src/server/plugins/auth/verify-auth.ts b/backend/src/server/plugins/auth/verify-auth.ts index db9700867..3b3a239f7 100644 --- a/backend/src/server/plugins/auth/verify-auth.ts +++ b/backend/src/server/plugins/auth/verify-auth.ts @@ -3,21 +3,25 @@ import { FastifyReply, FastifyRequest, HookHandlerDoneFunction } from "fastify"; import { UnauthorizedError } from "@app/lib/errors"; import { AuthMode } from "@app/services/auth/auth-type"; +interface TAuthOptions { + requireOrg: boolean; +} + export const verifyAuth = - (authStrats: AuthMode[], options: { requireOrg: boolean } = { requireOrg: true }) => + (authStrategies: AuthMode[], options: TAuthOptions = { requireOrg: true }) => (req: T, _res: FastifyReply, done: HookHandlerDoneFunction) => { - if (!Array.isArray(authStrats)) throw new Error("Auth strategy must be array"); + if (!Array.isArray(authStrategies)) throw new Error("Auth strategy must be array"); if (!req.auth) throw new UnauthorizedError({ name: "Unauthorized access", message: "Token missing" }); - const isAccessAllowed = authStrats.some((strat) => strat === req.auth.authMode); + const isAccessAllowed = authStrategies.some((strategy) => strategy === req.auth.authMode); if (!isAccessAllowed) { throw new UnauthorizedError({ name: `${req.url} Unauthorized Access` }); } // New optional option. There are some routes which do not require an organization ID to be present on the request. - // En example of this is the /v1 auth routes. - if (options.requireOrg === true && !req.permission.orgId) { - throw new UnauthorizedError({ name: `${req.url} Unauthorized Access, no organization found` }); + // An example of this is the /v1 auth routes. + if (req.auth.authMode === AuthMode.JWT && options.requireOrg === true && !req.permission.orgId) { + throw new UnauthorizedError({ name: `${req.url} Unauthorized Access, no organization found in request` }); } done();