user.controller.js 17.8 KB
Newer Older
한규민's avatar
한규민 committed
1
2
import jwt from "jsonwebtoken";
import config from "../config/app.config.js";
Jiwon Yoon's avatar
Jiwon Yoon committed
3
import { User, Role, Guest, 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
// 현재 유저 상태 결정
한규민's avatar
한규민 committed
9
10
const getUser = async (req, res) => {
    try {
한규민's avatar
한규민 committed
11
        if (req.cookies.butterStudio) {
한규민's avatar
한규민 committed
12
            const token = req.cookies.butterStudio;
한규민's avatar
한규민 committed
13
14
            const { id, role } = jwt.verify(token, config.jwtSecret);
            res.json( { id, role } );
한규민's avatar
한규민 committed
15
16
17
18
19
20
21
22
        } else {
            res.json({ id: 0, role: "user" });
        }
    } catch (error) {
        console.error(error);
        return res.status(500).send("유저를 가져오지 못했습니다.");
    }
}
한규민's avatar
한규민 committed
23
// 로그인
Jiwon Yoon's avatar
Jiwon Yoon committed
24
const login = async (req, res) => {
한규민's avatar
한규민 committed
25
26
27
28
29
30
31
    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
32
        // 2) 비밀번호 확인은 데이터베이스 프로토타입 메소드에서 처리(사용자가 입력한 비밀번호와 서버에 있는 비번 비교)
한규민's avatar
한규민 committed
33
34
35
        const passwordMatch = await user.comparePassword(password);
        if (passwordMatch) {
            // 3) 비밀번호가 맞으면 토큰 생성
한규민's avatar
push    
한규민 committed
36
            const userRole = await user.getRole();
한규민's avatar
한규민 committed
37
            const signData = {
한규민's avatar
한규민 committed
38
                id: user.id,
한규민's avatar
push    
한규민 committed
39
                role: userRole.name,
한규민's avatar
한규민 committed
40
41
42
43
44
45
46
47
48
49
50
51
52
            };
            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
53
                id: user.id,
한규민's avatar
context    
한규민 committed
54
                role: userRole.name,
한규민's avatar
한규민 committed
55
56
57
58
59
60
61
62
63
64
            });
        } else {
            // 6) 비밀번호 불일치
            res.status(401).send("비밀번호가 일치하지 않습니다");
        }
    } catch (error) {
        console.error(error);
        return res.status(500).send("로그인 에러");
    }
}
한규민's avatar
한규민 committed
65
// 로그아웃
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
74
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
103
104
105
106
107
108
109
110
111
    } catch (error) {
        console.error(error);
        return res.status(500).send("로그인 에러");
    }
}

//비회원 예매확인 로그인
const guestLogin = async (req, res) => {
    try {
        const {guestName, guestEmail, guestBirthday, guestMbnum, guestPassword} = req.body;
        const guest = await Guest.findOne({ where : {
            name: guestName,
            email: guestEmail,
            birth: guestBirthday,
            phoneNumber: guestMbnum,
            password: guestPassword,
        }});
        if (!guest) {
            return res.status(422).send(`사용자가 존재하지 않습니다`);
        }else{
            const guestRole = await guest.getRole();
            const signData = {
                id: guest.id,
                role: guestRole.name
            };
            //토큰 생성
            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",
            });
            // 사용자 반환
            res.json(signData);
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
112
    } catch (error) {
한규민's avatar
context    
한규민 committed
113
114
        console.error(error);
        return res.status(500).send("로그인 에러");
한규민's avatar
한규민 committed
115
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
116
};
한규민's avatar
한규민 committed
117

