mirror of
https://github.com/bubblecup-12/VogelSocialMedia.git
synced 2025-07-07 06:08:54 +00:00
backend refactored
This commit is contained in:
commit
7ba2a34eb1
13 changed files with 684 additions and 16 deletions
44
code/backend/src/controllers/userController.ts
Normal file
44
code/backend/src/controllers/userController.ts
Normal file
|
@ -0,0 +1,44 @@
|
|||
import express, { Request, Response } from "express";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { UserLoginDto, userLoginSchema } from "../schemas/userSchemas";
|
||||
import jwt from "jsonwebtoken";
|
||||
import dotenv from "dotenv";
|
||||
import { string } from "zod";
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
const prisma = new PrismaClient();
|
||||
// load environment variables from .env file
|
||||
dotenv.config();
|
||||
const JWT_SECRET: string = process.env.TOKEN_SECRET!;
|
||||
|
||||
function generateAccessToken(username: string) {
|
||||
return jwt.sign({ username }, JWT_SECRET, { expiresIn: "1800s" });
|
||||
}
|
||||
|
||||
export const registerUser = async (req: Request, res: Response) => {
|
||||
const userRequest = await req.body;
|
||||
const user = await prisma.user.create({ data: userRequest });
|
||||
console.log(user.username);
|
||||
res.json({ message: "User registered successfully", data: req.body });
|
||||
};
|
||||
|
||||
export const loginUser = (req: Request, res: Response) => {
|
||||
const token: string = generateAccessToken(req.body.username);
|
||||
res.json({ message: "User logged in successfully", data: req.body, token });
|
||||
};
|
||||
|
||||
export const getUser = async (req: Request, res: Response) => {
|
||||
const username = req.body.username;
|
||||
console.log(username, req.body);
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
username: username,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
res.status(404).json({ message: "User not found" });
|
||||
}
|
||||
res.json({ message: "User found", data: user });
|
||||
};
|
||||
|
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" });
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
30
code/backend/src/routes/userRoutes.ts
Normal file
30
code/backend/src/routes/userRoutes.ts
Normal file
|
@ -0,0 +1,30 @@
|
|||
// src/routes/userRoutes.ts
|
||||
import express from "express";
|
||||
import { validateData } from "../middleware/validationMiddleware";
|
||||
import {
|
||||
userRegistrationSchema,
|
||||
userLoginSchema,
|
||||
} from "../schemas/userSchemas";
|
||||
import { authenticateToken } from "../middleware/authenticateToken";
|
||||
|
||||
const userRouter = express.Router();
|
||||
|
||||
import {
|
||||
registerUser,
|
||||
loginUser,
|
||||
getUser,
|
||||
} from "../controllers/userController";
|
||||
|
||||
userRouter.post(
|
||||
"/register",
|
||||
validateData(userRegistrationSchema),
|
||||
registerUser,
|
||||
);
|
||||
userRouter.post("/login", validateData(userLoginSchema), loginUser);
|
||||
userRouter.get(
|
||||
"/getUser",
|
||||
authenticateToken(),
|
||||
validateData(userLoginSchema),
|
||||
getUser,
|
||||
);
|
||||
export default userRouter;
|
16
code/backend/src/schemas/userSchemas.ts
Normal file
16
code/backend/src/schemas/userSchemas.ts
Normal file
|
@ -0,0 +1,16 @@
|
|||
// src/schemas/userSchemas.ts
|
||||
import { z } from "zod";
|
||||
|
||||
export const userRegistrationSchema = z.object({
|
||||
username: z.string(),
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8),
|
||||
});
|
||||
|
||||
export const userLoginSchema = z.object({
|
||||
username: z.string(),
|
||||
password: z.string().min(8),
|
||||
});
|
||||
// DTO-Typen aus den Schemas ableiten
|
||||
export type UserRegistrationDto = z.infer<typeof userRegistrationSchema>;
|
||||
export type UserLoginDto = z.infer<typeof userLoginSchema>;
|
|
@ -1,13 +1,17 @@
|
|||
import express, { Request, Response } from 'express';
|
||||
import express, { Request, Response } from "express";
|
||||
|
||||
import dotenv from "dotenv";
|
||||
import userRouter from "./routes/userRoutes";
|
||||
import bodyParser from "body-parser";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const app = express();
|
||||
const port = 3000;
|
||||
|
||||
app.get('/', (req: Request, res: Response) => {
|
||||
res.send('Hallo, Welt mit TypeScript!');
|
||||
});
|
||||
app.use(bodyParser.json());
|
||||
app.use("/api/user", userRouter);
|
||||
|
||||
app.listen(port, () => {
|
||||
console.log(`Server läuft auf http://localhost:${port}`);
|
||||
});
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue