user.controller.js 16.6 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 {
Jiwon Yoon's avatar
Jiwon Yoon committed
11
        if (req.cookies.butterStudio) {
한규민's avatar
한규민 committed
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("유저를 가져오지 못했습니다.");
    }
}
한규민'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
        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
81
82
// 인증번호 발송
const confirmMbnum = async (req, res) => {
    try {
한규민's avatar
한규민 committed
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
112
        
        // 휴대폰 인증
        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
113
114
        const phoneNumber = req.params.phone;
        console.log(phoneNumber);
115

한규민's avatar
한규민 committed
116
117
        //인증번호 생성
        const verifyCode = Math.floor(Math.random() * (999999 - 100000)) + 100000;
한규민's avatar
한규민 committed
118
119
        console.log("verifyCode : ", verifyCode);
        let today = new Date();
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
        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
144

145
146
        // const resultMs = result.data.messages;
        // console.log('resultMs', resultMs);
한규민's avatar
한규민 committed
147

148
        // console.log('response', res.data, res['data']);
한규민's avatar
한규민 committed
149
150
        const confirm = await ConfirmNum.findOne({ where: { phone: phoneNumber } });
        if (confirm) {
151
152
153
154
155
156
157
            await confirm.destroy();
            // 5분 유효시간 설정 
            await ConfirmNum.create({
                confirmNum: String(verifyCode),
                phone: phoneNumber,
                startTime: time,
            });
한규민's avatar
한규민 committed
158
        } else {
159
160
161
162
163
            await ConfirmNum.create({
                confirmNum: String(verifyCode),
                phone: phoneNumber,
                startTime: time,
            }
한규민's avatar
한규민 committed
164
            );
165
166
        }
        res.json({ startTime: time, isSuccess: true, code: 202, message: "본인인증 문자 발송 성공", result: res.data });
한규민's avatar
한규민 committed
167
168
169
170
171
172
173
174
    } 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 });
    }
};
175

한규민's avatar
한규민 committed
176
177
178
//  인증번호 확인
const confirmNum = async (req, res) => {
    try {
한규민's avatar
한규민 committed
179
180
        const { userMbnum, number, startTime } = req.body;
        const confirm = await ConfirmNum.findOne({ where: { phone: userMbnum, startTime: startTime } });
181

한규민's avatar
한규민 committed
182
        let today = new Date();
183
184
185
        let time = today.getTime();
        const elapsedMSec = time - confirm.startTime;
        const elapsedMin = String(elapsedMSec / 1000 / 60);
한규민's avatar
한규민 committed
186
        if (elapsedMin <= 5) {
187
            if (number !== confirm.confirmNum) {
한규민's avatar
한규민 committed
188
                res.send("실패");
한규민's avatar
한규민 committed
189
            } else {
190
                await confirm.destroy();
한규민's avatar
한규민 committed
191
192
                res.send("성공");
            }
한규민's avatar
한규민 committed
193
        } else {
194
            res.send("재전송")
한규민's avatar
한규민 committed
195
196
197
198
199
200
        }
    } catch (error) {
        console.error("error : ", error.message);
        res.status(500).send("잘못된 접근입니다.");
    }
};
한규민's avatar
한규민 committed
201

