user.controller.js 9.76 KB
Newer Older
한규민's avatar
한규민 committed
1
2
import jwt from "jsonwebtoken";
import config from "../config/app.config.js";
한규민's avatar
한규민 committed
3
import { User, Role } from '../db/index.js';
Jiwon Yoon's avatar
Jiwon Yoon committed
4
<<<<<<< HEAD
한규민's avatar
한규민 committed
5
import fs from "fs";
한규민's avatar
한규민 committed
6
7
8
=======
<<<<<<< HEAD
>>>>>>> master
한규민's avatar
한규민 committed
9

한규민's avatar
한규민 committed
10
11
const getUser = async (req, res) => {
    try {
한규민's avatar
한규민 committed
12
        if (req.cookies.butterStudio) {
한규민's avatar
한규민 committed
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
=======
25
// import Twilio from "twilio";
Jiwon Yoon's avatar
Jiwon Yoon committed
26
>>>>>>> jiwon
한규민's avatar
한규민 committed
27

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

}

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

한규민's avatar
한규민 committed
86
const compareId = async (req, res) => {
한규민's avatar
한규민 committed
87
88
89
90
91
92
93
94
95
96
97
    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
98
99
100
    }
}

한규민's avatar
한규민 committed
101
const confirmMbnum = async (req, res) => {
102
103
    // const id = req.params.id;
    // const token = req.params.token;
한규민's avatar
한규민 committed
104

한규민's avatar
한규민 committed
105
106
107
108
109
110
    // const client = Twilio(id, token);
    // // console.log(client);
    // client.messages
    //     .create({
    //         to: '+8201086074580',
    //         from: '+14159428621',
한규민's avatar
한규민 committed
111
    //         body: '[config.cookieName] 인증번호[1234]를 입력해주세요',
한규민's avatar
한규민 committed
112
113
114
    //     })
    //     .then(message => console.log(message.sid))
    //     .catch(e => console.log(error));
한규민's avatar
한규민 committed
115
    // console.log("id = ", id, "token = ", token);
한규민's avatar
한규민 committed
116
    res.json(true);
한규민's avatar
한규민 committed
117
118
}

한규민's avatar
한규민 committed
119
const signup = async (req, res) => {
한규민's avatar
한규민 committed
120
    const { userId, userEmail, userNickName, userBirthday, userMbnum, userPassword } = req.body;
한규민's avatar
한규민 committed
121
122
    // 휴대폰 중복 확인
    try {
Jiwon Yoon's avatar
Jiwon Yoon committed
123
        const mbnum = await User.findOne({ where: { phoneNumber: userMbnum } });
한규민's avatar
한규민 committed
124
125
126
127
128
129
130
        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
131
            return res.status(422).send(`이미 있는 휴대폰번호입니다.`);
한규민's avatar
한규민 committed
132
133
134
135
136
137
138
139
140
141
142
143
        } else {
            const role = await Role.findOne({ where: { name: "member" } })
            const newUser = await User.create({
                userId: userId,
                email: userEmail,
                nickname: userNickName,
                birth: userBirthday,
                phoneNumber: userMbnum,
                password: userPassword,
                roleId: role.id
            });
            res.json(newUser);
한규민's avatar
한규민 committed
144
145
146
147
148
149
150
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("회원가입 에러. 나중에 다시 시도 해주세요");
    }
};

한규민's avatar
한규민 committed
151
const getMember = async (req, res) => {
한규민's avatar
한규민 committed
152
    try {
한규민's avatar
한규민 committed
153
154
155
        const token = req.cookies.butterStudio;
        const decoded = jwt.verify(token, config.jwtSecret);
        if (decoded.role === "member") {
한규민's avatar
한규민 committed
156
157
            const user = await User.findOne({ where: { id: decoded.id } });
            res.json({nickname : user.nickname, img : user.img});
한규민's avatar
한규민 committed
158
159
160
        } else {
            res.status(401).send("잘못된 접근입니다.");
        }
한규민's avatar
한규민 committed
161
    } catch (error) {
한규민's avatar
한규민 committed
162
163
164
165
166
        console.error("error : ", error.message);
        res.status(500).send("잘못된 접근입니다.");
    }
}

한규민's avatar
한규민 committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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) {
            const img = await User.findOne({ where: { id:decoded.id }, attributes : ["img"]});
            console.log("여기여기");
            fs.unlink( "upload"+`\\${img.img}`, function(data){ console.log(data);});

            const user = await User.update({
                img: image
            }, { where: { id: decoded.id } });
            if(user){
                const success = await User.findOne({ where: { id: decoded.id }, attributes: ["img"]});
                res.json(success)
            }else{
                throw new Error("프로필 등록 실패")
            }
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("프로필 에러");
    }
}

