login.js 2.24 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 jwt = require('jsonwebtoken');
5
const user = require('../schemas/user');
CHAERIN KIM's avatar
CHAERIN KIM committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

const router = express.Router();

router.get('/', function (req, res, next) {
    console.log('/login get request', req.body)
    User.find({})
        .then((signups) => {
            res.json(signups);
        })
        .catch((err) => {
            console.error(err);
            next(err);
        });
});

router.post('/', function (req, res, next) {
    console.log('/login post request', req.body)
CHAERIN KIM's avatar
CHAERIN KIM committed
23
    User.findOne({ id: req.body.id }, 'id password name', function (err, users) {
CHAERIN KIM's avatar
CHAERIN KIM committed
24
25
26
        if (err) return res.status(500).json({ error: err });

        if (!users) {
27
            return res.status(404).json({ error: '해당 학번이 존재하지 않습니다.' });
CHAERIN KIM's avatar
CHAERIN KIM committed
28
29
30
31
32
33
34
35
36
37
        }

        bcrypt.compare(req.body.password, users.password, function (err, result) {
            if (err) {
                console.log(err)
                return res.status(500).json({ error: err });
            }

            if (result) {
                const token = jwt.sign({
38
                    id: users.id,
CHAERIN KIM's avatar
CHAERIN KIM committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
                }, process.env.JWT_SECRET, {
                    expiresIn: '1m',
                });
                return res.status(201).json({
                    token,
                    users,
                });
            }
            res.status(404).json({ error: '비밀번호를 다시 입력해주세요.' });
        });

    })
});

53
54
55
56
57
router.post('/find', function (req, res, next) {
    console.log('/find post request', req.body)
    User.findOne({ id: req.body.id }, 'id question answer', function (err, users) {
        if (err) return res.status(500).json({ error: err });

58
59
        if (!users) return res.status(404).json({ error: '해당 학번이 존재하지 않습니다.' });
        
60
61
62
63
64
65
66
67
68
        if (users.question === req.body.question) {
            if (users.answer === req.body.answer) {
                return res.status(201).json({users});
            }
            return res.status(404).json({ error: '답변이 일치하지 않습니다.'});
        }
        return res.status(404).json({error: '질문을 다시 선택해주세요.'});
    })
});
CHAERIN KIM's avatar
CHAERIN KIM committed
69
module.exports = router;