한규민's avatar
한규민 committed
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
//유효성 검사
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
218
// 회원정보
한규민's avatar
한규민 committed
219
const signup = async (req, res) => {
220
    const { userId, userName, userEmail, userNickName, userBirthday, userMbnum, userPassword } = req.body;
한규민's avatar
한규민 committed
221
    try {
한규민's avatar
한규민 committed
222
223
224
225
226
227
228
229
230
        let errorMsg = {
            errorId: false,
            errorName: false,
            errorEmail: false,
            errorBirthday: false,
            errorNickName: false,
            errorMbnum: false,
            errorPassword: false,
        };
한규민's avatar
한규민 committed
231

한규민's avatar
한규민 committed
232
233
234
235
236
237
238
239
240
241
        //유효성 검사
        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
242
243
        // db에서 데이터 중복검사
        const id = await User.findOne({ where: { userId: userId } });
한규민's avatar
한규민 committed
244
        const mbnum = await User.findOne({ where: { phoneNumber: userMbnum } });
한규민's avatar
한규민 committed
245
        const email = await User.findOne({ where: { email: userEmail } });
한규민's avatar
한규민 committed
246
247
        if (!valid) {
            res.json(errorMsg);
한규민's avatar
한규민 committed
248
        } else {
한규민's avatar
한규민 committed
249
250
251
252
253
254
255
            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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
                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
270
271
272
273
274
275
276
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("회원가입 에러. 나중에 다시 시도 해주세요");
    }
};

한규민's avatar
한규민 committed
277
const getMember = async (req, res) => {
한규민's avatar
한규민 committed
278
    try {
한규민's avatar
한규민 committed
279
280
281
        const token = req.cookies.butterStudio;
        const decoded = jwt.verify(token, config.jwtSecret);
        if (decoded.role === "member") {
한규민's avatar
한규민 committed
282
            const user = await User.findOne({ where: { id: decoded.id } });
한규민's avatar
한규민 committed
283
            res.json({ nickname: user.nickname, img: user.img });
한규민's avatar
한규민 committed
284
        } else {
한규민's avatar
한규민 committed
285
            res.status(500).send("잘못된 접근입니다.");
한규민's avatar
한규민 committed
286
        }
한규민's avatar
한규민 committed
287
    } catch (error) {
한규민's avatar
한규민 committed
288
289
290
291
        console.error("error : ", error.message);
        res.status(500).send("잘못된 접근입니다.");
    }
}
한규민's avatar
한규민 committed
292
// 프로필 변경
한규민's avatar
한규민 committed
293
294
295
296
297
298
299
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
300
301
            const img = await User.findOne({ where: { id: decoded.id }, attributes: ["img"] });
            fs.unlink("upload" + `\\${img.img}`, function (data) { console.log(data); });
한규민's avatar
한규민 committed
302
303
304
305

            const user = await User.update({
                img: image
            }, { where: { id: decoded.id } });
한규민's avatar
한규민 committed
306
307
            if (user) {
                const success = await User.findOne({ where: { id: decoded.id }, attributes: ["img"] });
한규민's avatar
한규민 committed
308
                res.json(success)
한규민's avatar
한규민 committed
309
            } else {
한규민's avatar
한규민 committed
310
311
312
313
314
315
316
317
                throw new Error("프로필 등록 실패")
            }
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("프로필 에러");
    }
}
한규민's avatar
한규민 committed
318
// 기본 비밀번호인지 확인
한규민's avatar
한규민 committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
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
337
338
    }
}
한규민's avatar
한규민 committed
339
// 회원정보 수정할 때 쓰는 함수
한규민's avatar
한규민 committed
340
341
342
const overlap = async (decoded, dataType, data) => {
    try {
        let overlap = await User.findOne({ where: { id: decoded.id } });
한규민's avatar
한규민 committed
343
        // 변경할 데이터가 자기자신이면 true
한규민's avatar
한규민 committed
344
345
346
        if (overlap[dataType] === data) {
            return true
        } else {
한규민's avatar
한규민 committed
347
            // 그렇지 않으면 다른 데이터들 중에서 중복되는지 검사
한규민's avatar
한규민 committed
348
349
            let overlap2 = await User.findOne({ attributes: [dataType] });
            if (overlap2[dataType] === data) {
한규민's avatar
한규민 committed
350
351
352
353
354
                return false
            } else {
                return true
            }
        }
한규민's avatar
한규민 committed
355
    } catch (error) {
한규민's avatar
한규민 committed
356
357
358
        console.error(error.message);
    }
}
한규민's avatar
한규민 committed
359
// 회원정보 수정
한규민's avatar
한규민 committed
360
361
const modifyUser = async (req, res) => {
    try {
한규민's avatar
한규민 committed
362
363
        const token = req.cookies.butterStudio;
        const decoded = jwt.verify(token, config.jwtSecret);
364
        const { userName, userEmail, userNickName, userMbnum, userPassword } = req.body;
Jiwon Yoon's avatar
Jiwon Yoon committed
365

한규민's avatar
한규민 committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
        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
382
383
        const overlapEmail = await overlap(decoded, "email", userEmail);
        const overlapMbnum = await overlap(decoded, "phoneNumber", userMbnum);
한규민's avatar
한규민 committed
384
385
        if (!valid) {
            res.json(errorMsg);
한규민's avatar
한규민 committed
386
        } else {
한규민's avatar
한규민 committed
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
            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
403
404
405
406
407
408
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("수정 에러. 나중에 다시 시도 해주세요");
    }
};
409

Jiwon Yoon's avatar
Jiwon Yoon committed
410
411
const getUserInfo = async (req, res) => {
    const { id } = req.body
Jiwon Yoon's avatar
Jiwon Yoon committed
412
    // console.log(id)
413
414
    try {
        const userInfo = await User.findOne({
Jiwon Yoon's avatar
Jiwon Yoon committed
415
            where: { id: id },
416
            attributes: ["id", "userId", "email", "nickname", "birth", "phoneNumber"]
417
        })
Jiwon Yoon's avatar
Jiwon Yoon committed
418
        // console.log(userInfo)
419
        res.json(userInfo)
Jiwon Yoon's avatar
Jiwon Yoon committed
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
    } catch (error) {
        res.status(500).send("회원정보 불러오기 실패");
    }
}

const saveGuestInfo = async (req, res) => {
    const { name, email, birth, phoneNumber, password } = req.body
    try {
        const newGuest = await Guest.create({
            name: name,
            email: email,
            birth: birth,
            phoneNumber: phoneNumber,
            password: password,
        });
435
436
437
438
439
440
441
442
443
444
445
        // console.log(newGuest)
        res.clearCookie(config.cookieName);
        const token = jwt.sign({id: newGuest.id, role: "user"}, config.jwtSecret, {
            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
446
        res.json(newGuest);
447
    } catch (error) {
Jiwon Yoon's avatar
Jiwon Yoon committed
448
        res.status(500).send("비회원정보 등록 실패");
449
450
    }
}
한규민's avatar
한규민 committed
451

452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
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
467
export default {
한규민's avatar
한규민 committed
468
    getUser,
한규민's avatar
한규민 committed
469
    login,
한규민's avatar
push    
한규민 committed
470
    logout,
한규민's avatar
한규민 committed
471
    confirmMbnum,
한규민's avatar
한규민 committed
472
    confirmNum,
한규민's avatar
한규민 committed
473
    signup,
한규민's avatar
한규민 committed
474
    comparePw,
Jiwon Yoon's avatar
Jiwon Yoon committed
475
    modifyUser,
Jiwon Yoon's avatar
Jiwon Yoon committed
476
477
478
    saveGuestInfo,
    getMember,
    uploadProfile,
479
480
    getUserInfo,
    getGuestInfo
한규민's avatar
한규민 committed
481
}