Partypack/Server/Source/Modules/Middleware.ts

59 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-01-28 11:07:10 +01:00
import { NextFunction, Request, Response } from "express";
import { User } from "../Schemas/User";
import { JwtPayload, verify } from "jsonwebtoken";
import { IS_DEBUG, JWT_KEY } from "./Constants";
import j from "joi";
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Express {
interface Request {
user?: User;
}
}
}
export function RequireAuthentication(Relations?: object) {
return async (req: Request, res: Response, next: NextFunction) => {
if (!req.header("X-Partypack-Token") && !req.cookies["Token"] && !req.header("Authorization"))
2024-02-05 01:28:46 +01:00
return res.status(401).send("You must be logged in to perform this action.");
2024-01-28 11:07:10 +01:00
let JWT: JwtPayload;
try {
JWT = verify(req.header("X-Partypack-Token") ?? req.cookies["Token"] ?? req.header("Authorization"), JWT_KEY!) as JwtPayload;
} catch (err) {
console.error(err);
return res.status(403).send(`Invalid Partypack token provided.${IS_DEBUG ? ` (${err})` : ""}`);
2024-01-28 11:07:10 +01:00
}
const UserData = await User.findOne({ where: { ID: JWT.ID }, relations: Relations });
if (!UserData)
return res.status(401).send("Invalid Partypack token provided. User does not exist in database. Please contact an instance admin.");
2024-01-28 11:07:10 +01:00
req.user = UserData;
next();
}
}
export function ValidateBody(Schema: j.Schema) {
return async (req: Request, res: Response, next: NextFunction) => {
try {
req.body = await Schema.validateAsync(req.body);
next();
} catch (err) {
res.status(400).json(err)
2024-01-28 11:07:10 +01:00
}
}
2024-01-28 16:54:32 +01:00
}
export function ValidateQuery(Schema: j.Schema) {
return async (req: Request, res: Response, next: NextFunction) => {
try {
req.query = await Schema.validateAsync(req.query);
next();
} catch (err) {
res.status(400).json(err)
2024-01-28 16:54:32 +01:00
}
}
2024-02-05 01:28:46 +01:00
}