728x90
간단 암호화된 로그인 만들어 보기
JS
// 모듈 express, fs, mysql
// express열고, 데이터베이스 연결까지
// 데이터베이스 이름은 test8
// express에서 body객체 사용
const express = require("express");
const fs = require("fs");
const app = express();
const mysql = require("mysql2");
let client = mysql.createConnection({
user: "root",
password: "kga22C3_05^",
database: "test8",
multipleStatements: true,
});
const makeTable =
"CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, user_id VARCHAR(255), password VARCHAR(255), salt VARCHAR(255))";
client.query(makeTable, (err, result) => {
if (err) {
console.log("이미 users Table이 있습니다.");
return;
} else {
console.log("users Table이 생성되었습니다.");
}
});
app.use(express.urlencoded({ extended: false }));
app.listen(3000, () => {
console.log("server start");
});
app.get("/", (req, res) => {
fs.readFile("view/join.html", "utf-8", (err, data) => {
res.send(data);
});
});
app.get("/login", (req, res) => {
fs.readFile("view/login.html", "utf-8", (err, data) => {
res.send(data);
});
});
app.post("/join", async (req, res) => {
const { password, salt } = await createPwHashed(req.body.user_pw);
const sql = "INSERT INTO users (user_id,password,salt) VALUES(?,?,?)";
client.query(sql, [req.body.user_id, password, salt], (err, result) => {
if (err) throw err;
res.redirect("/login");
});
});
app.post("/login", async (req, res) => {
const { user_id, user_pw } = req.body;
pwHashed(user_id, user_pw)
.then((result) => {
res.send(result + "로그인 성공");
})
.catch((err) => {
res.send(err);
});
});
join.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="/join" method="post">
<input type="text" name="user_id" />
<input type="text" name="user_pw" />
<button>가입하기</button>
</form>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="/login" method="post">
<!-- 요청 보냈을때 body 객체 안에 user_id, user_pw의 키값으로 input 값이 전달된다. -->
<input type="text" name="user_id" />
<input type="text" name="user_pw" />
<button>로그인</button>
</form>
</body>
</html>
728x90
'개발 > node.js' 카테고리의 다른 글
sequelize 외래키 설정 (0) | 2022.08.25 |
---|---|
[Node.js] mysql FOREIGN KEY (0) | 2022.08.18 |
[Node.js] crypto, bcrypto (0) | 2022.08.17 |
[Node.js] access token, refresh token 을 활용하여 로그인 유지시키기 (0) | 2022.08.16 |
[Node.js] 로그인 Access Token, Refresh Token (0) | 2022.08.16 |