userController.js 8.13 KB
Newer Older
1
import db from "../db/index";
2
import envs from "../../config/config";
3
import jwt from "jsonwebtoken";
4
import nodemailer from "nodemailer";
5
import resForm from "../resForm";
6
import routes from "../routes";
7

KangMin An's avatar
KangMin An committed
8
// 메일 전송 처리
9
const postMail = async (email, token) => {
10
  const transporter = nodemailer.createTransport({
11
    service: envs.api.nodemailer.service,
12
13
    auth: {
      type: "OAuth2",
14
15
16
17
      user: envs.api.nodemailer.user,
      clientId: envs.api.nodemailer.gmail_client_id,
      clientSecret: envs.api.nodemailer.gmail_client_secret,
      refreshToken: envs.api.nodemailer.gmail_refresh_token,
18
19
20
21
22
23
24
    },
    tls: {
      rejectUnauthorized: false,
    },
  });

  const mailOptions = {
25
    from: `EUE Auth Supply <${envs.api.nodemailer.user}>`,
26
27
    to: email,
    subject: "EUE 사용자 계정 확인용 메일.",
28
29
30
31
32
33
34
    html: `<a href="${envs.server.protocol}://${envs.server.host}:${
      envs.server.port
    }${routes.base + routes.confirm}?token=${token}">${
      envs.server.protocol
    }://${envs.server.host}:${envs.server.port}${
      routes.base + routes.confirm
    }?token=${token}</a>`,
35
36
37
38
39
40
41
42
43
44
45
  };

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

46
47
48
49
50
51
52
53
54
55
// 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
56
// Page for Development Test.
57
58
export const getEditProfile = (req, res) => {
  res.render("edit-profile", { pagename: "Edit Profile" });
KangMin An's avatar
KangMin An committed
59
60
61
};

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

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

72
  if (result.length !== 0) {
73
    res.json({ msg: resForm.msg.err, contents: { existing_user: true } });
74
  } else {
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    await db.User.create(
      { email: email, nick_name: nick_name },
      { logging: false }
    );

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

    if (isOAuth) {
      const payload = {
        email: email,
      };

      const accessT = jwt.sign(payload, envs.secretKey.access_token, {
        expiresIn: "14d",
        issuer: "eue.com",
        subject: "userInfo",
      });

      res
        .cookie("acs_token", accessT)
        .json({ msg: resForm.msg.ok, contents: { existing_user: false } });
    } else {
      res.json({ msg: resForm.msg.ok, contents: { existing_user: false } });
    }
103
104
105
  }
};

KangMin An's avatar
KangMin An committed
106
// 메일 확인용 토큰 발행 및 전송 처리
107
export const postLogin = async (req, res) => {
108
  const {
109
    body: { email, isOAuth },
110
111
  } = req;

112
  const result = await db.User.findAll({
113
114
115
116
    where: { email: email },
    logging: false,
  });

117
118
119
120
121
  if (result.length !== 0) {
    if (isOAuth) {
      const payload = {
        email: email,
      };
122

123
124
125
126
      const accessT = jwt.sign(payload, envs.secretKey.access_token, {
        expiresIn: "14d",
        issuer: "eue.com",
        subject: "userInfo",
127
      });
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160

      res
        .cookie("acs_token", accessT)
        .json({ msg: resForm.msg.ok, contents: { existing_user: true } });
    } else {
      try {
        // token 발행
        const mail_token = jwt.sign(
          {
            email: email,
          },
          envs.secretKey.mail,
          {
            expiresIn: 10 * 60,
            issuer: "eue.com",
            subject: "auth_checker",
          }
        );

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

        res.json({
          msg: resForm.msg.ok,
          contents: { existing_user: true, mail_sending: true },
        });
      } catch (err) {
        console.log(err);
        res.json({
          msg: resForm.msg.err,
          contents: { existing_user: true, mail_sending: false, error: err },
        });
      }
161
    }
162
  } else {
163
164
165
    res.json({
      msg: resForm.msg.err,
      contents: { existing_user: false, mail_sending: false },
166
    });
167
168
  }
};
169

170
171
// 로그아웃 요청 처리
export const getLogout = (req, res) => {
172
  res.clearCookie("acs_token").json({ msg: resForm.msg.ok, contents: {} });
173
174
};

