user.controller.js 15.1 KB
Newer Older
한규민's avatar
한규민 committed
1
2
import jwt from "jsonwebtoken";
import config from "../config/app.config.js";
3
import { User, Role, ConfirmNum } from '../db/index.js';
한규민's avatar
한규민 committed
4
import fs from "fs";
한규민's avatar
한규민 committed
5
import CryptoJS from "crypto-js";
한규민's avatar
한규민 committed
6
import validator from "validator";
한규민's avatar
한규민 committed
7

한규민's avatar
한규민 committed
8
9
const getUser = async (req, res) => {
    try {
한규민's avatar
한규민 committed
10
        if (req.cookies.butterStudio) {
한규민's avatar
한규민 committed
11
12
13
14
15
16
17
18
19
20
21
22
            const token = req.cookies.butterStudio;
            const decoded = jwt.verify(token, config.jwtSecret);
            res.json(decoded);
        } else {
            res.json({ id: 0, role: "user" });
        }
    } catch (error) {
        console.error(error);
        return res.status(500).send("유저를 가져오지 못했습니다.");
    }
}

Jiwon Yoon's avatar
Jiwon Yoon committed
23
const login = async (req, res) => {
한규민's avatar
한규민 committed
24
25
26
27
28
29
30
    try {
        const { id, password } = req.body;
        //사용자 존재 확인
        const user = await User.scope("withPassword").findOne({ where: { userId: id } });
        if (!user) {
            return res.status(422).send(`사용자가 존재하지 않습니다`);
        }
한규민's avatar
한규민 committed
31
        // 2) 비밀번호 확인은 데이터베이스 프로토타입 메소드에서 처리(사용자가 입력한 비밀번호와 서버에 있는 비번 비교)
한규민's avatar
한규민 committed
32
33
34
        const passwordMatch = await user.comparePassword(password);
        if (passwordMatch) {
            // 3) 비밀번호가 맞으면 토큰 생성
한규민's avatar
push    
한규민 committed
35
            const userRole = await user.getRole();
한규민's avatar
한규민 committed
36
            const signData = {
한규민's avatar
한규민 committed
37
                id: user.id,
한규민's avatar
push    
한규민 committed
38
                role: userRole.name,
한규민's avatar
한규민 committed
39
40
41
42
43
44
45
46
47
48
49
50
51
            };
            const token = jwt.sign(signData, config.jwtSecret, {
                expiresIn: config.jwtExpires,
            });
            // 4) 토큰을 쿠키에 저장
            res.cookie(config.cookieName, token, {
                maxAge: config.cookieMaxAge,
                path: "/",
                httpOnly: config.env === "production",
                secure: config.env === "production",
            });
            // 5) 사용자 반환
            res.json({
한규민's avatar
한규민 committed
52
                id: user.id,
한규민's avatar
context    
한규민 committed
53
                role: userRole.name,
한규민's avatar
한규민 committed
54
55
56
57
58
59
60
61
62
63
64
65
            });
        } else {
            // 6) 비밀번호 불일치
            res.status(401).send("비밀번호가 일치하지 않습니다");
        }
    } catch (error) {
        console.error(error);
        return res.status(500).send("로그인 에러");
    }

}

