สวัสดีพี่ๆทุกคนครับ ตอนนี้ผมทำ project ที่มหาลัยกับเพื่อนๆอยู่ครับ ถ้า code อ่านยาก งงๆ ขอโทษด้วยนะครับ ผมอยากทราบว่า password ที่ hash แล้วใน db ทำยังไงถึงจะนำ password นั้นนำมา login ได้หรอครับ ผมหาข้อมูลและลองมาหลายวิธีแล้วก็ยังแก้ไม่ได้สักทีครับ รบกวนพี่ๆด้วยครับ
Code Login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
<!-- link -->
<!-- bootstrap -->
<link rel="stylesheet" href="../../public/css/bootstrap.min.css">
<script src="../../public/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="../../public/css/login.css">
<!-- eye icon -->
<link rel="stylesheet" href="
https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
<!-- sweetalert2 -->
<link href="
https://cdn.jsdelivr.net/npm/@sweetalert2/theme-dark@4/dark.css" rel="stylesheet">
<!-- -->
</head>
<body>
<div class="row" id="roww">
<div class="col-sm-4 p-4 border-rounded text-center bluee">
<div class="m-5">
<h1>LOGIN</h1>
<h1>to</h1>
<h1>"Research's borrowing"</h1>
<p>-----------Welcome back!-----------</p>
</div>
<div id="spac"></div>
<img id="bookpic" src="../../public/img/book.png" alt="book.img">
<p class="my-2">Contact us</p>
<a class="text text-white" href="#">supportteam.@aas.ac.th</a>
</div>
<div class="col mt-5 px-5 mx-5">
<form action="/loginstudent" method="POST">
<div id="spac"></div>
<label for="username" class="h1">Username</label>
<input type="text" id="username" name="username" placeholder="USERNAME" class="form-control">
<label for="password" class="h1">Password</label>
<div class="input-group">
<input type="password" id="password" name="password" placeholder="PASSWORD" class="form-control">
<span class="input-group-text">
<i id="togglePassword" class="far fa-eye"></i>
</span>
</div>
<div class="row my-2">
<div>
<input type="checkbox" id="remember" class="text text-mute text-start">
<label for="remember" class="green">Remember me</label>
</div>
<a href="" class="text text-end redt">FORGET PASSWORD?</a>
</div>
<div class="text tex-mute text-end">OR DO YOU NOT HAVE AN ACCOUNT YET? LET <a href="/View/login-register/register.html" class="text green text-end">REGISTER!</a></div>
<button type="submit" id="login" class="btn btn-green text-white border-round my-2 btn-lg">Log in</button>
</form>
</div>
</div>
<script>
const users = [
{ "id": 1, "username": "staff", "password": "1111", "role": 1 },
{ "id": 2, "username": "lecture", "password": "2222", "role": 2 },
{ "id": 3, "username": "user", "password": "3333", "role": 3 }
];
// CheckLocalStorage
const storedUsername = localStorage.getItem('username');
if (storedUsername) {
const foundUser = users.find(user => user.username === storedUsername);
if (foundUser.role) {
if (foundUser.role === 1) {
window.location.replace('/View/Booklist-staff/index.html');
} else if (foundUser.role === 2) {
window.location.replace('../Booklist-lecturer/index.html');
} else if (foundUser.role === 3) {
window.location.replace('../Booklist-user/index.html');
}
}
}
// Check User
document.querySelector("#login").onclick = async function () {
event.preventDefault();
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
try {
const responseStaff = await fetch('/loginstaff');
const responseLecture = await fetch('/loginlecture');
const responseStudent = await fetch('/loginstudent');
const staff = await responseStaff.json();
const lecture = await responseLecture.json();
const student = await responseStudent.json();
const foundStaff = staff.find(user => user.username === username && user.password === password);
const foundLecture = lecture.find(user => user.username === username && user.password === password);
const foundStudent = student.find(user => user.username === username && user.password === password);
if (foundStaff) {
window.location.replace('/View/Booklist-staff/index.html');
} else if (foundLecture) {
window.location.replace('/View/Booklist-lecturer/index.html');
} else if (foundStudent) {
window.location.replace('/View/Booklist-user/index.html');
} else {
Swal.fire({
customClass: {
confirmButton: "custom-button-confirm"
},
icon: 'error',
title: "<h5 style='color: black'>Incorrect!</h5>",
text: "Your username or password are not correct. Please try again.",
confirmButtonColor: "#4d9f9f",
});
}
} catch (error) {
console.error('Error:', error);
}
};
const togglePassword = document.querySelector('#togglePassword');
const passwordd = document.querySelector('#password');
togglePassword.addEventListener('click', function (e) {
// toggle the type attribute
const type = passwordd.getAttribute('type') === 'password' ? 'text' : 'password';
passwordd.setAttribute('type', type);
// toggle the eye slash icon
// this.classList.toggle('fa-eye');
this.classList.toggle('fa-eye-slash');
// adjust margin-left to align the icon properly
// const marginLeft = type === 'password' ? '10px' : '0px';
// this.parentElement.style.marginLeft = marginLeft;
});
</script>
</body>
<!-- script -->
<script src="
https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
<!-- -->
</html>
Code api ต่างๆครับ
const express = require('express')
const mysql = require('mysql');
const app = express();
app.use(express.json())
app.use(express.static(__dirname));
// Index Web
app.get("/", (req, res) => {
res.sendFile(__dirname + "/View/login-register/login.html");
})
// Mysql connection
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'project',
port: '3306'
})
connection.connect((err) => {
if (err) {
console.log('Error connecting to database =', err)
return;
}
console.log('Mysql succesully connected!');
})
//Create User
const bcrypt = require('bcrypt');
const saltRound = 10;
app.post("/createstudent", async (req, res) => {
const {id, username, password, fullname, email } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, saltRound);
connection.query(
"INSERT INTO user(id ,username, password, fullname, email, role) VALUES(?, ?, ?, ?, ?, ?)",
[id, username, hashedPassword, fullname, email, 1],
(err, results, fields) => {
if (err) {
console.log('Error while inserting a user into the database', err);
return res.status(401).send();
}
return res.status(200).json({message: "New user succesfully created!"})
}
)
} catch(err) {
console.log(err);
return res.status(500).send();
}
});
// Read User
app.get("/loginstaff", async (req, res) => {
try {
connection.query("SELECT * FROM user WHERE role = 3", (err, results, fields) => {
if(err) {
console.log(err);
return res.status(401).send();
}
res.status(200).json(results)
})
} catch (err) {
console.log(err);
return res.status(500).send();
}
})
app.get("/loginlecture", async (req, res) => {
try {
connection.query("SELECT * FROM user WHERE role = 2", (err, results, fields) => {
if(err) {
console.log(err);
return res.status(401).send();
}
res.status(200).json(results)
})
} catch (err) {
console.log(err);
return res.status(500).send();
}
})
app.get("/loginstudent", async (req, res) => {
try {
connection.query("SELECT * FROM user WHERE role = 1", (err, results, fields) => {
if(err) {
console.log(err);
return res.status(401).send();
}
res.status(200).json(results)
})
} catch (err) {
console.log(err);
return res.status(500).send();
}
})
// Set Port
app.listen(3000, ()=> console.log('Server is running on port 3000'));
เป็นไปได้อยากให้แก้โค๊ดแล้วเขียนคอมเม้นในส่วนที่ผิดพลาดไว้ให้ครับ อยากไปนั่งทำความเข้าใจในสิ่งที่ผิดพลาครับ ยังไงรบกวนด้วยครับ ขอบคุณครับ
login จาก password ที่ hash แล้วใน node js ทำยังไงหรอครับ
Code Login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
<!-- link -->
<!-- bootstrap -->
<link rel="stylesheet" href="../../public/css/bootstrap.min.css">
<script src="../../public/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="../../public/css/login.css">
<!-- eye icon -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
<!-- sweetalert2 -->
<link href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-dark@4/dark.css" rel="stylesheet">
<!-- -->
</head>
<body>
<div class="row" id="roww">
<div class="col-sm-4 p-4 border-rounded text-center bluee">
<div class="m-5">
<h1>LOGIN</h1>
<h1>to</h1>
<h1>"Research's borrowing"</h1>
<p>-----------Welcome back!-----------</p>
</div>
<div id="spac"></div>
<img id="bookpic" src="../../public/img/book.png" alt="book.img">
<p class="my-2">Contact us</p>
<a class="text text-white" href="#">supportteam.@aas.ac.th</a>
</div>
<div class="col mt-5 px-5 mx-5">
<form action="/loginstudent" method="POST">
<div id="spac"></div>
<label for="username" class="h1">Username</label>
<input type="text" id="username" name="username" placeholder="USERNAME" class="form-control">
<label for="password" class="h1">Password</label>
<div class="input-group">
<input type="password" id="password" name="password" placeholder="PASSWORD" class="form-control">
<span class="input-group-text">
<i id="togglePassword" class="far fa-eye"></i>
</span>
</div>
<div class="row my-2">
<div>
<input type="checkbox" id="remember" class="text text-mute text-start">
<label for="remember" class="green">Remember me</label>
</div>
<a href="" class="text text-end redt">FORGET PASSWORD?</a>
</div>
<div class="text tex-mute text-end">OR DO YOU NOT HAVE AN ACCOUNT YET? LET <a href="/View/login-register/register.html" class="text green text-end">REGISTER!</a></div>
<button type="submit" id="login" class="btn btn-green text-white border-round my-2 btn-lg">Log in</button>
</form>
</div>
</div>
<script>
const users = [
{ "id": 1, "username": "staff", "password": "1111", "role": 1 },
{ "id": 2, "username": "lecture", "password": "2222", "role": 2 },
{ "id": 3, "username": "user", "password": "3333", "role": 3 }
];
// CheckLocalStorage
const storedUsername = localStorage.getItem('username');
if (storedUsername) {
const foundUser = users.find(user => user.username === storedUsername);
if (foundUser.role) {
if (foundUser.role === 1) {
window.location.replace('/View/Booklist-staff/index.html');
} else if (foundUser.role === 2) {
window.location.replace('../Booklist-lecturer/index.html');
} else if (foundUser.role === 3) {
window.location.replace('../Booklist-user/index.html');
}
}
}
// Check User
document.querySelector("#login").onclick = async function () {
event.preventDefault();
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
try {
const responseStaff = await fetch('/loginstaff');
const responseLecture = await fetch('/loginlecture');
const responseStudent = await fetch('/loginstudent');
const staff = await responseStaff.json();
const lecture = await responseLecture.json();
const student = await responseStudent.json();
const foundStaff = staff.find(user => user.username === username && user.password === password);
const foundLecture = lecture.find(user => user.username === username && user.password === password);
const foundStudent = student.find(user => user.username === username && user.password === password);
if (foundStaff) {
window.location.replace('/View/Booklist-staff/index.html');
} else if (foundLecture) {
window.location.replace('/View/Booklist-lecturer/index.html');
} else if (foundStudent) {
window.location.replace('/View/Booklist-user/index.html');
} else {
Swal.fire({
customClass: {
confirmButton: "custom-button-confirm"
},
icon: 'error',
title: "<h5 style='color: black'>Incorrect!</h5>",
text: "Your username or password are not correct. Please try again.",
confirmButtonColor: "#4d9f9f",
});
}
} catch (error) {
console.error('Error:', error);
}
};
const togglePassword = document.querySelector('#togglePassword');
const passwordd = document.querySelector('#password');
togglePassword.addEventListener('click', function (e) {
// toggle the type attribute
const type = passwordd.getAttribute('type') === 'password' ? 'text' : 'password';
passwordd.setAttribute('type', type);
// toggle the eye slash icon
// this.classList.toggle('fa-eye');
this.classList.toggle('fa-eye-slash');
// adjust margin-left to align the icon properly
// const marginLeft = type === 'password' ? '10px' : '0px';
// this.parentElement.style.marginLeft = marginLeft;
});
</script>
</body>
<!-- script -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
<!-- -->
</html>
Code api ต่างๆครับ
const express = require('express')
const mysql = require('mysql');
const app = express();
app.use(express.json())
app.use(express.static(__dirname));
// Index Web
app.get("/", (req, res) => {
res.sendFile(__dirname + "/View/login-register/login.html");
})
// Mysql connection
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'project',
port: '3306'
})
connection.connect((err) => {
if (err) {
console.log('Error connecting to database =', err)
return;
}
console.log('Mysql succesully connected!');
})
//Create User
const bcrypt = require('bcrypt');
const saltRound = 10;
app.post("/createstudent", async (req, res) => {
const {id, username, password, fullname, email } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, saltRound);
connection.query(
"INSERT INTO user(id ,username, password, fullname, email, role) VALUES(?, ?, ?, ?, ?, ?)",
[id, username, hashedPassword, fullname, email, 1],
(err, results, fields) => {
if (err) {
console.log('Error while inserting a user into the database', err);
return res.status(401).send();
}
return res.status(200).json({message: "New user succesfully created!"})
}
)
} catch(err) {
console.log(err);
return res.status(500).send();
}
});
// Read User
app.get("/loginstaff", async (req, res) => {
try {
connection.query("SELECT * FROM user WHERE role = 3", (err, results, fields) => {
if(err) {
console.log(err);
return res.status(401).send();
}
res.status(200).json(results)
})
} catch (err) {
console.log(err);
return res.status(500).send();
}
})
app.get("/loginlecture", async (req, res) => {
try {
connection.query("SELECT * FROM user WHERE role = 2", (err, results, fields) => {
if(err) {
console.log(err);
return res.status(401).send();
}
res.status(200).json(results)
})
} catch (err) {
console.log(err);
return res.status(500).send();
}
})
app.get("/loginstudent", async (req, res) => {
try {
connection.query("SELECT * FROM user WHERE role = 1", (err, results, fields) => {
if(err) {
console.log(err);
return res.status(401).send();
}
res.status(200).json(results)
})
} catch (err) {
console.log(err);
return res.status(500).send();
}
})
// Set Port
app.listen(3000, ()=> console.log('Server is running on port 3000'));
เป็นไปได้อยากให้แก้โค๊ดแล้วเขียนคอมเม้นในส่วนที่ผิดพลาดไว้ให้ครับ อยากไปนั่งทำความเข้าใจในสิ่งที่ผิดพลาครับ ยังไงรบกวนด้วยครับ ขอบคุณครับ