All files / src/middleware validateWorkspace.ts

93.33% Statements 14/15
81.81% Branches 9/11
100% Functions 2/2
93.33% Lines 14/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36129x 1x   2x 72x       72x     72x       72x     72x 2x         70x   70x 14x         56x 56x    
import { Request, Response, NextFunction } from "express";
import guard from "@cooper/backend/src/middleware/guard";
 
export async function validateWorkspace(req: Request, res: Response, next: NextFunction) {
  const db = req.app.locals.database;
 
  // parseInt because we don't want to include "truthy" numbers
  // e.g. hello10 = 10 > this should be NaN
  const workspaceId = parseInt(req.params.workspaceId, 10);
 
  // workspaceId is wildly invalid
  Iif (Number.isNaN(workspaceId)) {
    return res.status(401).json({ error: "Unauthorised" });
  }
 
  const workspace = db.budgeting.workspaces.getWorkspace(workspaceId);
 
  // Workspace does not exist
  if (workspace == null) {
    return res.status(404).json({
      error: "Workspace does not exist",
    });
  }
 
  const username = guard(res.session).username;
  // User does not have access to workspace
  if (!workspace.users.includes(username)) {
    return res.status(401).json({
      error: "Unauthorised",
    });
  }
 
  res.workspace = workspace;
  return next();
}