userController.js 4.71 KB
Newer Older
1
import db from "../db/index";
2
import dotenv from "dotenv";
3
import jwt from "jsonwebtoken";
4
5
import nodemailer from "nodemailer";
import { serverMSG, statusCode } from "../serverinfo";
6
import routes from "../routes";
7
8
9

dotenv.config();

KangMin An's avatar
KangMin An committed
10
// 메일 전송 처리
11
const postMail = async (email, token) => {
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  const transporter = nodemailer.createTransport({
    service: process.env.NODEMAILER_SERVICE,
    auth: {
      type: "OAuth2",
      user: process.env.NODEMAILER_USER,
      clientId: process.env.NODEMAILER_GAMIL_CLIENT_ID,
      clientSecret: process.env.NODEMAILER_GMAIL_CLIENT_PASSWORD,
      refreshToken: process.env.NODEMAILER_GMAIL_REFRESH_TOKEN,
    },
    tls: {
      rejectUnauthorized: false,
    },
  });

  const mailOptions = {
    from: `EUE Auth Supply <${process.env.NODEMAILER_USER}>`,
    to: email,
    subject: "EUE 사용자 계정 확인용 메일.",
30
31
32
33
34
    html: `<a href="${process.env.PROTOCOL}://${process.env.HOST}:${
      process.env.PORT
    }${routes.base + routes.confirm}?token=${token}">${
      process.env.PROTOCOL
    }://${process.env.HOST}:${process.env.PORT}${
35
36
      routes.base + routes.confirm
    }?token=${token}</a>`,
37
38
39
40
41
42
43
44
45
46
47
  };

  try {
    const mailResult = await transporter.sendMail(mailOptions);
    console.log(`Mail sent - ID : ${mailResult.messageId}`);
  } catch (err) {
    console.log("Mail Sending Failuer.");
    console.log(err);
  }
};

48
49
50
51
52
53
54
55
56
57
// Page for Development Test.
export const getSignup = (req, res) => {
  res.render("signup", { pagename: "Sign Up" });
};

// Page for Development Test.
export const getLogin = (req, res) => {
  res.render("login", { pagename: "Log In" });
};

KangMin An's avatar
KangMin An committed
58
59
60
61
62
63
// Page for Development Test.
export const getSetLoccode = (req, res) => {
  res.render("setLoccode", { pagename: "Set Loccode" });
};

// 회원 가입 처리
64
65
export const postSignup = async (req, res) => {
  const {
66
    body: { email, nick_name },
67
68
  } = req;

69
  const result = await db.User.findAll({
70
71
72
73
    where: { email: email },
    logging: false,
  });

74
  if (result.length != 0) {
75
76
77
78
79
    res.status(statusCode.err).json({
      msg: serverMSG.server_err,
      content: "You are aleady registered",
    });
  } else {
80
    db.User.create({ email: email, nick_name: nick_name }, { logging: false });
81
    // 로그인 페이지로 넘겨주기.
82
    res.redirect("/api/login");
83
84
85
  }
};

KangMin An's avatar
KangMin An committed
86
// 메일 확인용 토큰 발행 및 전송 처리
87
export const postLogin = async (req, res) => {
88
89
90
91
  const {
    body: { email },
  } = req;

92
  const result = await db.User.findAll({
93
94
95
96
    where: { email: email },
    logging: false,
  });

97
  if (result.length != 0) {
98
    // token 발행
99
100
101
102
    const mail_token = jwt.sign(
      {
        email: email,
      },
103
      process.env.AUTH_MAIL_SECRETKEY,
104
105
106
      {
        expiresIn: 10 * 60,
        issuer: "eue.com",
107
        subject: "auth_checker",
108
109
110
      }
    );

111
    // 토큰이 포함된 로그인 링크 전송
112
113
    postMail(email, mail_token);

114
115
116
117
    res
      .status(statusCode.ok)
      .json({ msg: serverMSG.server_ok, content: "Send Mail Successfully." });
  } else {
118
119
120
121
    res.status(statusCode.err).json({
      msg: serverMSG.server_err,
      content: "You are not one of our user yet.",
    });
122
123
  }
};
124

KangMin An's avatar
KangMin An committed
125
// 메일로 보낸 토큰의 유효성 검사 및 access 토큰 발행 처리
126
export const getConfirm = async (req, res) => {
127
  const {
128
    query: { token },
129
130
  } = req;

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
  try {
    const decoded = jwt.verify(token, process.env.AUTH_MAIL_SECRETKEY); // return payload.

    const result = await db.User.findAll({
      where: { email: decoded.email },
      logging: false,
    });
    const user = result[0];

    const payload = {
      email: user.email,
      nick_name: user.nick_name,
      loc_code: user.loc_code,
    };

    const accessT = jwt.sign(payload, process.env.AUTH_ACCESS_SECRETKEY, {
      expiresIn: "14d",
      issuer: "eue.com",
      subject: "userInfo",
    });

KangMin An's avatar
KangMin An committed
152
    res.status(statusCode.ok).cookie("acs_token", accessT).redirect("/api");
153
154
155
156
157
  } catch (err) {
    res
      .status(statusCode.err)
      .json({ msg: serverMSG.server_err, content: `${err}` });
  }
158
};
KangMin An's avatar
KangMin An committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

// 사용자의 지역 코드 설정 처리
export const postSetLoccode = async (req, res) => {
  const {
    cookies: { acs_token },
    body: { loccode },
  } = req;

  const decoded = jwt.decode(acs_token);
  console.log(decoded);

  await db.User.update(
    { loccode: loccode },
    { where: { email: decoded.email } }
  );

  const payload = {
    email: decoded.email,
    nick_name: decoded.nick_name,
    loc_code: loccode,
  };

  const accessT = jwt.sign(payload, process.env.AUTH_ACCESS_SECRETKEY, {
    expiresIn: "14d",
    issuer: "eue.com",
    subject: "userInfo",
  });

  res
    .status(statusCode.ok)
    .cookie("acs_token", accessT)
    .json({ msg: serverMSG.server_ok, content: "Successfully Set Loccode" });
};