🔖 강의 범위 #7.0~7.2
#7부터는 그동안 배운 이론들(몽고db, 몽구스의 Schema, model, 그외 다양한 기능들, express, pug template 등)을 모두 이용하여 홈페이지의 간단한 기능들을 만들어보는 작업들을 할 것이다.
저번시간에는 search 페이지를 만들어보았다.
이번시간에는 유저 가입 페이지를 만들어 볼 것이다.
비밀번호 털렸다고? 암호화. 해시함수. 5분 설명 영상
https://www.youtube.com/watch?v=67UwxR3ts2E
해시함수 테스트
https://emn178.github.io/online-tools/sha256.html
bcrypt 설치
암호를 해시하는 데 도움이 되는 라이브러리입니다.
npm i bcrypt
https://www.npmjs.com/package/bcrypt
mongoose.Schema 의 unique:true 속성
remove() 명령어 실행이 안될 때
db.users.remove()는 deprecated되었기 때문에
db.users.deleteMany({})로 지우시면 됩니다.
// Model - models/User.js 생성
import mongoose from "mongoose";
const userSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true },
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
name: { type: String, required: true },
location: String,
});
const User = mongoose.model('User', userSchema);
export default User;
mongoose.Schema 의 unique:true 속성이 새로 등장했다.
// Template - views/join.pug 생성
extends base
block contents
form(method="POST")
input(name="name" type="text" placeholder="Name" required)
input(name="username" type="text" placeholder="User Name" required)
input(name="email" type="email" placeholder="e-mail" required)
input(name="password" type="password" placeholder="Password" required)
input(name="location" type="text" placeholder="Location" required)
input(type="submit" value="Join")
// Router - routers/rootRouter.js
rootRouter.route("/join").get(getJoin).post(postJoin);
// Controller - controllers/userController.js
export const getJoin = (req, res) => {
return res.render("join", { pageTitle : "Join"});
};
export const postJoin = async (req,res) => {
console.log(req.body);
const { name, username, email, password, location } = req.body;
await User.create({
name, username, email, password, location
})
return res.redirect("/login");
};
명령어 순서: mongo -> use 데베 -> show collections -> db.데이터형식.find()
그런데 문제는 db 를 열어보니 password 로 보낸 정보가 너무 잘 드러나는 걸 확인할 수 있다.
보안상의 문제를 해결하기 위해 '패스워드 해싱' 을 이용하여 db 에 보낸 password 가 보이지 않도록 해버리자.
npm i bcrypto
// Template - views/join.pug
userSchema.pre('save', async function () {
this.password = await bcrypt.hash(this.password, 5);
});
! 복습: 몽구스의 미들웨어(pre,post)
Schema.prototype.pre()
https://mongoosejs.com/docs/api.html#schema_Schema-pre
명령어 순서: mongo -> use 데베 -> show collections -> db.데이터형식.find()
다시 한 번 같은 방식으로 확인했을 때, 이번에는 password 가 알 수 없는 문자,숫자 조합으로 나타난다는 걸 알 수 있다.
x