Skip to content

Commit

Permalink
fix: Could not verify JWT bug (#2384)
Browse files Browse the repository at this point in the history
* fix: Add token to user context regardless of how request is made

* chore: Use publicClient to get FlowData
  • Loading branch information
DafyddLlyr authored Nov 6, 2023
1 parent 3cda007 commit eafd15c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
3 changes: 1 addition & 2 deletions api.planx.uk/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Flow> => {
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) {
Expand Down
15 changes: 9 additions & 6 deletions api.planx.uk/modules/auth/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }>();

Expand Down Expand Up @@ -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
Expand All @@ -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) => {
Expand Down Expand Up @@ -163,7 +166,7 @@ export const useRoleAuth: UseRoleAuth =
{
user: {
...req.user,
jwt: req.cookies.jwt,
jwt: getToken(req),
},
},
() => next(),
Expand All @@ -190,7 +193,7 @@ export const useLoginAuth: RequestHandler = (req, res, next) =>
{
user: {
...req.user,
jwt: req.cookies.jwt,
jwt: getToken(req),
},
},
() => next(),
Expand Down

0 comments on commit eafd15c

Please sign in to comment.