# 8.4-5 Change Password

이원규·2022년 7월 3일
0

Itube

목록 보기
29/46

Change Password

1. views 수정.(edit-profile에 비밀번호 변경하는 url 추가)

  • 상대 url 사용. 맨 마지막 /이후로만 바뀜. 링크: http://localhost:4000/users/change-password 이것처럼 맨 마지막 / 이후로만 바뀜.
  • 깃허브로 로그인 한 사람은 password바꾸기 링크를 못 보게 생성했음.
//추가 -> 
if !loggedInUser.socialOnly
            hr
            a(href="change-password") Change Password →

2. router(userRouter)만들기

import {getEdit, postEdit, logout, see, startGithubLogin, callbackGithubLogin, getChangePassword, postChangePassword} from "../controllers/userController";

userRouter.route("change-password").all(protectorMiddleware).get(getChangePassword).post(postChangePassword);

3. view만들기(views/users/change-password.pug)

extends ../base //이 password.pug가 users파일 내에 있어서 ../로 파일 나가고 base import해준 것임.

block content
    form(method="POST")
        input(placeholder="Old Password", type="password", name="oldPassword")
        input(placeholder="New Password", type="password", name="newPassword")
        input(placeholder="New Password Confirmation", type="password", name="newPasswordConfirmation")
        input(value="Change Password", type="submit")

4. UserController

  • 깃허브로 로그인 한 사람은 password바꾸기를 보면 안됨.
export const getChangePassword = (req, res) => {
    if(req.session.user.socialOnly === true){
        return res.redirect("/");
    }
    return res.render("users/change-password",{pageTitle:"Change Password"});
};

export const postChangePassword = async (req, res) => {
    const { session: {user: {_id}}, body: { oldPassword, newPassword, newPasswordConfirmation }} = req;
    const user = await User.findById(_id);
    const ok = await bcrypt.compare(oldPassword, user.password)//bcrypt: 비밀번호 암호화 해주는 패키지 , compare: 두 인수를 받아 첫번째는 암호화하여 비교하고, 두번째는 그 상태 그대로(암호화가 이미 걸린상태) 두고 두 인수를 비교한다. 출력값은 Boolean
    if(!ok){
        return res.status(400).render("users/change-password",{pageTitle:"Change Password", errorMessage: "The current password is incorrect"});
    }
    if(newPassword !== newPasswordConfirmation){
        return res.status(400).render("users/change-password",{pageTitle:"Change Password", errorMessage: "The password does not match the confirmation"});
    }
    
    user.password = newPassword;//user.password를 새로운 비밀번호로 바꿔주는 것임.
    await user.save(); // model내장 함수 save()를 발동시킴. save: password를 hash화 시켜서 저장함.(user model파일에 pre(save)내장 함수가 있기에 해쉬화ㅡ되는 것임.) // save는 promise일지도 모르기에 await을 해줌
    // send notification
    return res.redirect("/users/logout");
};
profile
github: https://github.com/WKlee0607

0개의 댓글