Jiwon Yoon's avatar
Jiwon Yoon committed
66
67
const logout = async (req, res) => {
    try {
한규민's avatar
한규민 committed
68
        res.clearCookie(config.cookieName);
한규민's avatar
한규민 committed
69
70
71
72
        res.json({
            id: 0,
            role: "user",
        })
한규민's avatar
한규민 committed
73
        res.send('successfully cookie cleared.')
Jiwon Yoon's avatar
Jiwon Yoon committed
74
    } catch (error) {
한규민's avatar
context    
한규민 committed
75
76
        console.error(error);
        return res.status(500).send("로그인 에러");
한규민's avatar
한규민 committed
77
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
78
}
한규민's avatar
한규민 committed
79

한규민's avatar
한규민 committed
80
const compareId = async (req, res) => {
한규민's avatar
한규민 committed
81
82
83
    try {
        const id = req.params.userId;
        const userid = await User.findOne({ where: { userId: id } });
한규민's avatar
한규민 committed
84
        if (userid) {
한규민's avatar
한규민 committed
85
86
87
88
89
90
91
            return res.json(true);
        } else {
            return res.json(false);
        }
    } catch (error) {
        console.error(error);
        return res.status(500).send("아이디 중복 확인 에러");
한규민's avatar
한규민 committed
92
93
94
    }
}

한규민's avatar
한규민 committed
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// 휴대폰 인증
const NCP_serviceID = 'ncp:sms:kr:270376424445:butterstudio';
const NCP_accessKey = 'GQmVCT2ZFxnEaJOWbrQs';
const NCP_secretKey = 'XLQQ8sd9WxW40hNi0xNBTOG0T8ksRsr8c8sUIEvy';

const date = Date.now().toString();
const uri = NCP_serviceID;
const secretKey = NCP_secretKey;
const accessKey = NCP_accessKey;
const method = 'POST';
const space = " ";
const newLine = "\n";
const url = `https://sens.apigw.ntruss.com/sms/v2/services/${uri}/messages`;
const url2 = `/sms/v2/services/${uri}/messages`;
한규민's avatar
한규민 committed
109

한규민's avatar
한규민 committed
110
111
112
113
114
115
116
117
118
119
120
121
122
//시크릿 키를 암호화하는 작업
const hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secretKey);

hmac.update(method);
hmac.update(space);
hmac.update(url2);
hmac.update(newLine);
hmac.update(date);
hmac.update(newLine);
hmac.update(accessKey);

const hash = hmac.finalize();
const signature = hash.toString(CryptoJS.enc.Base64);
123
124


한규민's avatar
한규민 committed
125
126
127
128
129
// 인증번호 발송
const confirmMbnum = async (req, res) => {

    try {
        const phoneNumber = req.params.phone;
한규민's avatar
한규민 committed
130

한규민's avatar
한규민 committed
131
132
        //인증번호 생성
        const verifyCode = Math.floor(Math.random() * (999999 - 100000)) + 100000;
한규민's avatar
한규민 committed
133
134
        console.log("verifyCode : ", verifyCode);
        let today = new Date();
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        let time = String(today.getTime());
        // let result = await axios({
        //     method: method,
        //     json: true,
        //     url: url,
        //     headers: {
        //         'Content-Type': "application/json",
        //         'x-ncp-apigw-timestamp': date,
        //         'x-ncp-iam-access-key': accessKey,
        //         'x-ncp-apigw-signature-v2': signature,
        //     },
        //     data: {
        //         type: 'SMS',
        //         contentType: 'COMM',
        //         countryCode: '82',
        //         from: '01086074580',
        //         content: `[본인 확인] 인증번호 [${verifyCode}]를 입력해주세요.`,
        //         messages: [
        //             {
        //                 to: `${phoneNumber}`,
        //             },
        //         ],
        //     },
        // });
한규민's avatar
한규민 committed
159

160
161
        // const resultMs = result.data.messages;
        // console.log('resultMs', resultMs);
한규민's avatar
한규민 committed
162

163
        // console.log('response', res.data, res['data']);
한규민's avatar
한규민 committed
164
165
        const confirm = await ConfirmNum.findOne({ where: { phone: phoneNumber } });
        if (confirm) {
166
167
168
169
170
171
172
            await confirm.destroy();
            // 5분 유효시간 설정 
            await ConfirmNum.create({
                confirmNum: String(verifyCode),
                phone: phoneNumber,
                startTime: time,
            });
한규민's avatar
한규민 committed
173
        } else {
174
175
176
177
178
            await ConfirmNum.create({
                confirmNum: String(verifyCode),
                phone: phoneNumber,
                startTime: time,
            }
한규민's avatar
한규민 committed
179
            );
180
181
        }
        res.json({ startTime: time, isSuccess: true, code: 202, message: "본인인증 문자 발송 성공", result: res.data });
한규민's avatar
한규민 committed
182
183
184
185
186
187
188
189
    } catch (error) {
        console.log("error: ", error);
        if (error.res == undefined) {
            res.json({ isSuccess: true, code: 200, message: "본인인증 문자 발송 성공", result: res.data });
        }
        else res.json({ isSuccess: true, code: 204, message: "본인인증 문자 발송에 문제가 있습니다.", result: error.res });
    }
};
190

