user.controller.js 13.4 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
6
7
import CryptoJS from "crypto-js";
import axios from "axios";

한규민'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
13
14
15
16
17
18
19
20
21
22
23
            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
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
            };
            const token = jwt.sign(signData, config.jwtSecret, {
                expiresIn: config.jwtExpires,
            });
한규민's avatar
한규민 committed
44
            console.log(token);
한규민's avatar
한규민 committed
45
46
47
48
49
50
51
52
53
            // 4) 토큰을 쿠키에 저장
            res.cookie(config.cookieName, token, {
                maxAge: config.cookieMaxAge,
                path: "/",
                httpOnly: config.env === "production",
                secure: config.env === "production",
            });
            // 5) 사용자 반환
            res.json({
한규민's avatar
한규민 committed
54
                id: user.id,
한규민's avatar
context    
한규민 committed
55
                role: userRole.name,
한규민's avatar
한규민 committed
56
57
58
59
60
61
62
63
64
65
66
67
            });
        } else {
            // 6) 비밀번호 불일치
            res.status(401).send("비밀번호가 일치하지 않습니다");
        }
    } catch (error) {
        console.error(error);
        return res.status(500).send("로그인 에러");
    }

}

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

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

한규민's avatar
한규민 committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// 휴대폰 인증
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
111

한규민's avatar
한규민 committed
112
113
114
115
116
117
118
119
120
121
122
123
124
//시크릿 키를 암호화하는 작업
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);
125
126


한규민's avatar
한규민 committed
127
128
129
130
131
132
133
134
135
136
// 인증번호 발송
const confirmMbnum = async (req, res) => {

    try {
        const phoneNumber = req.params.phone;
        console.log(phoneNumber);
    
        //인증번호 생성
        const verifyCode = Math.floor(Math.random() * (999999 - 100000)) + 100000;
        console.log("verifyCode : ",verifyCode);
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        let today = new Date();   
        let time = String(today.getTime());
        console.log("time : ", time);
        // 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
163

164
165
        // const resultMs = result.data.messages;
        // console.log('resultMs', resultMs);
한규민's avatar
한규민 committed
166

167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
        // console.log('response', res.data, res['data']);
        const confirm = await ConfirmNum.findOne({ where: { phone: phoneNumber} });
        console.log(confirm);
        if(confirm){
            await confirm.destroy();
            // 5분 유효시간 설정 
            await ConfirmNum.create({
                confirmNum: String(verifyCode),
                phone: phoneNumber,
                startTime: time,
            });
        }else{
            await ConfirmNum.create({
                confirmNum: String(verifyCode),
                phone: phoneNumber,
                startTime: time,
            }
        );
        }
        res.json({ startTime: time, isSuccess: true, code: 202, message: "본인인증 문자 발송 성공", result: res.data });
한규민's avatar
한규민 committed
187
188
189
190
191
192
193
194
    } 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 });
    }
};
195

한규민's avatar
한규민 committed
196
197
198
//  인증번호 확인
const confirmNum = async (req, res) => {
    try {
199
200
201
202
203
204
205
206
207
208
209
210
211
        const {userMbnum, number, startTime} = req.body;
        console.log(userMbnum, number, startTime);
        const confirm = await ConfirmNum.findOne({ where: { phone: userMbnum, startTime: startTime} });
        console.log(confirm);

        let today = new Date();   
        let time = today.getTime();
        console.log("time2 :", time);
        const elapsedMSec = time - confirm.startTime;
        const elapsedMin = String(elapsedMSec / 1000 / 60);
        console.log("elapsedMin : ", elapsedMin);
        if(elapsedMin <= 5 ){
            if (number !== confirm.confirmNum) {
한규민's avatar
한규민 committed
212
213
                res.send("실패");
            }else {
214
                await confirm.destroy();
한규민's avatar
한규민 committed
215
216
                res.send("성공");
            }
217
218
        }else{
            res.send("재전송")
한규민's avatar
한규민 committed
219
220
221
222
223
224
        }
    } catch (error) {
        console.error("error : ", error.message);
        res.status(500).send("잘못된 접근입니다.");
    }
};
한규민's avatar
한규민 committed
225

