본문 바로가기
웹/Node.js

[MongoDB] 비밀번호 일치 확인, 토큰 생성

by ohojee 2023. 2. 27.

토큰 생성을 위해 라이브러리를 설치해야 된다

npm install jsonwebtoken --save

https://www.npmjs.com/package/jsonwebtoken

 

jsonwebtoken

JSON Web Token implementation (symmetric and asymmetric). Latest version: 9.0.0, last published: 2 months ago. Start using jsonwebtoken in your project by running `npm i jsonwebtoken`. There are 22578 other projects in the npm registry using jsonwebtoken.

www.npmjs.com

npm install cookie-parser --save

쿠키에 저장하기 위해 cookie-parser 설치

//index.js

app.post('/login', (req, res) => {
	//로그인 요청된 이메일이 DB에 있는지 확인
	User.findOne({ email: req.body.email }, (err, user) => {
		if (!user) { //user collection 안에 전달된 이메일을 가진 유저가 없다면
			return res.json({
				loginSuccess: false,
				message: "제공된 이메일에 해당하는 유저가 없습니다."
		})
	}
	//요청된 이메일이 DB에 있다면 pwd가 일치하는지 확인
	user.comparePassword(req.body.password,  (err, isMatch) => {
		if (!isMatch)
		return res.json({ 
			loginSuccess: false, 
			message: "비밀번호가 틀렸습니다."})
	})
	//일치한다면 토큰 생성
	user.generateToken((err, user) => {
		if (err) return res.status(400).send(err); //400: 에러났다는 상태
		//토큰을 쿠키, 로컬스토리지 등에 저장할 수 있는데 쿠키에 저장
		res.cookie("x_auth", user.token)
		.status(200)
		.json({ loginSuccess : true, useId: user._id })
	})

	})
})​
//User.js

const jwt = require('jsonwebtoken');

userSchema.methods.comparePassword = function(plainPassword, cb) {
	//pwd가 맞는지 비교하기 위해서는 plainPwd를 암호화해서 이미 암호화된 비밀번호(hash)와 비교해야함, 암호화된걸 다시 복호화할 수는 없음
	bcypt.compare(plainPassword, this.password, function(err, isMatch) {
		if (err) return cb(err), //같지 않다면 err
		cb(null, isMatch) //같다면 에러는 null, isMatch(true): 비밀번호는 같다
	})
}

userSchema.methods.generateToken = function(cb) {
	var user = this;
	//jsonwebtoken을 이용해 토큰 생성
	var token = jwt.sign(user._id.toHexString(), 'secretToken')
	//user._id + 'secretToken' = token
	//token 해석할 때 secretToken를 넣으면 user._id이 해석됨
	user.token = token
	user.save (function(err, user) {
		if (err) return cb(err)
		cb(null, user)
	})
}

이전에 입력해뒀던 이메일과 pwd를 올바르게 입력하면 loginSuccess: true라고 뜬다

로그인하면 토큰 생성

댓글