박민정

[feat] Generate token

...@@ -13,6 +13,9 @@ app.use(bodyParser.json()) // application/json 타입으로 된 데이터를 ...@@ -13,6 +13,9 @@ app.use(bodyParser.json()) // application/json 타입으로 된 데이터를
13 13
14 const config = require('./config/key') 14 const config = require('./config/key')
15 15
16 +const cookieParser = require('cookie-parser')
17 +app.use(cookieParser())
18 +
16 const mongoose = require('mongoose') 19 const mongoose = require('mongoose')
17 20
18 //이 정보는 비밀임..! 몽고DB아이디랑 비밀번호를 감춰야해..! 21 //이 정보는 비밀임..! 몽고DB아이디랑 비밀번호를 감춰야해..!
...@@ -48,6 +51,34 @@ app.post('/register', (req, res) => { ...@@ -48,6 +51,34 @@ app.post('/register', (req, res) => {
48 51
49 }) 52 })
50 53
54 +// 로그인 구현
55 +app.post('/login', (req, res) => {
56 + // 1. 요청된 이메일이 데이터베이스에 있는지 찾기
57 + User.findOne({ email: req.body.email }, (err, user) => {
58 + if(!user)
59 + {
60 + return res.json({
61 + loginSuccess: false,
62 + message: "There is no user with that email."
63 + })
64 + }
65 + // 2. email과 비밀번호가 맞는지 확인 (User.js에 comparePassword 함수 정의되어 있음)
66 + user.comparePassword(req.body.password, (err, isMatch) => {
67 + if(!isMatch)
68 + return res.json({loginSuccess: false, message: "Password is not match."})
69 + // 3. 비밀번호까지 맞다면 유저를 위한 토큰 생성 (User.js에 generateToken 함수 정의)
70 + user.generateToken((err, user) => { // err가 없으면 user에 정보 받아옴
71 + if(err)
72 + return res.status(400).send(err);
73 + // 4. 생성한 토큰을 저장함 -> 쿠키나 로컬 스토리지 등에 저장할 수 있는데 여기선 쿠키에 저장
74 + res.cookie("loginCookie", user.token)
75 + .status(200) //성공했다는 표시
76 + .json({loginSuccess: true, userId: user._id})
77 + })
78 + })
79 + })
80 +})
81 +
51 app.listen(port, () => { 82 app.listen(port, () => {
52 console.log(`Example app listening at http://localhost:${port}`) 83 console.log(`Example app listening at http://localhost:${port}`)
53 }) 84 })
......
...@@ -5,6 +5,9 @@ const bcrypt = require('bcrypt') ...@@ -5,6 +5,9 @@ const bcrypt = require('bcrypt')
5 // bcrypt 사용하기 위해 salt를 생성하고 그걸 이용해 암호화 시킴 5 // bcrypt 사용하기 위해 salt를 생성하고 그걸 이용해 암호화 시킴
6 const saltRounds = 10 // salt를 몇글자 할 건지 6 const saltRounds = 10 // salt를 몇글자 할 건지
7 7
8 +//
9 +const jwt = require('jsonwebtoken')
10 +
8 const userSchema = mongoose.Schema({ 11 const userSchema = mongoose.Schema({
9 name:{ 12 name:{
10 type: String, 13 type: String,
...@@ -54,10 +57,38 @@ userSchema.pre('save', function( next ){ ...@@ -54,10 +57,38 @@ userSchema.pre('save', function( next ){
54 }); 57 });
55 }); 58 });
56 } 59 }
57 - 60 + else
61 + {
62 + next()
63 + }
58 64
59 }) 65 })
60 66
67 +userSchema.methods.comparePassword = function(plainPassword, cb){
68 +
69 + // 1. plainPassword가 1234567 암호화된 비밀번호 가 같은지 체크해야함
70 + // 그러면 plainPassword도 암호화해서 비교해야함. (복호화 할 수 없기 때문에)
71 + bcrypt.compare(plainPassword, this.password, function(err, isMatch)
72 + { // 에러가 나면 err callback, 아니면 isMatch
73 + if(err) return cb(err);
74 + cb(null, isMatch);
75 + })
76 +}
77 +
78 +userSchema.methods.generateToken = function(cb)
79 +{
80 + var user = this;
81 + // jsonwebtoken을 이용해서 token 생성
82 + var token = jwt.sign(user._id.toHexString(), 'secretToken') //database에 있는 id라서 _id
83 +
84 + user.token = token
85 + user.save(function(err, user){
86 + if(err)
87 + return cb(err) // 에러가 있다면 callback으로 에러 전달
88 + cb(null, user) // 에러가 없다면 err는 없고 user정보만 전달
89 + })
90 +
91 +}
61 92
62 // 만든 스키마를 모델로 감싸줌 93 // 만든 스키마를 모델로 감싸줌
63 const User = mongoose.model('User', userSchema) 94 const User = mongoose.model('User', userSchema)
......
...@@ -268,6 +268,11 @@ ...@@ -268,6 +268,11 @@
268 "resolved": "https://registry.npmjs.org/bson/-/bson-1.1.6.tgz", 268 "resolved": "https://registry.npmjs.org/bson/-/bson-1.1.6.tgz",
269 "integrity": "sha512-EvVNVeGo4tHxwi8L6bPj3y3itEvStdwvvlojVxxbyYfoaxJ6keLgrTuKdyfEAszFK+H3olzBuafE0yoh0D1gdg==" 269 "integrity": "sha512-EvVNVeGo4tHxwi8L6bPj3y3itEvStdwvvlojVxxbyYfoaxJ6keLgrTuKdyfEAszFK+H3olzBuafE0yoh0D1gdg=="
270 }, 270 },
271 + "buffer-equal-constant-time": {
272 + "version": "1.0.1",
273 + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
274 + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk="
275 + },
271 "bytes": { 276 "bytes": {
272 "version": "3.1.0", 277 "version": "3.1.0",
273 "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", 278 "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
...@@ -442,6 +447,15 @@ ...@@ -442,6 +447,15 @@
442 "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", 447 "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz",
443 "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==" 448 "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg=="
444 }, 449 },
450 + "cookie-parser": {
451 + "version": "1.4.5",
452 + "resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.5.tgz",
453 + "integrity": "sha512-f13bPUj/gG/5mDr+xLmSxxDsB9DQiTIfhJS/sqjrmfAWiAN+x2O4i/XguTL9yDZ+/IFDanJ+5x7hC4CXT9Tdzw==",
454 + "requires": {
455 + "cookie": "0.4.0",
456 + "cookie-signature": "1.0.6"
457 + }
458 + },
445 "cookie-signature": { 459 "cookie-signature": {
446 "version": "1.0.6", 460 "version": "1.0.6",
447 "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", 461 "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
...@@ -527,6 +541,14 @@ ...@@ -527,6 +541,14 @@
527 "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=", 541 "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=",
528 "dev": true 542 "dev": true
529 }, 543 },
544 + "ecdsa-sig-formatter": {
545 + "version": "1.0.11",
546 + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
547 + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
548 + "requires": {
549 + "safe-buffer": "^5.0.1"
550 + }
551 + },
530 "ee-first": { 552 "ee-first": {
531 "version": "1.1.1", 553 "version": "1.1.1",
532 "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", 554 "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
...@@ -976,6 +998,49 @@ ...@@ -976,6 +998,49 @@
976 "integrity": "sha1-Wx85evx11ne96Lz8Dkfh+aPZqJg=", 998 "integrity": "sha1-Wx85evx11ne96Lz8Dkfh+aPZqJg=",
977 "dev": true 999 "dev": true
978 }, 1000 },
1001 + "jsonwebtoken": {
1002 + "version": "8.5.1",
1003 + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz",
1004 + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==",
1005 + "requires": {
1006 + "jws": "^3.2.2",
1007 + "lodash.includes": "^4.3.0",
1008 + "lodash.isboolean": "^3.0.3",
1009 + "lodash.isinteger": "^4.0.4",
1010 + "lodash.isnumber": "^3.0.3",
1011 + "lodash.isplainobject": "^4.0.6",
1012 + "lodash.isstring": "^4.0.1",
1013 + "lodash.once": "^4.0.0",
1014 + "ms": "^2.1.1",
1015 + "semver": "^5.6.0"
1016 + },
1017 + "dependencies": {
1018 + "ms": {
1019 + "version": "2.1.3",
1020 + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
1021 + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
1022 + }
1023 + }
1024 + },
1025 + "jwa": {
1026 + "version": "1.4.1",
1027 + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz",
1028 + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==",
1029 + "requires": {
1030 + "buffer-equal-constant-time": "1.0.1",
1031 + "ecdsa-sig-formatter": "1.0.11",
1032 + "safe-buffer": "^5.0.1"
1033 + }
1034 + },
1035 + "jws": {
1036 + "version": "3.2.2",
1037 + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",
1038 + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",
1039 + "requires": {
1040 + "jwa": "^1.4.1",
1041 + "safe-buffer": "^5.0.1"
1042 + }
1043 + },
979 "kareem": { 1044 "kareem": {
980 "version": "2.3.2", 1045 "version": "2.3.2",
981 "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.3.2.tgz", 1046 "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.3.2.tgz",
...@@ -999,6 +1064,41 @@ ...@@ -999,6 +1064,41 @@
999 "package-json": "^6.3.0" 1064 "package-json": "^6.3.0"
1000 } 1065 }
1001 }, 1066 },
1067 + "lodash.includes": {
1068 + "version": "4.3.0",
1069 + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
1070 + "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8="
1071 + },
1072 + "lodash.isboolean": {
1073 + "version": "3.0.3",
1074 + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
1075 + "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY="
1076 + },
1077 + "lodash.isinteger": {
1078 + "version": "4.0.4",
1079 + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
1080 + "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M="
1081 + },
1082 + "lodash.isnumber": {
1083 + "version": "3.0.3",
1084 + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
1085 + "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w="
1086 + },
1087 + "lodash.isplainobject": {
1088 + "version": "4.0.6",
1089 + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
1090 + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs="
1091 + },
1092 + "lodash.isstring": {
1093 + "version": "4.0.1",
1094 + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
1095 + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE="
1096 + },
1097 + "lodash.once": {
1098 + "version": "4.1.1",
1099 + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
1100 + "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w="
1101 + },
1002 "lowercase-keys": { 1102 "lowercase-keys": {
1003 "version": "1.0.1", 1103 "version": "1.0.1",
1004 "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", 1104 "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz",
...@@ -1513,8 +1613,7 @@ ...@@ -1513,8 +1613,7 @@
1513 "semver": { 1613 "semver": {
1514 "version": "5.7.1", 1614 "version": "5.7.1",
1515 "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", 1615 "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz",
1516 - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", 1616 + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ=="
1517 - "dev": true
1518 }, 1617 },
1519 "semver-diff": { 1618 "semver-diff": {
1520 "version": "3.1.1", 1619 "version": "3.1.1",
......
...@@ -13,7 +13,9 @@ ...@@ -13,7 +13,9 @@
13 "dependencies": { 13 "dependencies": {
14 "bcrypt": "^5.0.1", 14 "bcrypt": "^5.0.1",
15 "body-parser": "^1.19.0", 15 "body-parser": "^1.19.0",
16 + "cookie-parser": "^1.4.5",
16 "express": "^4.17.1", 17 "express": "^4.17.1",
18 + "jsonwebtoken": "^8.5.1",
17 "mongoose": "^5.12.12" 19 "mongoose": "^5.12.12"
18 }, 20 },
19 "devDependencies": { 21 "devDependencies": {
......