한규민's avatar
한규민 committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
213
214
    }
}
한규민's avatar
한규민 committed
215

Jiwon Yoon's avatar
Jiwon Yoon committed
216
<<<<<<< HEAD
한규민's avatar
한규민 committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
const overlap = async (decoded, dataType, data) => {
    try {
        let overlap = await User.findOne({ where: { id: decoded.id } });
        console.log("overlap : ", overlap, "overlap[dataType] :    ", overlap[dataType]);
        if (overlap[dataType] === data) {
            console.log("여기여기")
            return true
        } else {
            overlap = await User.findOne({ where: { id: decoded.id }, attributes: [dataType] });
            if (overlap) {
                return false
            } else {
                return true
            }
        }
    }catch(error){
        console.error(error.message);
    }
}

한규민's avatar
한규민 committed
237
238
239
=======
<<<<<<< HEAD
>>>>>>> master
한규민's avatar
한규민 committed
240
241
const modifyUser = async (req, res) => {
    try {
한규민's avatar
한규민 committed
242
243
244
        const token = req.cookies.butterStudio;
        const decoded = jwt.verify(token, config.jwtSecret);
        const { userEmail, userNickName, userMbnum, userPassword } = req.body;
한규민's avatar
한규민 committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
        const overlapEmail = await overlap(decoded, "email", userEmail);
        const overlapMbnum = await overlap(decoded, "phoneNumber", userMbnum);
        console.log("overlapEmail", overlapEmail, " overlapMbnum : ", overlapMbnum);

        if (overlapEmail && overlapMbnum) {
            const user = await User.update({
                email: userEmail,
                nickname: userNickName,
                phoneNumber: userMbnum,
                password: userPassword,
            }, { where: { id: decoded.id } });
            console.log("user22 :", user);
            res.json(user);
        } else if (!overlapEmail && overlapMbnum) {
            res.status(500).send("이미 있는 이메일입니다.");
        } else if (overlapEmail && !overlapMbnum) {
            res.status(500).send("이미 있는 이메일입니다.");
한규민's avatar
한규민 committed
262
        } else {
한규민's avatar
한규민 committed
263
            res.status(500).send("이미 있는 이메일, 핸드폰번호입니다.");
한규민's avatar
한규민 committed
264
265
266
267
268
269
        }
    } catch (error) {
        console.error(error.message);
        res.status(500).send("수정 에러. 나중에 다시 시도 해주세요");
    }
};
Jiwon Yoon's avatar
Jiwon Yoon committed
270
=======
271
272
273
274
275
276
277
278
279
280
281
282
283
const getUserInfo = async (req,res)=>{
    const {id} = req.body
    console.log(id)
    try {
        const userInfo = await User.findOne({
            where:{id:id},
            attributes:["userId","email","nickname","birth","phoneNumber"]
        })
        res.json(userInfo)
    } catch (error) {
        console.log(error)
    }
}
Jiwon Yoon's avatar
Jiwon Yoon committed
284
>>>>>>> jiwon
한규민's avatar
한규민 committed
285

한규민's avatar
한규민 committed
286
export default {
한규민's avatar
한규민 committed
287
    getUser,
한규민's avatar
한규민 committed
288
    login,
한규민's avatar
push    
한규민 committed
289
    logout,
한규민's avatar
한규민 committed
290
    compareId,
한규민's avatar
한규민 committed
291
292
    confirmMbnum,
    signup,
한규민's avatar
한규민 committed
293
<<<<<<< HEAD
한규민's avatar
한규민 committed
294
295
    getMember,
    uploadProfile,
한규민's avatar
한규민 committed
296
=======
한규민's avatar
한규민 committed
297
    getNickName,
Jiwon Yoon's avatar
Jiwon Yoon committed
298
<<<<<<< HEAD
한규민's avatar
한규민 committed
299
>>>>>>> master
한규민's avatar
한규민 committed
300
    comparePw,
한규민's avatar
한규민 committed
301
    modifyUser
Jiwon Yoon's avatar
Jiwon Yoon committed
302
=======
303
    getUserInfo
Jiwon Yoon's avatar
Jiwon Yoon committed
304
>>>>>>> jiwon
한규민's avatar
한규민 committed
305
}