한규민's avatar
한규민 committed
191
192
193
//  인증번호 확인
const confirmNum = async (req, res) => {
    try {
한규민's avatar
한규민 committed
194
195
        const { userMbnum, number, startTime } = req.body;
        const confirm = await ConfirmNum.findOne({ where: { phone: userMbnum, startTime: startTime } });
196

한규민's avatar
한규민 committed
197
        let today = new Date();
198
199
200
        let time = today.getTime();
        const elapsedMSec = time - confirm.startTime;
        const elapsedMin = String(elapsedMSec / 1000 / 60);
한규민's avatar
한규민 committed
201
        if (elapsedMin <= 5) {
202
            if (number !== confirm.confirmNum) {
한규민's avatar
한규민 committed
203
                res.send("실패");
한규민's avatar
한규민 committed
204
            } else {
205
                await confirm.destroy();
한규민's avatar
한규민 committed
206
207
                res.send("성공");
            }
한규민's avatar
한규민 committed
208
        } else {
209
            res.send("재전송")
한규민's avatar
한규민 committed
210
211
212
213
214
215
        }
    } catch (error) {
        console.error("error : ", error.message);
        res.status(500).send("잘못된 접근입니다.");
    }
};
한규민's avatar
한규민 committed
216

한규민's avatar
한규민 committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
//유효성 검사
const validation = (errorMsg, data, minLength, maxLength, dataType) => {
    if (validator.isLength(data, minLength, maxLength)) {
        errorMsg[dataType] = false;
    } else {
        errorMsg[dataType] = true;
    }
    if (dataType === "userEmail") {
        if (validator.isEmail(data, minLength, maxLength)) {
            errorMsg[dataType] = false;
        } else {
            errorMsg[dataType] = true;
        }

    }
};

