user.controller.js 2.63 KB
Newer Older
Choi Ga Young's avatar
Choi Ga Young committed
1
2
import jwt from "jsonwebtoken";
import { User } from '../db/index.js';
3
import config from "../config/app.config.js";
Choi Ga Young's avatar
Choi Ga Young committed
4

5
6
const getUser = async (req, res) => {
  try {
Kim, Subin's avatar
context    
Kim, Subin committed
7
8
    if (req.cookies[config.cookieName]) {
      const token = req.cookies[config.cookieName];
9
      const { id, role, name } = jwt.verify(token, config.jwtSecret);
Kim, Subin's avatar
context    
Kim, Subin committed
10
      return res.json({ id, role, name });
11
    } else {
Kim, Subin's avatar
context    
Kim, Subin committed
12
      throw new Error("유효기간이 만료되었습니다. 다시 로그인해주세요.")
13
14
    }
  } catch (error) {
Kim, Subin's avatar
context    
Kim, Subin committed
15
    return res.status(500).send(error.message || "사용자 정보 가져오는 중 에러 발생");
16
17
18
  }
}

Choi Ga Young's avatar
Choi Ga Young committed
19
20
21
22
23
24
25
26
27
28
29
30
const signup = async (req, res) => {
  console.log('server/signup req.body', req.body)
  const { userId, password, userName, userStudNum } = req.body;
  try {
    const findId = await User.findOne({ where: { userID: userId } });
    if (findId) {
      throw new Error("이미 있는 회원정보 입니다.");
    }
    await User.create({
      userID: userId,
      password: password,
      userName: userName,
31
      studNum: userStudNum,
32
      role: "user"
Choi Ga Young's avatar
Choi Ga Young committed
33
    });
Kim, Subin's avatar
context    
Kim, Subin committed
34
    return res.status(201).json("success")
Choi Ga Young's avatar
Choi Ga Young committed
35
36
  } catch (error) {
    console.log(error)
37
    return res.status(500).send(error.message || "회원가입 에러발생")
Choi Ga Young's avatar
Choi Ga Young committed
38
39
40
41
42
  }
}

const login = async (req, res) => {
  console.log('server/login req.body', req.body)
43
44
45
46
47
48
49
50
51
52
53
  const { userId, password } = req.body;
  try {
    const user = await User.scope("withPassword").findOne({ where: { userID: userId } });
    console.log('user확인', user)
    if (!user) {
      return res.status(404).send(`일치하는 정보가 없습니다.`);
    }
    const passwordMatch = await user.comparePassword(password);
    if (passwordMatch) {

      const signData = {
54
        id: user.id,
Kim, Subin's avatar
context    
Kim, Subin committed
55
        role: user.role,
56
57
        name: user.userName,
      };
58
59
60
61
62
63
64
65
66
67
68
69

      const token = jwt.sign(signData, config.jwtSecret, {
        expiresIn: config.jwtExpires,
      });

      res.cookie(config.cookieName, token, {
        maxAge: config.cookieMaxAge,
        path: "/",
        httpOnly: config.env === "production",
        secure: config.env === "production",
      });

70
71
      res.status(201).json(signData)
    } else {
72
73
74
75
76
77
78
      res.status(401).send("비밀번호가 일치하지 않습니다.")
    }

  } catch (error) {
    console.log(error)
    return res.status(500).send("로그인 에러발생")
  }
Choi Ga Young's avatar
Choi Ga Young committed
79
80
}

81
82
83
const logout = async (req, res) => {
  try {
    res.clearCookie(config.cookieName);
Kim, Subin's avatar
context    
Kim, Subin committed
84
    return res.json({
85
86
87
88
89
90
91
92
93
94
      id:"",
      role:"user",
      name:""
    })
  } catch (error) {
    console.log(error);
    return res.status(500).send("로그아웃 에러발생")
  }
}

Choi Ga Young's avatar
Choi Ga Young committed
95
export default {
96
  getUser,
Choi Ga Young's avatar
Choi Ga Young committed
97
  signup,
98
99
  login,
  logout
Choi Ga Young's avatar
Choi Ga Young committed
100
}