auth.controller.js 1.35 KB
Newer Older
이재연's avatar
이재연 committed
1
2
3
4
5
import User from '../schemas/User.js'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import config from '../config.js'

6
7
8
9
const login = async (req, res) => {
    const { id, password } = req.body
    console.log(id, password)
    try {
Jiwon Yoon's avatar
Jiwon Yoon committed
10
        const user = await User.findOne({ id }).select('password role name tel email')
11
        console.log('u=', user)
12
        if (!user) {
이재연's avatar
이재연 committed
13
            return res.status(404).send(`${id}가 존재하지 않습니다.`)
이재연's avatar
이재연 committed
14
        }
15
        const passwordMatch = await bcrypt.compare(password, user.password)
이재연's avatar
이재연 committed
16

17
18
19
        if (passwordMatch) {
            const token = jwt.sign({ userId: user._id }, config.jwtSecret, {
                expiresIn: '3d'
이재연's avatar
이재연 committed
20
            })
21
22
23
24
            res.cookie('token', token, {
                maxAge: config.cookieMaxAge,
                httpOnly: true,
                secure: config.env === 'production'
이재연's avatar
이재연 committed
25
            })
Jiwon Yoon's avatar
Jiwon Yoon committed
26
            res.json({ userId: user._id, role: user.role, name: user.name, tel: user.tel, email:user.email })
이재연's avatar
0115    
이재연 committed
27

28
        } else {
이재연's avatar
이재연 committed
29
            res.status(401).send('비밀번호가 일치하지 않습니다.')
이재연's avatar
이재연 committed
30
        }
31
    } catch (error) {
이재연's avatar
이재연 committed
32
        console.log(error)
이재연's avatar
이재연 committed
33
        res.status(500).send('로그인 실패. 다시 시도하세요.')
이재연's avatar
이재연 committed
34
35
36
    }
}

37
38
39
40
const logout = (req, res) => {
    res.clearCookie('token')
    res.send('로그아웃 되었습니다.')
}
이재연's avatar
이재연 committed
41

42
export default { login, logout }