import { Request, Response } from "express"; import { compareSync, genSaltSync, hashSync } from "bcrypt-ts"; import jwt from 'jsonwebtoken'; import { AppDataSource } from '../data-source'; import { User } from "../entity/User"; import { Post } from "../entity/Post"; class UserController { async register(req: Request, res: Response): Promise { const { username, password } = req.body; const user = new User(); user.username = username; user.password_hash = hashSync(password, genSaltSync(10)); const userId = (await AppDataSource.manager.save(user)).id; res.cookie("jwt", jwt.sign({ username, id: userId }, process.env.JWT_SECRET)); res.status(200).redirect("/"); } async login(req: Request, res: Response): Promise { const { username, password } = req.body; let savedUser = (await AppDataSource.manager.findOneBy(User, { username })); if (!compareSync(password, savedUser.password_hash)) { res.status(401).send("Incorrect password"); return; } res.cookie("jwt", jwt.sign({ username, id: savedUser.id }, process.env.JWT_SECRET)); res.status(200).redirect("/"); } async getPosts(req: Request, res: Response): Promise { const { userId } = req.params; const posts = await AppDataSource.manager.findBy(Post, {authorId: Number.parseInt(userId)}); console.log(posts); res.status(200).send(posts); } } export default new UserController();