redbean096@khu.ac.kr

Implement Line channel and hide Secret key with domain

1 const Koa = require("koa"); 1 const Koa = require("koa");
2 const Router = require("koa-router"); 2 const Router = require("koa-router");
3 const bodyParser = require("koa-bodyparser"); 3 const bodyParser = require("koa-bodyparser");
4 +
4 const mongoose = require("mongoose"); 5 const mongoose = require("mongoose");
5 const fs = require("fs"); 6 const fs = require("fs");
7 +const path = require('path');
8 +const HTTPS = require('https');
9 +
6 const morgan = require("koa-morgan"); 10 const morgan = require("koa-morgan");
7 const jwtMiddleware = require("./src/lib/jwtMiddleware"); 11 const jwtMiddleware = require("./src/lib/jwtMiddleware");
12 +
8 const api = require("./src/api"); 13 const api = require("./src/api");
14 +
9 const cors = require('@koa/cors'); // for fix CORS Error 15 const cors = require('@koa/cors'); // for fix CORS Error
16 +
10 require("dotenv").config(); 17 require("dotenv").config();
11 18
12 const app = new Koa(); 19 const app = new Koa();
...@@ -19,7 +26,8 @@ app.use(cors()); ...@@ -19,7 +26,8 @@ app.use(cors());
19 app.use(bodyParser()); 26 app.use(bodyParser());
20 app.use(jwtMiddleware); 27 app.use(jwtMiddleware);
21 app.use(morgan("combined", { stream: accessLogStream })); 28 app.use(morgan("combined", { stream: accessLogStream }));
22 -const { SERVER_PORT, MONGO_URL } = process.env; 29 +
30 +const { SERVER_PORT, MONGO_URL, SSLPORT, DOMAIN } = process.env;
23 31
24 router.use("/api", api.routes()); 32 router.use("/api", api.routes());
25 app.use(router.routes()).use(router.allowedMethods()); 33 app.use(router.routes()).use(router.allowedMethods());
...@@ -40,3 +48,18 @@ mongoose ...@@ -40,3 +48,18 @@ mongoose
40 app.listen(SERVER_PORT, () => { 48 app.listen(SERVER_PORT, () => {
41 console.log("Server is running on port", process.env.SERVER_PORT); 49 console.log("Server is running on port", process.env.SERVER_PORT);
42 }); 50 });
51 +
52 +try {
53 + const option = {
54 + ca: fs.readFileSync('/etc/letsencrypt/live/' + DOMAIN +'/fullchain.pem'),
55 + key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + DOMAIN +'/privkey.pem'), 'utf8').toString(),
56 + cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + DOMAIN +'/cert.pem'), 'utf8').toString(),
57 + };
58 +
59 + HTTPS.createServer(option, app.callback()).listen(SSLPORT, () => {
60 + console.log(`[HTTPS] Server is started on port ${SSLPORT}`);
61 + });
62 +} catch (error) {
63 + console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
64 + console.log(error);
65 +}
......
1 -// const lineCtrl = require("./line.ctrl");
2 -
3 -// var Koa = require('koa');
4 -// const request = require('request');
5 -// const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
6 -// const TOKEN = 'iaoVQEV5adLHh7MbW8bZvHKoULoKZUD6B0bXD2l0srO+yXyXKRe4HBLvWQwrkKQx2fwdsz1O/qVpVh9eucUf9GxRb8w2dSaaWCXd9FTqDLP5Yu9xovneGprYlU/0VKSAVw1iphi9BfJWfjIjwWY2pAdB04t89/1O/w1cDnyilFU=';
7 -// const fs = require('fs');
8 -// const path = require('path');
9 -// const HTTPS = require('https');
10 -// const domain = "www.ossjaksimsamil.ml"
11 -// const sslport = 23023;
12 -
13 -// const bodyParser = require('body-parser');
14 -// var app = new Koa();
15 -// app.use(bodyParser.json());
16 -// let username; //username 저장
17 -// app.post('/hook', function (req, res) {
18 -
19 -// var eventObj = req.body.events[0];
20 -// //var source = eventObj.source;
21 -// //var message = eventObj.message;
22 -
23 -// // request log
24 -// console.log('======================', new Date() ,'======================');
25 -// console.log('[request]', req.body);
26 -// console.log('[request source] ', eventObj.source);
27 -// console.log('[request message]', eventObj.message);
28 -// if((eventObj.message.text == '문제추천')&&(username != undefined)){
29 -// console.log("문제를 추천합니다.");
30 -// recommendData = lineCtrl.lineRecommend(username);
31 -// recommendBJ(eventObj.replyToken, recommendData);
32 -// } else {
33 -// let isExist = lineCtrl.findID(eventObj.message.text);
34 -// if (isExist == true)
35 -// username = eventObj.message.text;
36 -// else{
37 -// request.post(
38 -// {
39 -// url: TARGET_URL,
40 -// headers: {
41 -// 'Authorization': `Bearer ${TOKEN}`
42 -// },
43 -// json: {
44 -// "replyToken":replyToken,
45 -// "messages":[
46 -// {
47 -// "type":"text",
48 -// "text": "작심삼일 혹은 백준 사이트의 ID값이 올바르지 않습니다. 다시 입력해주세요."
49 -// }
50 -// ]
51 -// }
52 -// },(body) => {
53 -// console.log(body)
54 -// });
55 -// }
56 -
57 -// recommendBJ(eventObj.replyToken, eventObj.message.text);
58 -// }
59 -// res.sendStatus(200);
60 -// },
61 -
62 -// function recommendBJ(replyToken, message) {
63 -// var recommendProblem = "오늘의 추천문제는 " + message.problem_title + "입니다.";
64 -// var problemURL = "https://www.boj.kr/" + recommendData.problem_number;
65 -// request.post(
66 -// {
67 -// url: TARGET_URL,
68 -// headers: {
69 -// 'Authorization': `Bearer ${TOKEN}`
70 -// },
71 -// json: {
72 -// "replyToken":replyToken,
73 -// "messages":[
74 -// {
75 -// "type":"text",
76 -// "text": recommendProblem
77 -// },
78 -// {
79 -// "type":"text",
80 -// "text": problemURL
81 -// }
82 -// ]
83 -// }
84 -// },(body) => {
85 -// console.log(body)
86 -// });
87 -
88 -
89 -// res.sendStatus(200);
90 -// });
91 -
92 -// try {
93 -// const option = {
94 -// ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'),
95 -// key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/privkey.pem'), 'utf8').toString(),
96 -// cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/cert.pem'), 'utf8').toString(),
97 -// };
98 -
99 -// HTTPS.createServer(option, app).listen(sslport, () => {
100 -// console.log(`[HTTPS] Server is started on port ${sslport}`);
101 -// });
102 -// } catch (error) {
103 -// console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
104 -// console.log(error);
105 -// }
...\ No newline at end of file ...\ No newline at end of file
1 const request = require('request'); 1 const request = require('request');
2 const TARGET_URL = 'https://api.line.me/v2/bot/message/reply' 2 const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
3 -const TOKEN = 'iaoVQEV5adLHh7MbW8bZvHKoULoKZUD6B0bXD2l0srO+yXyXKRe4HBLvWQwrkKQx2fwdsz1O/qVpVh9eucUf9GxRb8w2dSaaWCXd9FTqDLP5Yu9xovneGprYlU/0VKSAVw1iphi9BfJWfjIjwWY2pAdB04t89/1O/w1cDnyilFU='; 3 +
4 -const fs = require('fs'); 4 +require("dotenv").config();
5 -const path = require('path'); 5 +const TOKEN = process.env.LINE_CHANNEL_KEY;
6 -const HTTPS = require('https');
7 -const domain = "www.ossjaksimsamil.ml"
8 -const sslport = 23023;
9 6
10 const Profile = require("../../models/profile"); 7 const Profile = require("../../models/profile");
11 const problem_set = require("../../data/problem_set"); 8 const problem_set = require("../../data/problem_set");
12 const compareBJ = require("../../util/compareBJ"); 9 const compareBJ = require("../../util/compareBJ");
13 -const user = require('../user');
14 10
15 let username = ""; 11 let username = "";
16 12
17 -exports.linestart = function(req,res) { 13 +exports.linestart = async(ctx) => {
18 - var eventObj = req.body.events[0]; 14 + var eventObj = ctx.request.body.events[0];
19 - //var source = eventObj.source; 15 +
20 - //var message = eventObj.message;
21 -
22 // request log 16 // request log
23 console.log('======================', new Date() ,'======================'); 17 console.log('======================', new Date() ,'======================');
24 - console.log('[request]', req.body); 18 + console.log('[request]', ctx.request.body);
25 console.log('[request source] ', eventObj.source); 19 console.log('[request source] ', eventObj.source);
26 console.log('[request message]', eventObj.message); 20 console.log('[request message]', eventObj.message);
27 - 21 + console.log('[username]', username);
22 +
28 if(username == "") { 23 if(username == "") {
29 username = eventObj.message.text; 24 username = eventObj.message.text;
30 - }
31 25
32 - if (!isExist(username)) { 26 + const result = await isExist(username);
33 - username = ""; 27 + if (!result) {
28 + username = "";
29 +
30 + request.post(
31 + {
32 + url: TARGET_URL,
33 + headers: {
34 + 'Authorization': `Bearer ${TOKEN}`
35 + },
36 + json: {
37 + "replyToken":eventObj.replyToken,
38 + "messages":[
39 + {
40 + "type":"text",
41 + "text": "작심삼일 혹은 백준 사이트의 ID값이 올바르지 않습니다. 다시 입력해주세요."
42 + }
43 + ]
44 + }
45 + },(body) => {
46 + console.log(body)
47 + });
48 + } else {
49 + request.post({
50 + url: TARGET_URL,
51 + headers: {
52 + 'Authorization': `Bearer ${TOKEN}`
53 + },
54 + json: {
55 + "replyToken":eventObj.replyToken,
56 + "messages":[
57 + {
58 + "type":"text",
59 + "text": eventObj.message.text + " : 정상 등록 되었습니다."
60 + }
61 + ]
62 + }
63 + },(body) => {
64 + console.log(body)
65 + });
66 +
67 + }
68 + };
69 +
34 70
71 + if(eventObj.message.text == "reset ID") {
72 + username = "";
35 request.post( 73 request.post(
36 { 74 {
37 url: TARGET_URL, 75 url: TARGET_URL,
...@@ -39,11 +77,11 @@ exports.linestart = function(req,res) { ...@@ -39,11 +77,11 @@ exports.linestart = function(req,res) {
39 'Authorization': `Bearer ${TOKEN}` 77 'Authorization': `Bearer ${TOKEN}`
40 }, 78 },
41 json: { 79 json: {
42 - "replyToken":replyToken, 80 + "replyToken": eventObj.replyToken,
43 "messages":[ 81 "messages":[
44 { 82 {
45 "type":"text", 83 "type":"text",
46 - "text": "작심삼일 혹은 백준 사이트의 ID값이 올바르지 않습니다. 다시 입력해주세요." 84 + "text": "작심삼일 혹은 백준 사이트의 ID가 초기화 되었습니다."
47 } 85 }
48 ] 86 ]
49 } 87 }
...@@ -51,49 +89,20 @@ exports.linestart = function(req,res) { ...@@ -51,49 +89,20 @@ exports.linestart = function(req,res) {
51 console.log(body) 89 console.log(body)
52 }); 90 });
53 } 91 }
92 +
54 93
55 if(eventObj.message.text == "문제") { 94 if(eventObj.message.text == "문제") {
56 console.log("문제를 추천합니다."); 95 console.log("문제를 추천합니다.");
57 - recommendData = lineRecommend(username); 96 + let recommendData = await lineRecommend(username);
58 recommendBJ(eventObj.replyToken, recommendData); 97 recommendBJ(eventObj.replyToken, recommendData);
98 +
99 + console.log(recommendData);
59 } 100 }
60 101
61 - // if((eventObj.message.text == '문제추천')&&(username != undefined)){
62 - // console.log("문제를 추천합니다.");
63 - // recommendData = lineRecommend(username);
64 - // recommendBJ(eventObj.replyToken, recommendData);
65 - // } else {
66 - // let isExist = lineCtrl.findID(eventObj.message.text);
67 - // if (isExist == true)
68 - // username = eventObj.message.text;
69 - // else{
70 - // request.post(
71 - // {
72 - // url: TARGET_URL,
73 - // headers: {
74 - // 'Authorization': `Bearer ${TOKEN}`
75 - // },
76 - // json: {
77 - // "replyToken":replyToken,
78 - // "messages":[
79 - // {
80 - // "type":"text",
81 - // "text": "작심삼일 혹은 백준 사이트의 ID값이 올바르지 않습니다. 다시 입력해주세요."
82 - // }
83 - // ]
84 - // }
85 - // },(body) => {
86 - // console.log(body)
87 - // });
88 - // }
89 -
90 - // recommendBJ(eventObj.replyToken, eventObj.message.text);
91 - // }
92 - res.sendStatus(200);
93 } 102 }
94 103
95 -function recommendBJ(replyToken, message) { 104 +function recommendBJ(replyToken, recommendData) {
96 - var recommendProblem = "오늘의 추천문제는 " + message.problem_title + "입니다."; 105 + var recommendProblem = "오늘의 추천문제는 " + recommendData.problem_title + "입니다.";
97 var problemURL = "https://www.boj.kr/" + recommendData.problem_number; 106 var problemURL = "https://www.boj.kr/" + recommendData.problem_number;
98 request.post( 107 request.post(
99 { 108 {
...@@ -117,45 +126,22 @@ function recommendBJ(replyToken, message) { ...@@ -117,45 +126,22 @@ function recommendBJ(replyToken, message) {
117 },(body) => { 126 },(body) => {
118 console.log(body) 127 console.log(body)
119 }); 128 });
120 -
121 -
122 - res.sendStatus(200);
123 } 129 }
124 130
125 -try { 131 +async function lineRecommend (username) {
126 - const option = {
127 - ca: fs.readFileSync('/etc/letsencrypt/live/' + domain +'/fullchain.pem'),
128 - key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/privkey.pem'), 'utf8').toString(),
129 - cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain +'/cert.pem'), 'utf8').toString(),
130 - };
131 -
132 - HTTPS.createServer(option, app).listen(sslport, () => {
133 - console.log(`[HTTPS] Server is started on port ${sslport}`);
134 - });
135 -} catch (error) {
136 - console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
137 - console.log(error);
138 -}
139 -
140 -
141 -/*
142 -POST api/notify/slack/recommend
143 -{
144 - username: "username"
145 -}
146 -*/
147 -function lineRecommend(username) {
148 132
149 const profile = await Profile.findByUsername(username); 133 const profile = await Profile.findByUsername(username);
150 if (!profile) { 134 if (!profile) {
151 console.log("401"); 135 console.log("401");
152 return; 136 return;
153 } 137 }
154 - let unsolved_data = compareBJ.compareBJ( 138 +
139 + const unsolved_data = await compareBJ.compareBJ(
155 profile.getBJdata(), 140 profile.getBJdata(),
156 problem_set.problem_set 141 problem_set.problem_set
157 ); 142 );
158 - let recommendData = compareBJ.randomItem(unsolved_data); 143 +
144 + const recommendData = await compareBJ.randomItem(unsolved_data);
159 145
160 if (!recommendData) { 146 if (!recommendData) {
161 console.log("402"); 147 console.log("402");
...@@ -166,9 +152,12 @@ function lineRecommend(username) { ...@@ -166,9 +152,12 @@ function lineRecommend(username) {
166 152
167 }; 153 };
168 154
169 -function isExist(username) { 155 +async function isExist(username) {
170 const profile = await Profile.findByUsername(username); 156 const profile = await Profile.findByUsername(username);
157 +
171 if (!profile) { 158 if (!profile) {
172 return false; 159 return false;
173 - } else return true;
174 -}
...\ No newline at end of file ...\ No newline at end of file
160 + }
161 +
162 + return true;
163 +}
......