auth.controller.js 2.26 KB
Newer Older
우지원's avatar
01_06    
우지원 committed
1
2
3
4
import User from "../models/User.js"
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import config from "../config.js"
5
//server부분에는 꼭 js붙여주기!!
우지원's avatar
01_06    
우지원 committed
6
7
8
9
10
11
12
13
14
15

//sign validation해야됨
const login = async (req, res) => {
    const { email, password } = req.body
    //req.body를 구조분해하여 각각 보이게함 -> 모든정보들이 한줄에 보임
    console.log(email, password)

    try {
        // 1) 사용자 확인
        const user = await User.findOne({ email }).select('+password')
16
        
우지원's avatar
01_06    
우지원 committed
17
18
        // 2) 이메일 사용자가 없으면 에러 반환
        if (!user) {
19
            return res.status(404).send(`${email}을 사용하는 사용자가 없습니다`)
우지원's avatar
01_06    
우지원 committed
20
21
22
23
24
25
26
27
        }

        // 3) 비밀번호 일치 확인
        const passwordMatch = await bcrypt.compare(password, user.password)

        // 4) 비밀번호가 맞으면 토큰 생성 후 쿠키에 저장
        if (passwordMatch) {
            //토큰 생성
28
29
30
31
            const token = jwt.sign({ userId: user._id }, config.jwtSecret, {expiresIn: '7d'})
            //jwtSecret : 노출되면 안됨. 문자열
            //expiresIn: '7d' -> 만기날짜 : 만든 7일후 만기

우지원's avatar
01_06    
우지원 committed
32
33
34
35
36
37
38
            //쿠키에 저장
            //res : client로 넘어가는 객체 cookie('이름', value)
            res.cookie('token', token, {
                maxAge: config.cookieMaxAge,
                //생성일로부터 어느정도까지 살아있을 것인가
                httpOnly: true,
                //client에서 javascript로 접근할 수 없음
39
                secure: config.env === 'production',
우지원's avatar
01_06    
우지원 committed
40
41
                //secure가 true이면 http로 접근하면 cookie가 들어가지 않음.
            })
42
43
            console.log('res.send.user', {user})
            res.send({user})
44

우지원's avatar
01_06    
우지원 committed
45
46
47
48
49
50
51
52
        } else {
            // 5) 비밀번호가 틀리면 에러 반환
            res.status(401).send('비밀번호가 일치하지 않습니다')
        }

    } catch (error) {
        //알수없는 모든 에러발생시 처리
        console.log(error)
우지원's avatar
우지원 committed
53
        res.status(500).send('로그인 에러가 발생하였습니다')
우지원's avatar
01_06    
우지원 committed
54
55
56
57
58
59
    }

}

const logout = (req, res) => {
    res.clearCookie('token')
우지원's avatar
우지원 committed
60
    res.send('로그아웃 되었습니다')
우지원's avatar
01_06    
우지원 committed
61
62
63
64
}

export default { login, logout }
// {} : 객체로 return함