한규민's avatar
한규민 committed
118
119
120
// 인증번호 발송
const confirmMbnum = async (req, res) => {
    try {
한규민's avatar
한규민 committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
        
        // 휴대폰 인증
        const NCP_serviceID = process.env.NCP_serviceID;
        const NCP_accessKey = process.env.NCP_accessKey;
        const NCP_secretKey = process.env.NCP_secretKey;
        
        const date = Date.now().toString();
        const uri = NCP_serviceID;
        const accessKey = NCP_accessKey;
        const secretKey = NCP_secretKey;
        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`;
        
        //시크릿 키를 암호화하는 작업
        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);
        
한규민's avatar
한규민 committed
151
152
        const phoneNumber = req.params.phone;
        console.log(phoneNumber);
153

한규민's avatar
한규민 committed
154
155
        //인증번호 생성
        const verifyCode = Math.floor(Math.random() * (999999 - 100000)) + 100000;
한규민's avatar
한규민 committed
156
157
        console.log("verifyCode : ", verifyCode);
        let today = new Date();
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
        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
182

183
184
        // const resultMs = result.data.messages;
        // console.log('resultMs', resultMs);
한규민's avatar
한규민 committed
185

186
        // console.log('response', res.data, res['data']);
한규민's avatar
한규민 committed
187
188
        const confirm = await ConfirmNum.findOne({ where: { phone: phoneNumber } });
        if (confirm) {
189
190
191
192
193
194
195
            await confirm.destroy();
            // 5분 유효시간 설정 
            await ConfirmNum.create({
                confirmNum: String(verifyCode),
                phone: phoneNumber,
                startTime: time,
            });
한규민's avatar
한규민 committed
196
        } else {
197
198
199
200
201
            await ConfirmNum.create({
                confirmNum: String(verifyCode),
                phone: phoneNumber,
                startTime: time,
            }
한규민's avatar
한규민 committed
202
            );
203
204
        }
        res.json({ startTime: time, isSuccess: true, code: 202, message: "본인인증 문자 발송 성공", result: res.data });
한규민's avatar
한규민 committed
205
206
207
208
209
210
211
212
    } 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 });
    }
};
213

한규민's avatar
한규민 committed
214
215
216
//  인증번호 확인
const confirmNum = async (req, res) => {
    try {
한규민's avatar
한규민 committed
217
218
        const { userMbnum, number, startTime } = req.body;
        const confirm = await ConfirmNum.findOne({ where: { phone: userMbnum, startTime: startTime } });
219

한규민's avatar
한규민 committed
220
        let today = new Date();
221
222
223
        let time = today.getTime();
        const elapsedMSec = time - confirm.startTime;
        const elapsedMin = String(elapsedMSec / 1000 / 60);
한규민's avatar
한규민 committed
224
        if (elapsedMin <= 5) {
225
            if (number !== confirm.confirmNum) {
한규민's avatar
한규민 committed
226
                res.send("실패");
한규민's avatar
한규민 committed
227
            } else {
228
                await confirm.destroy();
한규민's avatar
한규민 committed
229
230
                res.send("성공");
            }
한규민's avatar
한규민 committed
231
        } else {
232
            res.send("재전송")
한규민's avatar
한규민 committed
233
234
235
236
237
238
        }
    } catch (error) {
        console.error("error : ", error.message);
        res.status(500).send("잘못된 접근입니다.");
    }
};
한규민's avatar
한규민 committed
239

한규민's avatar
한규민 committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
//유효성 검사
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
256
// 회원정보
한규민's avatar
한규민 committed
257
const signup = async (req, res) => {
258
    const { userId, userName, userEmail, userNickName, userBirthday, userMbnum, userPassword } = req.body;
한규민's avatar
한규민 committed
259
    try {
한규민's avatar
한규민 committed
260
261
262
263
264
265
266
267
268
        let errorMsg = {
            errorId: false,
            errorName: false,
            errorEmail: false,
            errorBirthday: false,
            errorNickName: false,
            errorMbnum: false,
            errorPassword: false,
        };
한규민's avatar
한규민 committed
269

한규민's avatar
한규민 committed
270
271
272
273
274
275
276
277
278
279
        //유효성 검사
        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
280
281
        // db에서 데이터 중복검사
        const id = await User.findOne({ where: { userId: userId } });
한규민's avatar
한규민 committed
282
283
284
285
        const mbnum = await User.findOne({ where: { phoneNumber: userMbnum } });
        const email = await User.findOne({ where: { email: userEmail } });
        if (!valid) {
            res.json(errorMsg);
한규민's avatar
한규민 committed
286
        } else {
한규민's avatar
한규민 committed
287
288
289
290
291
292
293
            if (id) {
                return res.status(401).send(`이미 있는 아이디입니다.`);
            } else if (email) {
                return res.status(401).send(`이미 있는 이메일입니다.`);
            } else if (mbnum) {
                return res.status(401).send(`이미 있는 휴대폰번호입니다.`);
            } else{
한규민's avatar
한규민 committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
                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
308
309
310
311
312
313
314
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("회원가입 에러. 나중에 다시 시도 해주세요");
    }
};

한규민's avatar
한규민 committed
315
const getMember = async (req, res) => {
한규민's avatar
한규민 committed
316
    try {
한규민's avatar
한규민 committed
317
        const token = req.cookies.butterStudio;
한규민's avatar
한규민 committed
318
319
320
        const { id, role } = jwt.verify(token, config.jwtSecret);
        if ( role === "member") {
            const user = await User.findOne({ where: { id: id } });
한규민's avatar
한규민 committed
321
            res.json({ nickname: user.nickname, img: user.img });
한규민's avatar
한규민 committed
322
        } else {
한규민's avatar
한규민 committed
323
            res.status(500).send("잘못된 접근입니다.");
한규민's avatar
한규민 committed
324
        }
한규민's avatar
한규민 committed
325
    } catch (error) {
한규민's avatar
한규민 committed
326
327
328
329
        console.error("error : ", error.message);
        res.status(500).send("잘못된 접근입니다.");
    }
}
한규민's avatar
한규민 committed
330
// 프로필 변경
한규민's avatar
한규민 committed
331
332
333
334
const uploadProfile = async (req, res) => {
    try {
        const image = req.file.filename;
        const token = req.cookies.butterStudio;
한규민's avatar
한규민 committed
335
        const { id } = jwt.verify(token, config.jwtSecret);
한규민's avatar
한규민 committed
336

한규민's avatar
한규민 committed
337
338
        if (id) {
            const img = await User.findOne({ where: { id: id }, attributes: ["img"] });
한규민's avatar
한규민 committed
339
            fs.unlink("upload" + `\\${img.img}`, function (data) { console.log(data); });
한규민's avatar
한규민 committed
340
341
342

            const user = await User.update({
                img: image
한규민's avatar
한규민 committed
343
            }, { where: { id: id } });
한규민's avatar
한규민 committed
344
            if (user) {
한규민's avatar
한규민 committed
345
                const success = await User.findOne({ where: { id: id }, attributes: ["img"] });
한규민's avatar
한규민 committed
346
                res.json(success)
한규민's avatar
한규민 committed
347
            } else {
한규민's avatar
한규민 committed
348
349
350
351
352
353
354
355
                throw new Error("프로필 등록 실패")
            }
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("프로필 에러");
    }
}
한규민's avatar
한규민 committed
356
// 기본 비밀번호인지 확인
한규민's avatar
한규민 committed
357
358
359
360
const comparePw = async (req, res) => {
    try {
        //쿠키 안 토큰에서 id추출
        const token = req.cookies.butterStudio;
한규민's avatar
한규민 committed
361
        const { id } = jwt.verify(token, config.jwtSecret);
한규민's avatar
한규민 committed
362
        //해당 id의 행 추출
한규민's avatar
한규민 committed
363
        const user = await User.scope("withPassword").findOne({ where: { id: id } });
한규민's avatar
한규민 committed
364
365
366
367
368
369
370
371
372
373
374
        //입력한 비번과 해당 행 비번을 비교
        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
375
376
    }
}
한규민's avatar
한규민 committed
377
// 회원정보 수정할 때 쓰는 함수
한규민's avatar
한규민 committed
378
const overlap = async ( id , dataType, data) => {
한규민's avatar
한규민 committed
379
    try {
한규민's avatar
한규민 committed
380
        let overlap = await User.findOne({ where: { id: id } });
한규민's avatar
한규민 committed
381
        // 변경할 데이터가 자기자신이면 true
한규민's avatar
한규민 committed
382
383
384
        if (overlap[dataType] === data) {
            return true
        } else {
한규민's avatar
한규민 committed
385
            // 그렇지 않으면 다른 데이터들 중에서 중복되는지 검사
한규민's avatar
한규민 committed
386
387
            let overlap2 = await User.findOne({ attributes: [dataType] });
            if (overlap2[dataType] === data) {
한규민's avatar
한규민 committed
388
389
390
391
392
                return false
            } else {
                return true
            }
        }
한규민's avatar
한규민 committed
393
    } catch (error) {
한규민's avatar
한규민 committed
394
395
396
        console.error(error.message);
    }
}
한규민's avatar
한규민 committed
397
// 회원정보 수정
한규민's avatar
한규민 committed
398
399
const modifyUser = async (req, res) => {
    try {
한규민's avatar
한규민 committed
400
        const token = req.cookies.butterStudio;
한규민's avatar
한규민 committed
401
        const { id } = jwt.verify(token, config.jwtSecret);
402
        const { userName, userEmail, userNickName, userMbnum, userPassword } = req.body;
한규민's avatar
한규민 committed
403

한규민's avatar
한규민 committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
        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
420
421
        const overlapEmail = await overlap( id , "email", userEmail);
        const overlapMbnum = await overlap( id , "phoneNumber", userMbnum);
한규민's avatar
한규민 committed
422
423
        if (!valid) {
            res.json(errorMsg);
한규민's avatar
한규민 committed
424
        } else {
한규민's avatar
한규민 committed
425
426
427
428
429
430
431
            if (overlapEmail && overlapMbnum) {
                await User.update({
                    name: userName,
                    email: userEmail,
                    nickname: userNickName,
                    phoneNumber: userMbnum,
                    password: userPassword,
한규민's avatar
한규민 committed
432
                }, { where: { id:  id }, individualHooks: true });
한규민's avatar
한규민 committed
433
434
435
436
437
438
439
440
                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
441
442
443
444
445
446
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("수정 에러. 나중에 다시 시도 해주세요");
    }
};
447

한규민's avatar
한규민 committed
448
449
const getUserInfo = async (req, res) => {
    const { id } = req.body
Jiwon Yoon's avatar
Jiwon Yoon committed
450
    // console.log(id)
451
452
    try {
        const userInfo = await User.findOne({
한규민's avatar
한규민 committed
453
            where: { id: id },
454
            attributes: ["id", "userId", "email", "nickname", "birth", "phoneNumber"]
455
        })
Jiwon Yoon's avatar
Jiwon Yoon committed
456
        // console.log(userInfo)
457
458
        res.json(userInfo)
    } catch (error) {
Jiwon Yoon's avatar
Jiwon Yoon committed
459
460
461
462
463
464
        res.status(500).send("회원정보 불러오기 실패");
    }
}

const saveGuestInfo = async (req, res) => {
    try {
Jiwon Yoon's avatar
Jiwon Yoon committed
465
        const { name, email, birth, phoneNumber, password } = req.body
Jiwon Yoon's avatar
Jiwon Yoon committed
466
467
468
469
470
471
        const newGuest = await Guest.create({
            name: name,
            email: email,
            birth: birth,
            phoneNumber: phoneNumber,
            password: password,
Jiwon Yoon's avatar
Jiwon Yoon committed
472
            roleId:1
Jiwon Yoon's avatar
Jiwon Yoon committed
473
        });
474
        res.clearCookie(config.cookieName);
Jiwon Yoon's avatar
Jiwon Yoon committed
475
        const token = jwt.sign({id: newGuest.id, role: "guest"}, config.jwtSecret, {
476
477
478
479
480
481
482
483
            expiresIn: config.jwtExpires,
        });
        res.cookie(config.cookieName,token , {
            maxAge: config.cookieMaxAge,
            path: "/",
            httpOnly: config.env === "production",
            secure: config.env === "production",
        })
Jiwon Yoon's avatar
Jiwon Yoon committed
484
        res.json(newGuest);
485
    } catch (error) {
Jiwon Yoon's avatar
Jiwon Yoon committed
486
        res.status(500).send("비회원정보 등록 실패");
487
488
    }
}
한규민's avatar
한규민 committed
489

490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
const getGuestInfo = async (req,res) => {
    const {guestId} = req.params
    // console.log(req.body)
    try {
        const guestInfo = await Guest.findOne({
            where: {
                id:guestId
            }
        })
        // console.log("guestInfo====", guestInfo)
        res.json(guestInfo)
    } catch (error) {
        res.status(500).send("비회원정보 불러오기 실패");
    }
}
한규민's avatar
한규민 committed
505
export default {
한규민's avatar
한규민 committed
506
    getUser,
한규민's avatar
한규민 committed
507
    login,
한규민's avatar
push    
한규민 committed
508
    logout,
한규민's avatar
한규민 committed
509
    guestLogin,
한규민's avatar
한규민 committed
510
    confirmMbnum,
한규민's avatar
한규민 committed
511
    confirmNum,
한규민's avatar
한규민 committed
512
    signup,
한규민's avatar
한규민 committed
513
    comparePw,
한규민's avatar
한규민 committed
514
    modifyUser,
Jiwon Yoon's avatar
Jiwon Yoon committed
515
516
517
    saveGuestInfo,
    getMember,
    uploadProfile,
518
519
    getUserInfo,
    getGuestInfo
한규민's avatar
한규민 committed
520
}