auth.controller.js 1.92 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
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

const login = async (req, res) => {
    const { email, password } = req.body //구조분해해서 하나씩
    console.log( email, password)
    try {             //적어도 3개 맥시멈 10개 가 아니면 
        // 1) 사용자 확인
        const user = await User.findOne({email}).select('+password')
        // 2) 이메일 사용자가 없으면 에러 반환
        if (!user) {
            return res.status(404).send(`${email}이 없습니다`)
        }
        // 3) 비밀번호 일치 확인
        const passwordMatch = await bcrypt.compare(password, user.password)
        // 4) 비밀번호가 맞으면 토큰 생성 후 쿠키에 저장
        if (passwordMatch) {                             //비밀스럽게 한다 노출되면 안된다 문자열
            const token = jwt.sign({userId: user._id}, config.jwtSecret,{
                expiresIn: '7d' //만기날짜 
            })
            // 쿠키의 이름, 쿠키의 value
            res.cookie('token', token, {
                maxAge: config.cookieMaxAge, //쿠키 얼마동안 살아있을지 생성일이 지나면 자동으로 사라짐
                httpOnly: true, //client쪽에서 자바스크립트에서 쿠키 접근 불가
                secure: config.env === 'production' //true가되면 https로만 접근가능
            })
            res.json({userId: user._id})
            // 5) 비밀번호가 틀리면 에러 반환
        } else {
            res.status(401).send('비밀번호가 일치하지 않습니다')
        }
        
    } catch (error) { //다른 과정에서 에러가 나면 실행 
        console.log(error)
        res.status(500).send('로그인 에러')
    }
}

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

export default { login, logout}