Skip to content

Commit

Permalink
Extract getting authenticated user into function
Browse files Browse the repository at this point in the history
  • Loading branch information
Timothy-Gonzalez committed Oct 9, 2024
1 parent 29cccf4 commit c10136f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/common/auth.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/middleware/specification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down Expand Up @@ -60,7 +60,7 @@ export default function specification<Params extends AnyZodObject, Responses ext
return async (req: Request, res: Response, next: NextFunction) => {
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",
Expand Down

0 comments on commit c10136f

Please sign in to comment.