Browse Source

로그인 추가

허용운 5 years ago
parent
commit
3323290e2b
2 changed files with 35 additions and 0 deletions
  1. 5 0
      server/models/user.js
  2. 30 0
      server/routes/auth.js

+ 5 - 0
server/models/user.js

@@ -33,4 +33,9 @@ UserSchema.pre('save', function(next) {
   }
 })
 
+UserSchema.methods.comparePassword = function (password, next) {
+  let user = this
+  return bcrypt.compareSync(password, user.password)
+}
+
 module.exports = mongoose.model('User', UserSchema)

+ 30 - 0
server/routes/auth.js

@@ -51,4 +51,34 @@ router.get('/auth/user', virifyToken, async (req, res) => {
   }
 })
 
+router.post('/auth/login', async (req, res) => {
+  try {
+    let foundUser = await User.findOne({ email: req.body.email})
+    if (!foundUser) {
+      res.status(403).json({
+        success: false,
+        message: 'Authentication failed, User not found '
+      })
+    } else {
+      if (foundUser.comparePassword(req.body.password)) {
+        let token = jwt.sign(foundUser.toJSON(), process.env.SECRET, {
+          expiresIn: 604800
+        })
+s
+        res.json({ success: true, token})
+      } else {
+        res.status(403).json({
+          success: false,
+          message: 'Authentication failed, Wrong password'
+        })
+      }
+    }
+  } catch (err) {
+    res.status(500).json({
+      success: false,
+      message: err.message
+    })    
+  }
+})
+
 module.exports = router