-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
587 lines (535 loc) · 22.7 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
112
113
114
115
116
117
118
119
120
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
const express = require("express");
const adminRouter = require("./routes/admin");
const reviewsRouter = require("./routes/reviews");
const communityRouter = require("./routes/community");
const mypageRouter = require("./routes/mypage");
const methodOverride = require("method-override");
const http = require("http");
const crypto = require("crypto");
const expressSession = require("express-session");
const ObjectId = require('mongodb').ObjectId;
const request = require("request-promise-native");
const cors = require('cors');
//model
const Users = require("./models/users");
const Hospitals = require("./models/hospitals");
const Reports = require("./models/reports");
const app = express();
const port = process.env.PORT || 3001;
app.use(express.urlencoded({ extended: false })); // enable to use req.body.(input field)
app.use(expressSession({
secret: "secretKey",
resave: true,
saveUninitialized: true
}));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// views engine (convert ejs code to HTML)
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.use(methodOverride('_method'));
app.engine("html", require("ejs").renderFile);
// other routes
app.use("/admin", adminRouter);
app.use("/reviews", reviewsRouter);
app.use("/community", communityRouter);
app.use("/mypage", mypageRouter);
const { swaggerUi, specs } = require("./swagger/swagger");
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(specs));
app.use(cors());
// routes
/**
* @swagger
* paths:
* /newapi:
* get:
* tags: [ 검색 ]
* summary: "Get main page"
* description: 주소명 검색 페이지
* responses:
* "200":
* description: A successful response
* "400":
* description: Not Found
*/
app.get("/newapi", async (req, res) => {
const inputAddr = req.query.inputAddr;
const inputType = req.query.inputType;
const inputFilter = req.query.inputFilter;
const addrFilter = req.query.addrFilter;
const search_type = req.query.search_type;
if (typeof inputAddr == "undefined" || typeof inputType == "undefined" || typeof inputFilter == "undefined") {
if (req.session.user) {
res.send({ results: "", user_id: req.session.user['id'], text: "유저긴 한데 결과 없음" });
} else if (req.session.admin) {
res.send({ results: "", admin_id: req.session.admin['id'], text: "관리자긴한데 결과 없음" });
} else {
res.send({ results: "", text: "아무것도 없음" });
}
} else {
let searchAddr;
if (addrFilter === "lo") {
if (inputAddr.includes("서울")) {
let listAddr = inputAddr.split(" ");
let road = listAddr[2].substr(0, listAddr[2].indexOf("로") + 1);
searchAddr = `${listAddr[0]}특별시 ${listAddr[1]} ${road}`;
} else if (inputAddr.includes("인천") || inputAddr.includes("부산") || inputAddr.includes("울산") || inputAddr.includes("대구") || inputAddr.includes("광주") || inputAddr.includes("대전")) {
let listAddr = inputAddr.split(" ");
searchAddr = `${listAddr[0]}광역시 ${listAddr[1]} ${listAddr[2]}`;
} else {
let listAddr = inputAddr.split(" ");
let road = listAddr[3].substr(0, listAddr[3].indexOf("로") + 1);
searchAddr = `${listAddr[0]}도 ${listAddr[1]} ${listAddr[2]} ${road}`;
}
} else if (addrFilter === "gu") {
if (inputAddr.includes("서울")) {
let listAddr = inputAddr.split(" ");
let gu = listAddr[1].substr(0, listAddr[1].indexOf("구") + 1);
searchAddr = `${listAddr[0]}특별시 ${gu}`;
} else if (inputAddr.includes("인천") || inputAddr.includes("부산") || inputAddr.includes("울산") || inputAddr.includes("대구") || inputAddr.includes("광주") || inputAddr.includes("대전")) {
let listAddr = inputAddr.split(" ");
searchAddr = `${listAddr[0]}광역시 ${listAddr[1]}`;
} else {
let listAddr = inputAddr.split(" ");
let gu = listAddr[2].substr(0, listAddr[2].indexOf("구") + 1);
searchAddr = `${listAddr[0]}도 ${listAddr[1]} ${gu}`;
}
}
let conditions;
if (inputFilter == "all") {
if (inputType == "외과") {
conditions = {
$and : [
{name : {$regex : "외과"}},
{name : {$not : {$regex : "정형"}}},
{name : {$not : {$regex : "치과"}}}
],
addr: {$regex: searchAddr}
}
} else {
conditions = {
name: {$regex: inputType},
addr: {$regex: searchAddr}
}
}
}
else if (inputFilter == "infant") {
if (inputType == "외과") {
conditions = {
addr: {$regex: searchAddr},
$and : [
{name : {$regex : "외과"}},
{name : {$not : {$regex : "정형"}}},
{name : {$not : {$regex : "치과"}}},
{name: {$regex: "소아"}}
]
}
} else {
conditions = {
$and : [
{name : {$regex : inputType}},
{name : {$regex : "소아"}}
],
addr: {$regex: searchAddr}
}
}
}
let results = await Hospitals.find(conditions);
// Send index.ejs data
if (results.length > 0) {
if (req.session.user) {
res.send({ results: results, user_id: req.session.user['id'], text: "결과, 관리자"});
} else if (req.session.admin) {
res.send({ results: results, admin_id: req.session.admin['id'], text: "결과, 유저" });
} else {
res.send({ results: results, text: "결과만" });
}
} else {
if (req.session.user) {
res.send({ results: "", user_id: req.session.user['id'], text: '일치하는 검색 결과가 없습니다.'});
} else if (req.session.admin) {
res.send({ results: "", admin_id: req.session.admin['id'], text: '일치하는 검색 결과가 없습니다.' });
}else {
res.send({ results: "", text: '일치하는 검색 결과가 없습니다.' });
}
}
}
});
//병원명 검색
/**
* @swagger
* paths:
* /name-search:
* get:
* tags: [ 검색 ]
* summary: "Get main page"
* description: 병원명 검색 페이지
* responses:
* "200":
* description: A successful response
* "400":
* description: Not Found
*/
app.get("/name-search", async(req, res) => {
// 입력된 병원 이름 가져오기
const hospital_name = req.query.hospital_name;
// DB에서 병원 데이터 가져오기
let hospitals = await Hospitals.find({ name: {$regex : hospital_name} });
// index.ejs로 병원 데이터 내보내기
if (hospitals.length > 0) {
// 병원 데이터가 있다면 DB로 받은 병원 데이터를 내보낸다
if (req.session.user) {
res.send({ results: hospitals, user: req.session.user['id'] });
} else if (req.session.admin) {
res.send({ results: hospitals, admin: req.session.admin['id'] });
} else {
res.send({ results: hospitals });
}
} else {
// 병원 데이터가 없다면 "일치하는 검색 결과가 없다"는 내용을 내보낸다
if (req.session.user) {
res.send({ results: "", user: req.session.user['id'] });
} else if (req.session.admin) {
res.send({ results: "", admin: req.session.admin['id'] });
}else {
res.send({ results: "" });
}
}
});
//회원가입 로그인
app.post("/process/:type", async(req, res) => {
const type = req.params.type;
console.log(type)
if (type == "signup") {
try {
const salt = crypto.randomBytes(64).toString("base64");
const hashed_password = crypto.pbkdf2Sync(req.body.createPassword, salt, 190481, 64, "sha512").toString("base64");
let user = new Users();
user.user_id = req.body.createId;
user.user_salt = salt;
user.user_hashedPassword = hashed_password;
user.created_at = new Date();
user = await user.save();
res.send({text: "success"});
} catch (error) {
if (error.code === 11000) {
res.send({text: "exist"});
} else {
res.send({text: "error"});
console.log("*** DB 저장 문제: " + error);
}
}
} else if (type == "login") {
const results = await Users.findOne({ user_id: req.body.inputId });
if (results != null) {
const computed_password = crypto.pbkdf2Sync(req.body.inputPassword, results["user_salt"], 190481, 64, "sha512").toString("base64");
if (computed_password == results['user_hashedPassword']) {
if (results["is_admin"]) {
req.session.admin = {
id: results["_id"],
name: req.body.inputId,
authorized: true
};
} else {
req.session.user = {
id: results["_id"],
name: req.body.inputId,
authorized: true
};
}
res.send({text: "로그인 성공"});
}
} else {
res.send({results: "", text: "일치하는 회원 정보가 없습니다."});
}
} else if (type == "logout") {
req.session.destroy((error) => { res.send({text: "로그아웃"}); });
} else if (type == "change-password") {
const user = await Users.findOne({ user_id: req.body.input_id });
if (user != null) {
const computed_password = crypto.pbkdf2Sync(req.body.old_password, user["user_salt"], 190481, 64, "sha512").toString("base64");
if (computed_password === user["user_hashedPassword"]) {
const salt = crypto.randomBytes(64).toString("base64");
const hashed_password = crypto.pbkdf2Sync(req.body.new_password, salt, 190481, 64, "sha512").toString("base64");
await Users.findOneAndUpdate({ user_id: req.body.input_id }, { user_salt: salt, user_hashedPassword: hashed_password });
res.send({text: "성공"});
} else {
res.send({text: "일치하는 회원 정보가 없습니다."});
}
} else {
res.send({text: "일치하는 회원 정보가 없습니다."});
}
} else if (type == "report") {
let report = new Reports();
report.writer_id = req.body.writer_id;
report.hospital_id = req.body.hospital_id;
report = await report.save();
res.send({text: "신고가 접수되었습니다. 관리자 확인 후 신고횟수에 반영됩니다."});
}
});
/**
* @swagger
* paths:
* /signup:
* post:
* tags: [ 처리 ]
* summary: "Create a user in database"
* description: 회원가입 처리
* parameters:
* - name: "createId"
* in: "formData"
* description: 입력 아이디
* required: true
* type: "string"
* - name: "createPassword"
* in: "formData"
* description: 입력 비밀번호
* required: true
* type: "string"
* responses:
* "200":
* description: A successful response
* "400":
* description: Not Found
*/
app.post("/signup", async(req, res) => {
try {
const salt = crypto.randomBytes(64).toString("base64");
const hashed_password = crypto.pbkdf2Sync(req.body.createPassword, salt, 190481, 64, "sha512").toString("base64");
let user = new Users();
user.user_id = req.body.createId;
user.user_salt = salt;
user.user_hashedPassword = hashed_password;
user.created_at = new Date();
user = await user.save();
res.send({text: "success"});
} catch (error) {
if (error.code === 11000) {
res.send({text: "exist"});
} else {
res.send({text: "error"});
console.log("*** DB 저장 문제: " + error);
}
}
});
/**
* @swagger
* paths:
* /login:
* post:
* tags: [ 처리 ]
* summary: "Login"
* description: 로그인 세션 생성
* parameters:
* - name: "inputId"
* in: "formData"
* description: 입력 아이디
* required: true
* type: "string"
* - name: "inputPassword"
* in: "formData"
* description: 입력 비밀번호
* required: true
* type: "string"
* responses:
* "200":
* description: A successful response
* "400":
* description: Not Found
*/
app.post("/login", async(req, res) => {
const results = await Users.findOne({ user_id: req.body.inputId, is_withdrawn: false });
if (results != null) {
const computed_password = crypto.pbkdf2Sync(req.body.inputPassword, results["user_salt"], 190481, 64, "sha512").toString("base64");
if (computed_password == results['user_hashedPassword']) {
if (results["is_admin"]) {
req.session.admin = {
id: results["_id"],
name: req.body.inputId,
authorized: true
};
} else {
// session save
req.session.user = {
id: results["_id"],
name: req.body.inputId,
authorized: true
};
}
res.send({text: "로그인 성공"});
}
} else {
res.send({results: "", text: "일치하는 회원 정보가 없습니다."});
}
});
/**
* @swagger
* paths:
* /logout:
* delete:
* tags: [ 처리 ]
* summary: "Logout"
* description: 로그인 세션 파괴
* responses:
* "200":
* description: A successful response
* "400":
* description: Not Found
*/
app.delete("/logout", async(req, res) => {
req.session.destroy((error) => { res.send({text: "로그아웃"}); });
});
/**
* @swagger
* paths:
* /report:
* post:
* tags: [ 처리 ]
* summary: "Report a hospital in a databse"
* description: 회원의 병원 신고를 접수함
* parameters:
* - name: "writer_id"
* in: "formData"
* description: 신고하는 회원 아이디
* required: true
* type: "string"
* - name: "hospital_id"
* in: "formData"
* description: 신고하는 병원의 ObjectId
* required: true
* type: "string"
* responses:
* "200":
* description: A successful response
* "400":
* description: Not Found
*/
app.post("/report", async(req, res) => {
let report = new Reports();
report.writer_id = req.body.writer_id;
report.hospital_id = req.body.hospital_id;
report = await report.save();
res.send({text: "신고가 접수되었습니다. 관리자 확인 후 신고횟수에 반영됩니다."});
});
app.get("/openapi", (req, res) => {
// OpenAPI
var url = 'http://apis.data.go.kr/B551182/hospInfoService1/getHospBasisList1';
const myServiceKey = "JtIV8PCzx8%2BLWnp%2F07kxb%2FL4%2Fglq9W6WGZN2AQwOBG%2B9fIRQEA%2F12X%2F2ONTYaEFLDPxdBzqz1CWa6%2FRDwcMxRA%3D%3D";
var queryParams = '?' + encodeURIComponent('serviceKey') + '=' + myServiceKey; /* Service Key*/
queryParams += '&' + encodeURIComponent('sidoCd') + '=' + encodeURIComponent("110000");
request({
// 응답표준은 XML이며, JSON을 요청할 경우 “&_type=json”을 추가하여 요청합니다.
url: url + queryParams + "&_type=json",
method: "GET"
}, (err, response, body) => {
console.log(`Status: ${response.statusCode}`);
parsed_body = JSON.parse(body);
hospitals_list = parsed_body["response"]["body"]["items"]["item"];
res_list = []
hospitals_list.forEach((hospital, index) => {
res_list.push({
"인덱스": index,
"emdongNm": hospital["emdongNm"],
"병원명": hospital["yadmNm"],
"주소": hospital["addr"],
"종별코드명": hospital["clCdNm"],
"전화번호": hospital["telno"],
"의사총수": hospital["drTotCnt"],
"좌표": [hospital["XPos"], hospital["YPos"]],
"시도코드": hospital["sidoCd"],
"시도명": hospital["sidoCdNm"]
})
});
res.send(JSON.stringify(res_list, null, 4));
}
);
});
app.get("/api/checkUser", (req, res) => {
if (req.session.admin) {
res.send({admin_id: req.session.admin['name'], admin_id_id: req.session.admin['id'], user_id: "", user_id_id: ""});
}
else if (req.session.user) {
res.send({user_id: req.session.user['name'], user_id_id: req.session.user['id'], admin_id: "", admin_id_id: ""});
}
else {
res.send({user_id: "", user_id_id: "", admin_id: "", admin_id_id: ""});
}//
})
app.get("/admin/data", async (req, res) => {
const users = await Users.find().sort({ _id: -1 });
const hospitals = await Hospitals.find({ reports_cnt: { $ne: 0 }}, { sgguCdNm: 1, sidoCdNm: 1, reports_cnt: 1, name: 1 }).sort({ reports_cnt: -1 });
const reports = await Reports.find({ is_confirmed: false }).populate({ path: "writer_id", select: { user_id: 1 } }).populate({ path: "hospital_id", select: { sgguCdNm: 1, sidoCdNm: 1, name: 1 }});
res.render("admin/index", { users: users, hospitals: hospitals, reports: reports });
});
app.get("/admin/hospitals_data", async (req, res) => {
const results = await Hospitals.find().limit(50).sort({name: 1});
res.render("admin/hospitals", { results: results });
});
app.post("/admin/hospitals_data/:zipCd", async (req, res) => {
if (true) {
const _url = 'http://apis.data.go.kr/B551182/hospInfoService1/getHospBasisList1';
const myServiceKey = "JtIV8PCzx8%2BLWnp%2F07kxb%2FL4%2Fglq9W6WGZN2AQwOBG%2B9fIRQEA%2F12X%2F2ONTYaEFLDPxdBzqz1CWa6%2FRDwcMxRA%3D%3D";
let queryParams = '?' + encodeURIComponent('serviceKey') + '=' + myServiceKey;
queryParams += '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent('1');
/* 분류코드 */
const zipCd = String(req.params.zipCd);
let totalCount;
if (zipCd == "2010") { totalCount = 365; await Hospitals.deleteMany({zipCd: zipCd}); } // 종합병원
else if (zipCd == "2030") { totalCount = 1397; await Hospitals.deleteMany({zipCd: zipCd}); } // 병원
else if (zipCd == "2040") { totalCount = 1463; await Hospitals.deleteMany({zipCd: zipCd}); } // 요양병원
else if (zipCd == "2050") { totalCount = 18860; await Hospitals.deleteMany({zipCd: zipCd}); } // 치과
else if (zipCd == "2060") { totalCount = 15025; await Hospitals.deleteMany({zipCd: zipCd}); } // 한방
else if (zipCd == "2070") { totalCount = 33962; await Hospitals.deleteMany({zipCd: zipCd}); } // 의원
else if (zipCd == "2080") { totalCount = 3483; await Hospitals.deleteMany({zipCd: zipCd}); } // 보건기관
else if (zipCd == "2090") { totalCount = 16; await Hospitals.deleteMany({zipCd: zipCd}); }// 조산원
else { console.log("*** Error - no matching code"); }
queryParams += '&' + encodeURIComponent('zipCd') + '=' + encodeURIComponent(zipCd);
queryParams += '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent(totalCount);
queryParams += "&_type=json"; // To change XML (default response data type) to JSON, append "&_type=json"
const options = {
url: _url + queryParams,
method: "GET"
}
const response = await request(options); // request to OpenAPI
results = JSON.parse(response)["response"]["body"]["items"]["item"] // extract hospital data only
results.forEach( async (result) => {
let hospital = new Hospitals();
hospital.addr = result.addr;
hospital.type_code = result.clCdNm;
hospital.cmdcGdrCnt = result.cmdcGdrCnt;
hospital.cmdcIntnCnt = result.cmdcIntnCnt;
hospital.cmdcResdntCnt = result.cmdcResdntCnt;
hospital.cmdcSdrCnt = result.cmdcSdrCnt;
hospital.detyGdrCnt = result.detyGdrCnt;
hospital.detyIntnCnt = result.detyIntnCnt;
hospital.detyResdntCnt = result.detyResdntCnt;
hospital.detySdrCnt = result.detySdrCnt;
hospital.drTotCnt = result.drTotCnt;
hospital.estbDd = result.estbDd;
hospital.hospUrl = result.hospUrl;
hospital.mdeptGdrCnt = result.mdeptGdrCnt;
hospital.mdeptIntnCnt = result.mdeptIntnCnt;
hospital.mdeptResdntCnt = result.mdeptResdntCnt;
hospital.mdeptSdrCnt = result.mdeptSdrCnt;
hospital.postNo = result.postNo;
hospital.sgguCdNm = result.sgguCdNm;
hospital.sidoCdNm = result.sidoCdNm;
hospital.telno = result.telno;
hospital.coord = [result.XPos, result.YPos];
hospital.name = result.yadmNm;
hospital.zipCd = zipCd;
try {
hospital = await hospital.save();
} catch (error) {
console.log("DB 저장 문제: " + error);
}
});
res.redirect("/admin/hospitals_data");
}
});
// web server
const server = app.listen(3001, '220.149.235.76', () => {
// port: 3000 app success
console.log("220.149.235.76:3001");
})