From 36203b5768153dad6e4dbc48f63b842d78a53af3 Mon Sep 17 00:00:00 2001 From: Aelita4 Date: Tue, 18 Jun 2024 22:19:42 +0200 Subject: [PATCH] Fix bug where unauthorized user could get detailed planet data --- src/lib/db/planets.ts | 9 ++++++-- src/pages/api/planets/getPlanet/[planetId].ts | 22 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/lib/db/planets.ts b/src/lib/db/planets.ts index 9229566..cd45cd2 100644 --- a/src/lib/db/planets.ts +++ b/src/lib/db/planets.ts @@ -42,9 +42,14 @@ export const createPlanet = async (options: { name: string, owner?: User, ownerI export const getPlanetById = async (id: ObjectId) => { const planets = await Planets(); - return planets.findOne({ + const planet = await planets.findOne({ _id: id - }) as Promise; + }); + + if(!planet) return null; + + planet.owner = await getUserById(planet.owner); + return planet as Planet; } export const createOrUpgradeBuilding = async (planetId: ObjectId, building: Building) => { diff --git a/src/pages/api/planets/getPlanet/[planetId].ts b/src/pages/api/planets/getPlanet/[planetId].ts index 3fa32a7..6351fef 100644 --- a/src/pages/api/planets/getPlanet/[planetId].ts +++ b/src/pages/api/planets/getPlanet/[planetId].ts @@ -3,8 +3,23 @@ import { getPlanetById } from "../../../../lib/db/planets"; import { ObjectId } from "mongodb"; import Planet from "../../../../types/Planet"; import { calculateCurrentAvailableResources } from "../../../../lib/utils/resourceManager"; +import validateAccessToken from "../../../../lib/utils/validateAccessToken"; +import { getUserByAccessToken } from "../../../../lib/db/users"; export const GET: APIRoute = async ({ params, request }) => { + const response = await validateAccessToken(request); + if(response instanceof Response) return response; + + const user = await getUserByAccessToken(response); + if(user === null) { + return new Response( + JSON.stringify({ + code: 401, + message: "Unauthorized" + }), { status: 401 } + ) + } + const planetId = params['planetId']; if(!planetId) return new Response( JSON.stringify({ @@ -32,6 +47,13 @@ export const GET: APIRoute = async ({ params, request }) => { ); } + if(planet.owner._id.toString() !== user._id.toString()) return new Response( + JSON.stringify({ + code: 403, + message: "Forbidden" + }), { status: 403 } + ); + await calculateCurrentAvailableResources(planet._id); return new Response(