KangMin An's avatar
KangMin An committed
175
// 메일로 보낸 토큰의 유효성 검사 및 access 토큰 발행 처리
176
export const getConfirm = async (req, res) => {
177
  const {
178
    query: { token },
179
180
  } = req;

181
  try {
182
    const decoded = jwt.verify(token, envs.secretKey.mail); // return payload.
183
184
185
186
187
188
189
190
191
192
193

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

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

194
    const accessT = jwt.sign(payload, envs.secretKey.access_token, {
195
196
197
198
199
      expiresIn: "14d",
      issuer: "eue.com",
      subject: "userInfo",
    });

200
201
    res
      .cookie("acs_token", accessT)
202
      .redirect(
203
        `${envs.client.protocol}://${envs.client.host}:${envs.client.port}/first-local-code`
204
      );
205
  } catch (err) {
206
    res.json({ msg: resForm.msg.err, contents: { error: err } });
207
  }
208
};
KangMin An's avatar
KangMin An committed
209

210
211
212
213
214
215
// 사용자 정보 요청 처리
export const getUserInfo = async (req, res) => {
  const {
    cookies: { acs_token },
  } = req;

216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
  try {
    const decoded = jwt.decode(acs_token);

    const result_user = await db.User.findAll({
      where: { email: decoded.email },
      logging: false,
    });
    let user = {
      email: result_user[0].email,
      nick_name: result_user[0].nick_name,
      using_aircon: result_user[0].using_aircon,
      created_at: result_user[0].created_at,
      loc_code: result_user[0].loc_code,
    };

    if (user.loc_code) {
      let loc_name = {};

      const result_emd = await db.Emd.findAll({
        where: {
          code_emd: user.loc_code,
        },
        logging: false,
      });
240

241
242
243
244
245
246
      const result_doe = await db.Doe.findAll({
        where: {
          code_doe: result_emd[0].code_doe,
        },
        logging: false,
      });
247

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
      const result_sgg = await db.Sgg.findAll({
        where: {
          code_sgg: result_emd[0].code_sgg,
        },
        logging: false,
      });

      loc_name.doe = result_doe[0].name_doe;
      loc_name.sgg = result_sgg[0].name_sgg;
      loc_name.emd = result_emd[0].name_emd;

      user.loc_name = loc_name;
    }
    res.json({ msg: resForm.msg.ok, contents: { user_info: [user] } });
  } catch (err) {
    console.log(err);
    res.json({ msg: resForm.msg.err, contents: { error: err } });
  }
266
267
268
};

// 사용자 정보 수정 요청 처리
269
export const postEditProfile = async (req, res) => {
270
271
  const {
    cookies: { acs_token },
272
    body: { nick_name, loc_code },
KangMin An's avatar
KangMin An committed
273
274
  } = req;

275
276
  try {
    const decoded = jwt.decode(acs_token);
KangMin An's avatar
KangMin An committed
277

278
279
280
281
282
    const result_preuser = await db.User.findAll({
      where: { email: decoded.email },
      logging: false,
    });
    const user = result_preuser[0];
KangMin An's avatar
KangMin An committed
283

284
285
    let new_nick_name = nick_name ? nick_name : user.nick_name;
    let new_loc_code = loc_code ? Number(loc_code) : Number(user.loc_code);
286

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
    await db.User.update(
      {
        nick_name: new_nick_name,
        loc_code: new_loc_code,
      },
      { where: { email: decoded.email } }
    );

    const result_after_user = await db.User.findAll({
      where: { email: decoded.email },
    });

    res.json({
      msg: resForm.msg.ok,
      contents: { user_info: result_after_user },
    });
  } catch (err) {
    console.log(err);
    res.json({ msg: resForm.msg.err, contents: { error: err } });
  }
KangMin An's avatar
KangMin An committed
307
};
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332

// 에어컨 사용 변경 요청 처리
export const getToggleAircon = async (req, res) => {
  const {
    cookies: { acs_token },
  } = req;

  try {
    const decoded = jwt.decode(acs_token);
    const result_preuser = await db.User.findAll({
      where: { email: decoded.email },
      logging: false,
    });

    await db.User.update(
      { using_aircon: !result_preuser[0].using_aircon },
      { where: { email: decoded.email } }
    );

    res.json({ msg: resForm.msg.ok, contents: {} });
  } catch (err) {
    console.log(err);
    res.json({ msg: resForm.msg.err, contents: { error: err } });
  }
};