유튜브 클로닝 #7-2: 회원 가입 기능 (1)

이현정·2022년 4월 19일
1

🔖 강의 범위 #7.0~7.2

Preview

#7부터는 그동안 배운 이론들(몽고db, 몽구스의 Schema, model, 그외 다양한 기능들, express, pug template 등)을 모두 이용하여 홈페이지의 간단한 기능들을 만들어보는 작업들을 할 것이다.

저번시간에는 search 페이지를 만들어보았다.
이번시간에는 유저 가입 페이지를 만들어 볼 것이다.

핵심 개념

1. 패스워드 해싱(Password Hashing) 🌟

비밀번호 털렸다고? 암호화. 해시함수. 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

2. 그외

  • mongoose.Schema 의 unique:true 속성

  • remove() 명령어 실행이 안될 때
    db.users.remove()는 deprecated되었기 때문에
    db.users.deleteMany({})로 지우시면 됩니다.

강의 내용

step 0. setting

  1. 유저 데이터 형식 만들기
// 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 속성이 새로 등장했다.

  1. 회원가입 페이지 만들기 + POST 기능
// 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")
  1. url 부여하기 + POST 기능
// Router - routers/rootRouter.js

rootRouter.route("/join").get(getJoin).post(postJoin);
  1. 기능할 컨트롤러 생성
// 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");
};
  1. POST 기능 잘되나 db 열어 확인
명령어 순서: mongo -> use 데베 -> show collections -> db.데이터형식.find()

그런데 문제는 db 를 열어보니 password 로 보낸 정보가 너무 잘 드러나는 걸 확인할 수 있다.
보안상의 문제를 해결하기 위해 '패스워드 해싱' 을 이용하여 db 에 보낸 password 가 보이지 않도록 해버리자.

step 1. 패스워드 해싱(Password Hashing) 🌟

  1. bcrypto 를 설치해준다.
npm i bcrypto
  1. 저장 전 미들웨어로 해시기능을 추가해준다.
// 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

  1. db 확인
명령어 순서: mongo -> use 데베 -> show collections -> db.데이터형식.find()

다시 한 번 같은 방식으로 확인했을 때, 이번에는 password 가 알 수 없는 문자,숫자 조합으로 나타난다는 걸 알 수 있다.

추가 공부

x

요약

  • join template 을 만들고 form(method="POST")를 통해 유저 정보를 서버에 받아와서,
  • controller .postJoin 기능으로 데이터 형식을 만들고 db에 보내는 것까지 알아보았다.
  • 그 과정에서 db에 저장된 패스워드 정보가 관리자에게 노출되지 않도록 하는 "해싱" 이라는 개념과 이용법에 대해 알아보았다.

0개의 댓글