forked from lucaspatenaude/ScoreSpot
54 lines
1.6 KiB
JavaScript
54 lines
1.6 KiB
JavaScript
const express = require("express");
|
|
const db = require("../../database/db"); // Import the db modulei
|
|
const bcrypt = require("bcryptjs"); // To hash passwords
|
|
const router = express.Router();
|
|
|
|
// Trigger Registration Form to Post
|
|
router.post("/register", async (req, res) => {
|
|
try {
|
|
if (!req.body.username || !req.body.password) {
|
|
// If username or password is missing, respond with status 400 and an error message
|
|
return res
|
|
.status(400)
|
|
.json({ status: "error", message: "Invalid input" });
|
|
}
|
|
|
|
// Check if the username already exists in the database
|
|
const existingUser = await db.oneOrNone(
|
|
"SELECT * FROM users WHERE username = $1",
|
|
req.body.username
|
|
);
|
|
if (existingUser) {
|
|
// If a user with the same username already exists, respond with status 409 and an error message
|
|
return res
|
|
.status(409)
|
|
.json({ status: "error", message: "Username already exists" });
|
|
}
|
|
|
|
// Hash the password using bcrypt library
|
|
const hash = await bcrypt.hash(req.body.password, 10);
|
|
|
|
// Insert username and hashed password into the 'users' table
|
|
await db.none("INSERT INTO users (username, password) VALUES ($1, $2)", [
|
|
req.body.username,
|
|
hash,
|
|
]);
|
|
const user = await db.oneOrNone(
|
|
"SELECT * FROM users WHERE username = $1",
|
|
req.body.username
|
|
);
|
|
req.session.user = user;
|
|
req.session.save();
|
|
// Redirect user to the home page
|
|
res.redirect("/");
|
|
} catch (error) {
|
|
// If an error occurs during registration, respond with status 500 and an error message
|
|
res.status(500).json({
|
|
status: "error",
|
|
message: "An error occurred during registration",
|
|
});
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|