hub-site/backend/routes/auth.js
2024-11-16 14:14:49 -08:00

67 lines
1.8 KiB
JavaScript

import { Router } from "express";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import pkg from "pg"; // Importing the whole CommonJS module
const { Pool } = pkg; // Destructuring Pool from the imported CommonJS module
const router = Router();
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
});
const JWT_SECRET = process.env.JWT_SECRET || "your_jwt_secret";
// Register
router.post("/register", async (req, res) => {
const { username, password } = req.body;
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" });
}
});
// Login
router.post("/login", async (req, res) => {
const { username, password } = req.body;
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" });
}
});
export default router;