import bcrypt from "bcrypt"; import jwt from "jsonwebtoken"; import { Pool } from "pg"; const pool = new Pool(); const JWT_SECRET = process.env.JWT_SECRET || "your_jwt_secret"; export const register = async (req, res) => { const { username, password } = req.body; if (!username || !password) { return res.status(400).json({ message: "Username and password are required" }); } try { const hashedPassword = await bcrypt.hash(password, 10); await pool.query( "INSERT INTO users (username, password) VALUES ($1, $2)", [username, hashedPassword] ); res.status(201).json({ message: "User registered successfully" }); } catch (error) { console.error(error); res.status(500).json({ message: "Error registering user" }); } }; export const login = async (req, res) => { const { username, password } = req.body; if (!username || !password) { return res.status(400).json({ message: "Username and password are required" }); } try { const result = await pool.query("SELECT * FROM users WHERE username = $1", [username]); if (result.rows.length === 0) { return res.status(401).json({ message: "Invalid username or password" }); } const user = result.rows[0]; const isPasswordValid = await bcrypt.compare(password, user.password); if (!isPasswordValid) { return res.status(401).json({ message: "Invalid username or password" }); } const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET, { expiresIn: "1h", }); res.json({ token }); } catch (error) { console.error(error); res.status(500).json({ message: "Error logging in" }); } };