Nodejs 및 mongoDB로 인증 - 3부
자습서의 이 부분에서는
jasonwebtoken (JWT) 을 사용한 로그인을 다룰 것입니다. 마지막에는 사용자를 교차 확인하고 hashed password를 plain text password에 일치시키는 방법을 살펴보겠습니다.시간 낭비 없이 바로 뛰어들자.
스타터 프로젝트
이전 자습서에서 오지 않은 경우 here에서 시작 프로젝트를 가져올 수 있습니다.
로그인 끝점
npm i jsonwebtoken -s
JWT 파일의 맨 위에 있는 const bcrypt = require("bcrypt"); 줄 바로 아래에 있는 app.js 가져오기:
const jwt = require("jsonwebtoken");
register 엔드포인트 바로 아래에 다음 함수를 입력합니다.
app.post("/login", (request, response) => {
})
User.findOne({ email: request.body.email })
다음으로
then...catch... 블록을 사용하여 위의 이메일 검색이 성공했는지 여부를 확인합니다.catch 블록에서 캡처합니다.
User.findOne({ email: request.body.email })
.then()
.catch((e) => {
response.status(404).send({
message: "Email not found",
e,
});
});
then... 블록에서 이 작업을 수행합니다.
.then((user)=>{
bcrypt.compare(request.body.password, user.password)
})
그런 다음
then...catch... 블록을 다시 사용하여 비교가 성공했는지 여부를 확인합니다.catch 블록에 오류 메시지가 반환됩니다.
.then((user)=>{
bcrypt.compare(request.body.password, user.password)
.then()
.catch((error) => {
response.status(400).send({
message: "Passwords does not match",
error,
});
})
})
then 블록에서 암호가 올바른지 다시 확인합시다.
.then((passwordCheck) => {
// check if password matches
if(!passwordCheck) {
return response.status(400).send({
message: "Passwords does not match",
error,
});
}
})
jwt.sign() 함수를 사용하여 임의 토큰을 만듭니다. 3개의 매개변수, 즉 jwt.sign(payload, secretOrPrivateKey, [options, callback])를 취합니다. 더 읽을 수 있습니다 here
bcrypt.compare(request.body.password, user.password)
.then((passwordCheck) => {
// check if password matches
if(!passwordCheck) {
return response.status(400).send({
message: "Passwords does not match",
error,
});
}
// create JWT token
const token = jwt.sign(
{
userId: user._id,
userEmail: user.email,
},
"RANDOM-TOKEN",
{ expiresIn: "24h" }
);
})
.then((user)=>{
bcrypt.compare(request.body.password, user.password)
.then((passwordCheck) => {
// check if password matches
if(!passwordCheck) {
return response.status(400).send({
message: "Passwords does not match",
error,
});
}
// create JWT token
const token = jwt.sign(
{
userId: user._id,
userEmail: user.email,
},
"RANDOM-TOKEN",
{ expiresIn: "24h" }
);
// return success response
response.status(200).send({
message: "Login Successful",
email: user.email,
token,
});
})
// login endpoint
app.post("/login", (request, response) => {
// check if email exists
User.findOne({ email: request.body.email })
// if email exists
.then((user) => {
// compare the password entered and the hashed password found
bcrypt
.compare(request.body.password, user.password)
// if the passwords match
.then((passwordCheck) => {
// check if password matches
if(!passwordCheck) {
return response.status(400).send({
message: "Passwords does not match",
error,
});
}
// create JWT token
const token = jwt.sign(
{
userId: user._id,
userEmail: user.email,
},
"RANDOM-TOKEN",
{ expiresIn: "24h" }
);
// return success response
response.status(200).send({
message: "Login Successful",
email: user.email,
token,
});
})
// catch error if password do not match
.catch((error) => {
response.status(400).send({
message: "Passwords does not match",
error,
});
});
})
// catch error if email does not exist
.catch((e) => {
response.status(404).send({
message: "Email not found",
e,
});
});
});
테스트
tokenemail가 잘못되었거나 존재하지 않는 경우password가 잘못된 경우이 시점에서 이제 막 인증을 정복했으므로 손을 맞잡을 수 있습니다.
👏🏼👏🏼👏🏼👏🏼👏🏼
결론
PART 1에서 데이터베이스를 설정하여 이 인증 시리즈를 시작했고, PART 2에서
user 컬렉션 및 register 엔드포인트에 대한 모델을 생성했으며, 마지막으로 이 파트에서는 login 엔드포인트를 성공적으로 생성했습니다. 사용자가 존재하는지 여부를 확인합니다.축하합니다!!! 🍾🍾🍾
다음에 살펴보겠습니다. 그곳에서 당신을 만나기를 바랍니다.
한편, 모든 코드는 here입니다.
에베레깃 / 인증 백엔드
이 튜토리얼에서는 nodejs 및 mongoDB를 사용하여 사용자 인증을 생성하는 방법을 설명합니다.
Reference
이 문제에 관하여(Nodejs 및 mongoDB로 인증 - 3부), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/ebereplenty/authentication-with-nodejs-and-mongodb-part-3-3mic텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)