한규민's avatar
한규민 committed
226
const signup = async (req, res) => {
227
    const { userId, userName, userEmail, userNickName, userBirthday, userMbnum, userPassword } = req.body;
한규민's avatar
한규민 committed
228
    try {
229
        const mbnum = await User.findOne({ where: { phoneNumber: userMbnum }});
한규민's avatar
한규민 committed
230
231
232
233
234
235
236
        const email = await User.findOne({ where: { email: userEmail } });

        if (mbnum && email) {
            return res.status(422).send(`이미 있는 이메일, 휴대폰번호입니다.`);
        } else if (!mbnum && email) {
            return res.status(422).send(`이미 있는 이메일입니다.`);
        } else if (mbnum && !email) {
한규민's avatar
한규민 committed
237
            return res.status(422).send(`이미 있는 휴대폰번호입니다.`);
한규민's avatar
한규민 committed
238
239
240
241
        } else {
            const role = await Role.findOne({ where: { name: "member" } })
            const newUser = await User.create({
                userId: userId,
242
                name: userName,
한규민's avatar
한규민 committed
243
244
245
246
247
                email: userEmail,
                nickname: userNickName,
                birth: userBirthday,
                phoneNumber: userMbnum,
                password: userPassword,
한규민's avatar
한규민 committed
248
                img:"",
한규민's avatar
한규민 committed
249
250
251
                roleId: role.id
            });
            res.json(newUser);
한규민's avatar
한규민 committed
252
253
254
255
256
257
258
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("회원가입 에러. 나중에 다시 시도 해주세요");
    }
};

한규민's avatar
한규민 committed
259
const getMember = async (req, res) => {
한규민's avatar
한규민 committed
260
    try {
한규민's avatar
한규민 committed
261
262
263
        const token = req.cookies.butterStudio;
        const decoded = jwt.verify(token, config.jwtSecret);
        if (decoded.role === "member") {
한규민's avatar
한규민 committed
264
            const user = await User.findOne({ where: { id: decoded.id } });
한규민's avatar
한규민 committed
265
            res.json({ nickname: user.nickname, img: user.img });
한규민's avatar
한규민 committed
266
267
268
        } else {
            res.status(401).send("잘못된 접근입니다.");
        }
한규민's avatar
한규민 committed
269
    } catch (error) {
한규민's avatar
한규민 committed
270
271
272
273
274
        console.error("error : ", error.message);
        res.status(500).send("잘못된 접근입니다.");
    }
}

한규민's avatar
한규민 committed
275
276
277
278
279
280
281
282
const uploadProfile = async (req, res) => {
    try {
        const image = req.file.filename;
        console.log(req.file);
        const token = req.cookies.butterStudio;
        const decoded = jwt.verify(token, config.jwtSecret);

        if (decoded) {
한규민's avatar
한규민 committed
283
284
            const img = await User.findOne({ where: { id: decoded.id }, attributes: ["img"] });
            fs.unlink("upload" + `\\${img.img}`, function (data) { console.log(data); });
한규민's avatar
한규민 committed
285
286
287
288

            const user = await User.update({
                img: image
            }, { where: { id: decoded.id } });
한규민's avatar
한규민 committed
289
290
            if (user) {
                const success = await User.findOne({ where: { id: decoded.id }, attributes: ["img"] });
한규민's avatar
한규민 committed
291
                res.json(success)
한규민's avatar
한규민 committed
292
            } else {
한규민's avatar
한규민 committed
293
294
295
296
297
298
299
300
301
                throw new Error("프로필 등록 실패")
            }
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("프로필 에러");
    }
}

한규민's avatar
한규민 committed
302
303
304
305
306
307
308
309
310
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);
한규민's avatar
한규민 committed
311
        console.log("passwordMatch : ", passwordMatch);
한규민's avatar
한규민 committed
312
313
314
315
316
317
318
319
320
        //클라이언트로 동일여부를 전송
        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
321
322
    }
}
한규민's avatar
한규민 committed
323

