From 872891be8b1a0e919cd752e3b29ba9e5c8ba7da4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dafydd=20Ll=C5=B7r=20Pearson?= Date: Sun, 3 Sep 2023 17:08:02 +0100 Subject: [PATCH] chore: Safely handle user IDs --- api.planx.uk/editor/copyFlow.ts | 7 +++++-- api.planx.uk/editor/publish.ts | 6 +++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/api.planx.uk/editor/copyFlow.ts b/api.planx.uk/editor/copyFlow.ts index 2549625143..8f8e703e0c 100644 --- a/api.planx.uk/editor/copyFlow.ts +++ b/api.planx.uk/editor/copyFlow.ts @@ -1,6 +1,7 @@ import { Request, Response, NextFunction } from "express"; import { makeUniqueFlow, getFlowData, insertFlow } from "../helpers"; import { Flow } from "../types"; +import { userContext } from "../modules/auth/middleware"; const copyFlow = async ( req: Request, @@ -25,13 +26,15 @@ const copyFlow = async ( const shouldInsert = (req.body?.insert as boolean) || false; if (shouldInsert) { const newSlug = flow.slug + "-copy"; - const creatorId = parseInt(req.user!.sub!, 10); + const creatorId = userContext.getStore()?.user?.sub; + if (!creatorId) throw Error("User details missing from request"); + // Insert the flow and an associated operation await insertFlow( flow.team_id, newSlug, uniqueFlowData, - creatorId, + parseInt(creatorId), req.params.flowId, ); } diff --git a/api.planx.uk/editor/publish.ts b/api.planx.uk/editor/publish.ts index ed19f40ba1..1c81377389 100644 --- a/api.planx.uk/editor/publish.ts +++ b/api.planx.uk/editor/publish.ts @@ -5,6 +5,7 @@ import { dataMerged, getMostRecentPublishedFlow } from "../helpers"; import { gql } from "graphql-request"; import intersection from "lodash/intersection"; import { ComponentType } from "@opensystemslab/planx-core/types"; +import { userContext } from "../modules/auth/middleware"; const validateAndDiffFlow = async ( req: Request, @@ -73,6 +74,9 @@ const publishFlow = async ( const mostRecent = await getMostRecentPublishedFlow(req.params.flowId); const delta = jsondiffpatch.diff(mostRecent, flattenedFlow); + const userId = userContext.getStore()?.user?.sub; + if (!userId) throw Error("User details missing from request"); + if (delta) { const response = await adminClient.request( gql` @@ -101,7 +105,7 @@ const publishFlow = async ( { data: flattenedFlow, flow_id: req.params.flowId, - publisher_id: parseInt(req.user!.sub!, 10), + publisher_id: parseInt(userId), summary: req.query?.summary || null, }, );