backend refactored

This commit is contained in:
Kai Ritthaler 2025-05-08 13:42:41 +02:00
commit 7ba2a34eb1
13 changed files with 684 additions and 16 deletions

View file

@ -0,0 +1,43 @@
import express, { NextFunction, Request, Response } from "express";
import jwt from "jsonwebtoken";
import dotenv from "dotenv";
import { string } from "zod";
const JWT_SECRET: string = process.env.TOKEN_SECRET!;
interface JwtPayload {
username: string;
iat: number;
exp: number;
}
declare global {
namespace Express {
interface Request {
user?: JwtPayload;
}
}
}
export function authenticateToken() {
return (req: Request, res: Response, next: NextFunction) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (token == null) res.sendStatus(401);
else {
jwt.verify(
token,
process.env.TOKEN_SECRET as string,
(err: any, user: any) => {
console.log(err);
if (err) res.sendStatus(403);
req.user = user;
next();
},
);
}
};
}

View file

@ -0,0 +1,26 @@
import { Request, Response, NextFunction } from "express";
import { z, ZodError } from "zod";
import { StatusCodes } from "http-status-codes";
export function validateData(schema: z.ZodObject<any, any>) {
return (req: Request, res: Response, next: NextFunction) => {
try {
schema.parse(req.body);
next();
} catch (error) {
if (error instanceof ZodError) {
const errorMessages = error.errors.map((issue: any) => ({
message: `${issue.path.join(".")} is ${issue.message}`,
}));
res
.status(StatusCodes.BAD_REQUEST)
.json({ error: "Invalid data", details: errorMessages });
} else {
res
.status(StatusCodes.INTERNAL_SERVER_ERROR)
.json({ error: "Internal Server Error" });
}
}
};
}