users.js 1.7 KB
Newer Older
CHAERIN KIM's avatar
CHAERIN KIM committed
1
2
3
4
const express = require('express');
const User = require('../schemas/user');
const bcrypt = require("bcrypt");
const { verifyToken } = require('./middlewares');
Kim, Chaerin's avatar
어헛    
Kim, Chaerin committed
5

CHAERIN KIM's avatar
CHAERIN KIM committed
6
7
8
const router = express.Router();

router.post('/', function (req, res, next) {
9
10
11
12
13
  console.log('/users post req.body', req.body)
  User.findOne({ id: req.body.id }, function (err, users) {
    if (err) return res.status(500).json({ error: err });

    if (users) {
14
      return res.status(404).json({ error: '이미 존재하는 학번입니다.' })
15
16
17
18
19
20
    };

    const user = new User({
      name: req.body.name,
      id: req.body.id,
      password: req.body.password,
21
22
      question: req.body.question,
      answer: req.body.answer,
23
24
25
26
27
28
29
30
31
32
33
34
    });

    user.save()
      .then((result) => {
        console.log(result);
        res.status(201).json(result);
      })
      .catch((err) => {
        console.error(err);
        next(err);
      });
  })
Kim, Chaerin's avatar
어헛    
Kim, Chaerin committed
35
});
36

37
38
39
router.put('/change/:id', function (req, res, next) {
  console.log('/change put req.body', req.params)
  User.findOne({ _id: req.params.id }, 'password', function (err, user) {
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
    if (err) return res.status(500).json({ error: err });
    bcrypt.compare(req.body.password, user.password, function (err, result) {
      if (err) {
        console.log(err)
        return res.status(500).json({ error: err });
      }
      if (result) {
        return res.status(404).json({ error: '새로운 비밀번호를 입력해주세요.' })
      }
    });

    user.password = req.body.password;
    user.save()
      .then((result) => {
        console.log(result);
        res.status(201).json(result);
      })
      .catch((err) => {
        console.error(err);
        next(err);
      });
  })
});
63

Kim, Chaerin's avatar
어헛    
Kim, Chaerin committed
64
module.exports = router;