From 41f27362d254817b59a3ecfd4ddc445b4caf1db5 Mon Sep 17 00:00:00 2001 From: Sainan Date: Thu, 6 Jun 2024 15:03:05 +0200 Subject: [PATCH] Add getGuildForRequest --- .../api/startDojoRecipeController.ts | 19 +++---------------- src/services/guildService.ts | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 16 deletions(-) create mode 100644 src/services/guildService.ts diff --git a/src/controllers/api/startDojoRecipeController.ts b/src/controllers/api/startDojoRecipeController.ts index bc61e276..8b4104ac 100644 --- a/src/controllers/api/startDojoRecipeController.ts +++ b/src/controllers/api/startDojoRecipeController.ts @@ -1,8 +1,6 @@ import { RequestHandler } from "express"; import { IDojoComponentClient } from "@/src/types/guildTypes"; -import { getAccountIdForRequest } from "@/src/services/loginService"; -import { Inventory } from "@/src/models/inventoryModels/inventoryModel"; -import { Guild } from "@/src/models/guildModel"; +import { getGuildForRequest } from "@/src/services/guildService"; import { Types } from "mongoose"; interface IStartDojoRecipeRequest { @@ -11,19 +9,8 @@ interface IStartDojoRecipeRequest { } export const startDojoRecipeController: RequestHandler = async (req, res) => { - const accountId = await getAccountIdForRequest(req); - const inventory = await Inventory.findOne({ accountOwnerId: accountId }); - if (!inventory) { - res.status(400).end(); - return; - } - const guildId = req.query.guildId as string; - if (!inventory.GuildId || inventory.GuildId.toString() != guildId) { - res.status(400).end(); - return; - } - // Verified that a member of the guild is making this request. Assuming they are allowed to start a build. - const guild = (await Guild.findOne({ _id: guildId }))!; + const guild = await getGuildForRequest(req); + // At this point, we know that a member of the guild is making this request. Assuming they are allowed to start a build. const request = JSON.parse(req.body.toString()) as IStartDojoRecipeRequest; guild.DojoComponents!.push({ _id: new Types.ObjectId(), diff --git a/src/services/guildService.ts b/src/services/guildService.ts new file mode 100644 index 00000000..c43d8238 --- /dev/null +++ b/src/services/guildService.ts @@ -0,0 +1,18 @@ +import { Request } from "express"; +import { getAccountIdForRequest } from "@/src/services/loginService"; +import { getInventory } from "@/src/services/inventoryService"; +import { Guild } from "@/src/models/guildModel"; + +export const getGuildForRequest = async (req: Request) => { + const accountId = await getAccountIdForRequest(req); + const inventory = await getInventory(accountId); + const guildId = req.query.guildId as string; + if (!inventory.GuildId || inventory.GuildId.toString() != guildId) { + throw new Error("Account is not in the guild that it has sent a request for"); + } + const guild = await Guild.findOne({ _id: guildId }); + if (!guild) { + throw new Error("Account thinks it is a in guild that doesn't exist"); + } + return guild; +};