한규민's avatar
한규민 committed
234
const signup = async (req, res) => {
235
    const { userId, userName, userEmail, userNickName, userBirthday, userMbnum, userPassword } = req.body;
한규민's avatar
한규민 committed
236
    try {
한규민's avatar
한규민 committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
        let errorMsg = {
            errorId: false,
            errorName: false,
            errorEmail: false,
            errorBirthday: false,
            errorNickName: false,
            errorMbnum: false,
            errorPassword: false,
        };
        //유효성 검사
        validation(errorMsg, userId, 5, 10, "errorId");
        validation(errorMsg, userName, 1, 10, "errorName");
        validation(errorMsg, userEmail, 3, 20, "errorEmail");
        validation(errorMsg, userBirthday, 6, 6, "errorBirthday");
        validation(errorMsg, userNickName, 1, 10, "errorNickName");
        validation(errorMsg, userMbnum, 11, 11, "errorMbnum");
        validation(errorMsg, userPassword, 8, 11, "errorPassword");

        let valid = !(Object.values(errorMsg).some((element) => (element)));
한규민's avatar
한규민 committed
256

한규민's avatar
한규민 committed
257
258
259
260
        const mbnum = await User.findOne({ where: { phoneNumber: userMbnum } });
        const email = await User.findOne({ where: { email: userEmail } });
        if (!valid) {
            res.json(errorMsg);
한규민's avatar
한규민 committed
261
        } else {
한규민's avatar
한규민 committed
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
            if (mbnum && email) {
                return res.status(422).send(`이미 있는 이메일, 휴대폰번호입니다.`);
            } else if (!mbnum && email) {
                return res.status(422).send(`이미 있는 이메일입니다.`);
            } else if (mbnum && !email) {
                return res.status(422).send(`이미 있는 휴대폰번호입니다.`);
            } else {
                const role = await Role.findOne({ where: { name: "member" } })
                await User.create({
                    userId: userId,
                    name: userName,
                    email: userEmail,
                    nickname: userNickName,
                    birth: userBirthday,
                    phoneNumber: userMbnum,
                    password: userPassword,
                    img: "",
                    roleId: role.id
                });
                res.json("성공");
            }
한규민's avatar
한규민 committed
283
284
285
286
287
288
289
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("회원가입 에러. 나중에 다시 시도 해주세요");
    }
};

한규민's avatar
한규민 committed
290
const getMember = async (req, res) => {
한규민's avatar
한규민 committed
291
    try {
한규민's avatar
한규민 committed
292
293
294
        const token = req.cookies.butterStudio;
        const decoded = jwt.verify(token, config.jwtSecret);
        if (decoded.role === "member") {
한규민's avatar
한규민 committed
295
            const user = await User.findOne({ where: { id: decoded.id } });
한규민's avatar
한규민 committed
296
            res.json({ nickname: user.nickname, img: user.img });
한규민's avatar
한규민 committed
297
298
299
        } else {
            res.status(401).send("잘못된 접근입니다.");
        }
한규민's avatar
한규민 committed
300
    } catch (error) {
한규민's avatar
한규민 committed
301
302
303
304
305
        console.error("error : ", error.message);
        res.status(500).send("잘못된 접근입니다.");
    }
}

한규민's avatar
한규민 committed
306
307
308
309
310
311
312
const uploadProfile = async (req, res) => {
    try {
        const image = req.file.filename;
        const token = req.cookies.butterStudio;
        const decoded = jwt.verify(token, config.jwtSecret);

        if (decoded) {
한규민's avatar
한규민 committed
313
314
            const img = await User.findOne({ where: { id: decoded.id }, attributes: ["img"] });
            fs.unlink("upload" + `\\${img.img}`, function (data) { console.log(data); });
한규민's avatar
한규민 committed
315
316
317
318

            const user = await User.update({
                img: image
            }, { where: { id: decoded.id } });
한규민's avatar
한규민 committed
319
320
            if (user) {
                const success = await User.findOne({ where: { id: decoded.id }, attributes: ["img"] });
한규민's avatar
한규민 committed
321
                res.json(success)
한규민's avatar
한규민 committed
322
            } else {
한규민's avatar
한규민 committed
323
324
325
326
327
328
329
330
331
                throw new Error("프로필 등록 실패")
            }
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("프로필 에러");
    }
}

한규민's avatar
한규민 committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
const comparePw = async (req, res) => {
    try {
        //쿠키 안 토큰에서 id추출
        const token = req.cookies.butterStudio;
        const decoded = jwt.verify(token, config.jwtSecret);
        //해당 id의 행 추출
        const user = await User.scope("withPassword").findOne({ where: { id: decoded.id } });
        //입력한 비번과 해당 행 비번을 비교
        const passwordMatch = await user.comparePassword(req.params.pw);
        //클라이언트로 동일여부를 전송
        if (passwordMatch) {
            return res.json(true)
        } else {
            return res.json(false)
        }
    } catch (error) {
        console.error("error : ", error.message);
        res.status(500).send("인증 에러");
한규민's avatar
한규민 committed
350
351
    }
}
한규민's avatar
한규민 committed
352

한규민's avatar
한규민 committed
353
354
355
const overlap = async (decoded, dataType, data) => {
    try {
        let overlap = await User.findOne({ where: { id: decoded.id } });
한규민's avatar
한규민 committed
356
        // 변경할 데이터가 자기자신이면 true
한규민's avatar
한규민 committed
357
358
359
        if (overlap[dataType] === data) {
            return true
        } else {
한규민's avatar
한규민 committed
360
            // 그렇지 않으면 다른 데이터들 중에서 중복되는지 검사
한규민's avatar
한규민 committed
361
362
            let overlap2 = await User.findOne({ attributes: [dataType] });
            if (overlap2[dataType] === data) {
한규민's avatar
한규민 committed
363
364
365
366
367
                return false
            } else {
                return true
            }
        }
한규민's avatar
한규민 committed
368
    } catch (error) {
한규민's avatar
한규민 committed
369
370
371
372
        console.error(error.message);
    }
}

한규민's avatar
한규민 committed
373
374
const modifyUser = async (req, res) => {
    try {
한규민's avatar
한규민 committed
375
376
        const token = req.cookies.butterStudio;
        const decoded = jwt.verify(token, config.jwtSecret);
377
        const { userName, userEmail, userNickName, userMbnum, userPassword } = req.body;
한규민's avatar
한규민 committed
378

한규민's avatar
한규민 committed
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
        let errorMsg = {
            errorName: false,
            errorEmail: false,
            errorNickName: false,
            errorMbnum: false,
            errorPassword: false,
        };

        //유효성 검사
        validation(errorMsg, userName, 1, 10, "errorName");
        validation(errorMsg, userEmail, 3, 20, "errorEmail");
        validation(errorMsg, userNickName, 1, 10, "errorNickName");
        validation(errorMsg, userMbnum, 11, 11, "errorMbnum");
        validation(errorMsg, userPassword, 8, 11, "errorPassword");

        let valid = !(Object.values(errorMsg).some((element) => (element)));
한규민's avatar
한규민 committed
395
396
        const overlapEmail = await overlap(decoded, "email", userEmail);
        const overlapMbnum = await overlap(decoded, "phoneNumber", userMbnum);
한규민's avatar
한규민 committed
397
398
        if (!valid) {
            res.json(errorMsg);
한규민's avatar
한규민 committed
399
        } else {
한규민's avatar
한규민 committed
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
            if (overlapEmail && overlapMbnum) {
                await User.update({
                    name: userName,
                    email: userEmail,
                    nickname: userNickName,
                    phoneNumber: userMbnum,
                    password: userPassword,
                }, { where: { id: decoded.id }, individualHooks: true });
                res.json("성공");
            } else if (!overlapEmail && overlapMbnum) {
                res.status(500).send("이미 있는 이메일입니다.");
            } else if (overlapEmail && !overlapMbnum) {
                res.status(500).send("이미 있는 핸드폰번호입니다.");
            } else {
                res.status(500).send("이미 있는 이메일, 핸드폰번호입니다.");
            }
한규민's avatar
한규민 committed
416
417
418
419
420
421
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("수정 에러. 나중에 다시 시도 해주세요");
    }
};
422

한규민's avatar
한규민 committed
423
424
const getUserInfo = async (req, res) => {
    const { id } = req.body
425
426
427
    console.log(id)
    try {
        const userInfo = await User.findOne({
한규민's avatar
한규민 committed
428
429
            where: { id: id },
            attributes: ["userId", "email", "nickname", "birth", "phoneNumber"]
430
431
432
433
434
435
        })
        res.json(userInfo)
    } catch (error) {
        console.log(error)
    }
}
한규민's avatar
한규민 committed
436

한규민's avatar
한규민 committed
437
export default {
한규민's avatar
한규민 committed
438
    getUser,
한규민's avatar
한규민 committed
439
    login,
한규민's avatar
push    
한규민 committed
440
    logout,
한규민's avatar
한규민 committed
441
    compareId,
한규민's avatar
한규민 committed
442
    confirmMbnum,
한규민's avatar
한규민 committed
443
    confirmNum,
한규민's avatar
한규민 committed
444
    signup,
한규민's avatar
한규민 committed
445
446
    getMember,
    uploadProfile,
한규민's avatar
한규민 committed
447
    getUser,
한규민's avatar
한규민 committed
448
    comparePw,
한규민's avatar
한규민 committed
449
    modifyUser,
450
    getUserInfo
한규민's avatar
한규민 committed
451
}