auth.controller.js 1.23 KB
Newer Older
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
1
2
import User from "../models/User.js"
import bcrypt from "bcryptjs"
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
3
4
import jwt from "jsonwebtoken"
import config from "../config.js"
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
5
6
7
8

const login = async (req, res) => {
    const { email, password } = req.body //구조분해해서 하나씩
    console.log( email, password)
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
9
    try { 
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
10
11
12
13
14
        const user = await User.findOne({email}).select('+password')
        if (!user) {
            return res.status(404).send(`${email}이 없습니다`)
        }
        const passwordMatch = await bcrypt.compare(password, user.password)
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
15
        if (passwordMatch) { 
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
16
            const token = jwt.sign({userId: user._id}, config.jwtSecret,{
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
17
                expiresIn: '7d'
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
18
19
            })
            res.cookie('token', token, {
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
20
21
22
                maxAge: config.cookieMaxAge,
                httpOnly: true,
                secure: config.env === 'production'
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
23
24
25
26
27
28
            })
            res.json({userId: user._id})
        } else {
            res.status(401).send('비밀번호가 일치하지 않습니다')
        }
        
Lee SeoYeon's avatar
..    
Lee SeoYeon committed
29
    } catch (error) {
Lee SeoYeon's avatar
0111    
Lee SeoYeon committed
30
31
32
33
34
35
36
37
38
39
40
        console.log(error)
        res.status(500).send('로그인 에러')
    }
}

const logout = (req, res) => {
    res.clearCookie('token')
    res.send('Logout Successful')
}

export default { login, logout}