Add methods for requiring more specific levels of teamleader auth

+ Add AuthError
This commit is contained in:
Stephan
2022-05-27 23:08:23 +02:00
parent a9c182cf64
commit 2a33b703bc
5 changed files with 52 additions and 3 deletions
+5 -1
View File
@@ -6,13 +6,17 @@ import { authClient } from "../../lib/redis";
import jwt, { JsonWebTokenError, JwtPayload } from "jsonwebtoken";
import prisma from "../../lib/prisma";
const JWT_SECRET = process.env.JWT_SECRET || "secret";
const JWT_SECRET = process.env.JWT_SECRET;
export const verifyAuthorizationFormat = (authorization: string) => /^Bearer .+$/.test(authorization);
export const getBearerToken = (authorization: string) => authorization.slice(7);
export const requireAuthentication = async (req: Request, res: Response, next: NextFunction) => {
if (!JWT_SECRET) {
throw new Error("JWT_SECRET not set");
}
const { authorization } = req.headers;
if (!authorization) {
+22
View File
@@ -1,7 +1,9 @@
import { Participant } from "@prisma/client";
import e, { NextFunction, Request, Response } from "express";
import jwt, { JsonWebTokenError } from "jsonwebtoken";
import AuthError from "../error/AuthError";
import { getBearerToken, verifyAuthorizationFormat } from "./auth";
import prisma from "../../lib/prisma";
export interface TeamleaderJWTPayload {
pid: string;
@@ -73,3 +75,23 @@ export async function requireTeamleaderAuthentication(req: Request, res: Respons
throw e;
}
export function requireLeaderOfTeam(auth: TeamleaderJWTPayload | undefined, teamPid: string) {
if (auth?.team !== teamPid) {
throw new AuthError("The provided authorization is not valid for the requested team");
}
}
export async function requireResponsibleForParticipant(auth: TeamleaderJWTPayload | undefined, participantPid: string) {
if (!auth) {
throw new AuthError("There was an error with your authorization");
}
const teamPid = (
await prisma.participant.findUnique({ where: { pid: participantPid }, select: { team: { select: { pid: true } } } })
)?.team.pid;
if (teamPid !== auth.team) {
throw new AuthError("The provided authorization is not valid for the requested participant");
}
}
+13
View File
@@ -0,0 +1,13 @@
import ForwardableError from "./ForwardableError";
export default class AuthError extends ForwardableError {
protected __oid = "AUTH_ERROR";
constructor(message?: string) {
super(403, message ?? "The request did not provide sufficient authentication");
}
static isAuthError(err: any): err is AuthError {
return err.__oid === "AUTH_ERROR";
}
}