forked from lucaspatenaude/ScoreSpot
Updated to separate login routes from app.js
This commit is contained in:
57
src/routes/database/register.js
Normal file
57
src/routes/database/register.js
Normal file
@@ -0,0 +1,57 @@
|
||||
const express = require("express");
|
||||
const path = require("path");
|
||||
const handlebars = require("express-handlebars");
|
||||
const Handlebars = require("handlebars");
|
||||
const bodyParser = require("body-parser");
|
||||
const bcrypt = require("bcryptjs"); // To hash passwords
|
||||
const session = require("express-session"); // To set the session object. To store or access session data, use the `req.session`, which is (generally) serialized as JSON by the store.
|
||||
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;
|
||||
Reference in New Issue
Block a user