Feat: Scoped JWT to organization, require organization on all requests by default on JWT requests

This commit is contained in:
Daniel Hougaard
2024-03-17 18:48:10 +01:00
parent bd92e35729
commit dac5529b6c
+10 -6
View File
@@ -3,21 +3,25 @@ import { FastifyReply, FastifyRequest, HookHandlerDoneFunction } from "fastify";
import { UnauthorizedError } from "@app/lib/errors"; import { UnauthorizedError } from "@app/lib/errors";
import { AuthMode } from "@app/services/auth/auth-type"; import { AuthMode } from "@app/services/auth/auth-type";
interface TAuthOptions {
requireOrg: boolean;
}
export const verifyAuth = export const verifyAuth =
<T extends FastifyRequest>(authStrats: AuthMode[], options: { requireOrg: boolean } = { requireOrg: true }) => <T extends FastifyRequest>(authStrategies: AuthMode[], options: TAuthOptions = { requireOrg: true }) =>
(req: T, _res: FastifyReply, done: HookHandlerDoneFunction) => { (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" }); 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) { if (!isAccessAllowed) {
throw new UnauthorizedError({ name: `${req.url} Unauthorized Access` }); 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. // 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. // An example of this is the /v1 auth routes.
if (options.requireOrg === true && !req.permission.orgId) { if (req.auth.authMode === AuthMode.JWT && options.requireOrg === true && !req.permission.orgId) {
throw new UnauthorizedError({ name: `${req.url} Unauthorized Access, no organization found` }); throw new UnauthorizedError({ name: `${req.url} Unauthorized Access, no organization found in request` });
} }
done(); done();