한규민's avatar
한규민 committed
324
325
326
const overlap = async (decoded, dataType, data) => {
    try {
        let overlap = await User.findOne({ where: { id: decoded.id } });
한규민's avatar
한규민 committed
327
        console.log("기존 데이터 : ", overlap, "변경할 데이터 :    ", data);
한규민's avatar
한규민 committed
328
329
330
        if (overlap[dataType] === data) {
            return true
        } else {
한규민's avatar
한규민 committed
331
332
333
            let overlap2 = await User.findOne({ attributes: [dataType] });
            console.log(overlap2)
            if (overlap2[dataType] === data) {
한규민's avatar
한규민 committed
334
335
336
337
338
                return false
            } else {
                return true
            }
        }
한규민's avatar
한규민 committed
339
    } catch (error) {
한규민's avatar
한규민 committed
340
341
342
343
        console.error(error.message);
    }
}

한규민's avatar
한규민 committed
344
345
const modifyUser = async (req, res) => {
    try {
한규민's avatar
한규민 committed
346
347
        const token = req.cookies.butterStudio;
        const decoded = jwt.verify(token, config.jwtSecret);
348
        const { userName, userEmail, userNickName, userMbnum, userPassword } = req.body;
한규민's avatar
한규민 committed
349

한규민's avatar
한규민 committed
350
351
352
353
354
        const overlapEmail = await overlap(decoded, "email", userEmail);
        const overlapMbnum = await overlap(decoded, "phoneNumber", userMbnum);

        if (overlapEmail && overlapMbnum) {
            const user = await User.update({
355
                name: userName,
한규민's avatar
한규민 committed
356
357
358
359
                email: userEmail,
                nickname: userNickName,
                phoneNumber: userMbnum,
                password: userPassword,
360
            }, { where: { id: decoded.id }, individualHooks: true });
한규민's avatar
한규민 committed
361
362
363
364
365
            console.log("user22 :", user);
            res.json(user);
        } else if (!overlapEmail && overlapMbnum) {
            res.status(500).send("이미 있는 이메일입니다.");
        } else if (overlapEmail && !overlapMbnum) {
한규민's avatar
한규민 committed
366
            res.status(500).send("이미 있는 핸드폰번호입니다.");
한규민's avatar
한규민 committed
367
        } else {
한규민's avatar
한규민 committed
368
            res.status(500).send("이미 있는 이메일, 핸드폰번호입니다.");
한규민's avatar
한규민 committed
369
370
371
372
373
374
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("수정 에러. 나중에 다시 시도 해주세요");
    }
};
375

한규민's avatar
한규민 committed
376
377
const getUserInfo = async (req, res) => {
    const { id } = req.body
378
379
380
    console.log(id)
    try {
        const userInfo = await User.findOne({
한규민's avatar
한규민 committed
381
382
            where: { id: id },
            attributes: ["userId", "email", "nickname", "birth", "phoneNumber"]
383
384
385
386
387
388
        })
        res.json(userInfo)
    } catch (error) {
        console.log(error)
    }
}
한규민's avatar
한규민 committed
389

한규민's avatar
한규민 committed
390
export default {
한규민's avatar
한규민 committed
391
    getUser,
한규민's avatar
한규민 committed
392
    login,
한규민's avatar
push    
한규민 committed
393
    logout,
한규민's avatar
한규민 committed
394
    compareId,
한규민's avatar
한규민 committed
395
    confirmMbnum,
한규민's avatar
한규민 committed
396
    confirmNum,
한규민's avatar
한규민 committed
397
    signup,
한규민's avatar
한규민 committed
398
399
    getMember,
    uploadProfile,
한규민's avatar
한규민 committed
400
    getUser,
한규민's avatar
한규민 committed
401
    comparePw,
한규민's avatar
한규민 committed
402
    modifyUser,
403
    getUserInfo
한규민's avatar
한규민 committed
404
}