added register.js to store hash password to db
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const bcrypt = require("bcrypt"); // bcrypt for password hashing
|
||||
const db = require("../../config/db");
|
||||
|
||||
// User registration endpoint
|
||||
router.post("/", async (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return res.status(400).send("Username and password are required");
|
||||
}
|
||||
|
||||
// Check if the username already exists
|
||||
const sqlCheck = "SELECT * FROM tbl_user WHERE username = ?";
|
||||
db.query(sqlCheck, [username], async (err, results) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
return res.status(500).send("Server error");
|
||||
}
|
||||
|
||||
if (results.length > 0) {
|
||||
return res.status(400).send("Username already exists");
|
||||
}
|
||||
|
||||
try {
|
||||
// Hash the password using bcrypt
|
||||
const saltRounds = 10;
|
||||
const hashedPassword = await bcrypt.hash(password, saltRounds);
|
||||
|
||||
// Insert the new user into the database with the hashed password
|
||||
const sqlInsert = "INSERT INTO tbl_user (username, password) VALUES (?, ?)";
|
||||
db.query(sqlInsert, [username, hashedPassword], (err, result) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
return res.status(500).send("Server error");
|
||||
}
|
||||
|
||||
res.status(201).send("User registered successfully");
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
res.status(500).send("Error registering user");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user