mirror of
https://github.com/bubblecup-12/VogelSocialMedia.git
synced 2025-07-09 12:08:47 +00:00
backend refactored
This commit is contained in:
commit
7ba2a34eb1
13 changed files with 684 additions and 16 deletions
43
code/backend/src/middleware/authenticateToken.ts
Normal file
43
code/backend/src/middleware/authenticateToken.ts
Normal 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();
|
||||
},
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
26
code/backend/src/middleware/validationMiddleware.ts
Normal file
26
code/backend/src/middleware/validationMiddleware.ts
Normal 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" });
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue