From c10136f1a3819e1244d79f4954d85ba98f2b06d5 Mon Sep 17 00:00:00 2001 From: Timothy-Gonzalez <105177619+Timothy-Gonzalez@users.noreply.github.com> Date: Wed, 9 Oct 2024 02:25:31 -0500 Subject: [PATCH] Extract getting authenticated user into function --- src/common/auth.ts | 10 ++++++++++ src/middleware/specification.ts | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/common/auth.ts b/src/common/auth.ts index 0252258..0b21e00 100644 --- a/src/common/auth.ts +++ b/src/common/auth.ts @@ -1,5 +1,6 @@ import ms from "ms"; import jsonwebtoken, { SignOptions } from "jsonwebtoken"; +import { Request } from "express"; import { RequestHandler } from "express-serve-static-core"; import passport, { AuthenticateOptions, Profile } from "passport"; @@ -158,6 +159,15 @@ export function decodeJwtToken(token?: string): JwtPayload { return jsonwebtoken.verify(token, secret) as JwtPayload; } +/** + * Gets the authenticated user from a request + * @param req The request + * @returns User payload + */ +export function getAuthenticatedUser(req: Request): JwtPayload { + return decodeJwtToken(req.headers.authorization); +} + /** * Create an auth database entry for the current user. Should be called whenever a user is created. * @param id UserID to create the entry for diff --git a/src/middleware/specification.ts b/src/middleware/specification.ts index ee8f942..31a47a0 100644 --- a/src/middleware/specification.ts +++ b/src/middleware/specification.ts @@ -5,7 +5,7 @@ import { Response, Request, NextFunction } from "express"; import { registerPathSpecification } from "../common/openapi"; import { RouteConfig } from "@asteasolutions/zod-to-openapi"; import { Role } from "../services/auth/auth-models"; -import { decodeJwtToken } from "../common/auth"; +import { getAuthenticatedUser } from "../common/auth"; import { TokenExpiredError } from "jsonwebtoken"; export type Method = RouteConfig["method"]; @@ -60,7 +60,7 @@ export default function specification { if (spec.role) { try { - const jwt = decodeJwtToken(req.headers.authorization); + const jwt = getAuthenticatedUser(req); if (!jwt.roles.includes(spec.role)) { return res.status(StatusCode.ClientErrorForbidden).json({ error: "Forbidden",