Change Password
1. views 수정.(edit-profile에 비밀번호 변경하는 url 추가)
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
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)
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;
await user.save();
return res.redirect("/users/logout");
};