From eafd15c8608a01d959687abddf7e3c1a3a6b4e4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dafydd=20Ll=C5=B7r=20Pearson?= Date: Mon, 6 Nov 2023 14:26:19 +0000 Subject: [PATCH] fix: `Could not verify JWT` bug (#2384) * fix: Add token to user context regardless of how request is made * chore: Use publicClient to get FlowData --- api.planx.uk/helpers.ts | 3 +-- api.planx.uk/modules/auth/middleware.ts | 15 +++++++++------ 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/api.planx.uk/helpers.ts b/api.planx.uk/helpers.ts index 47e38c9be2..9075fc891b 100644 --- a/api.planx.uk/helpers.ts +++ b/api.planx.uk/helpers.ts @@ -6,8 +6,7 @@ import { $public, getClient } from "./client"; // Get a flow's data (unflattened, without external portal nodes) const getFlowData = async (id: string): Promise => { - const { client: $client } = getClient(); - const { flow } = await $client.request<{ flow: Flow | null }>( + const { flow } = await $public.client.request<{ flow: Flow | null }>( gql` query GetFlowData($id: uuid!) { flow: flows_by_pk(id: $id) { diff --git a/api.planx.uk/modules/auth/middleware.ts b/api.planx.uk/modules/auth/middleware.ts index a751ea0a23..df1b1217c6 100644 --- a/api.planx.uk/modules/auth/middleware.ts +++ b/api.planx.uk/modules/auth/middleware.ts @@ -9,6 +9,7 @@ import passport from "passport"; import { RequestHandler } from "http-proxy-middleware"; import { Role } from "@opensystemslab/planx-core/types"; import { AsyncLocalStorage } from "async_hooks"; +import { Request } from "express"; export const userContext = new AsyncLocalStorage<{ user: Express.User }>(); @@ -86,6 +87,11 @@ export const useFilePermission: RequestHandler = (req, _res, next): void => { return next(); }; +export const getToken = (req: Request) => + req.cookies?.jwt ?? + req.headers.authorization?.match(/^Bearer (\S+)$/)?.[1] ?? + req.query?.token; + // XXX: Currently not checking for JWT and including req.user in every // express endpoint because authentication also uses req.user. More info: // https://github.com/theopensystemslab/planx-new/pull/555#issue-684435760 @@ -95,10 +101,7 @@ export const useJWT = expressjwt({ algorithms: ["HS256"], credentialsRequired: true, requestProperty: "user", - getToken: (req) => - req.cookies?.jwt ?? - req.headers.authorization?.match(/^Bearer (\S+)$/)?.[1] ?? - req.query?.token, + getToken: getToken, }); export const useGoogleAuth: RequestHandler = (req, res, next) => { @@ -163,7 +166,7 @@ export const useRoleAuth: UseRoleAuth = { user: { ...req.user, - jwt: req.cookies.jwt, + jwt: getToken(req), }, }, () => next(), @@ -190,7 +193,7 @@ export const useLoginAuth: RequestHandler = (req, res, next) => { user: { ...req.user, - jwt: req.cookies.jwt, + jwt: getToken(req), }, }, () => next(),