-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
316 lines (276 loc) · 8.43 KB
/
index.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
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
var fs = require("fs");
const os = require("os-utils");
const { exec } = require("child_process");
// db 연결
const MongoClient = require("mongodb").MongoClient;
var db;
MongoClient.connect(
"mongodb+srv://admin:[email protected]/?retryWrites=true&w=majority",
function (error, client) {
if (error) return console.log(error);
db = client.db("online-compiler");
app.use(express.static(__dirname));
app.listen(8080, () => console.log("listening on 8080"));
}
);
//문법페이지
app.get("/grammer", (req, res) => {
res.sendFile(__dirname + "/grammer.html");
});
app.get("/grammer/:id", function (req, res) {
db.collection("grammer").findOne(
{ _id: parseInt(req.params.id) },
function (error, result) {
console.log(result);
res.render("grammer.ejs", { data: result });
}
);
});
//방명록 페이지
app.get("/guest", (req, res) => {
db.collection("guest")
.find()
.toArray(function (error, result) {
res.render("guest.ejs", { posts: result });
});
});
app.post("/comment", (req, res) => {
db.collection("counter").findOne(
{ name: "댓글 개수" },
function (error, result) {
var commentNum = result.totalComment;
db.collection("guest").insertOne(
{
_id: commentNum + 1,
name: Object.values(req.body)[0],
content: Object.values(req.body)[1],
},
function (error, res) {
if (error) console.log(error);
console.log("저장완료");
db.collection("counter").updateOne(
{ name: "댓글 개수" },
{ $inc: { totalComment: 1 } }
);
}
);
const responseData = { message: "방명록 저장 완료!" };
res.json(responseData);
}
);
});
app.delete("/delete", function (req, res) {
console.log(req.body);
req.body._id = parseInt(req.body._id);
db.collection("guest").deleteOne(req.body, function (error, result) {
console.log("삭제완료");
res.status(200).send({ message: "성공했습니다" });
});
});
// 로그인
app.get("/login", (req, res) => {
res.sendFile(__dirname + "/login.html");
});
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const session = require("express-session");
app.use(
session({ secret: "비밀코드", resave: true, saveUninitialized: false })
);
app.use(passport.initialize());
app.use(passport.session());
app.post(
"/login",
passport.authenticate("local", {
failureRedirect: "/fail",
}),
(req, res) => {
//console.log(Object.values(req.body)[0]); //id
//console.log(Object.values(req.body)[1]); //pw
const responseData = { redirectTo: "/editor" };
res.json(responseData);
}
);
passport.use(
new LocalStrategy(
{
usernameField: "id",
passwordField: "pw",
session: true,
passReqToCallback: false,
},
function (입력한아이디, 입력한비번, done) {
console.log(입력한아이디, 입력한비번);
db.collection("login").findOne(
{ id: 입력한아이디 },
function (에러, 결과) {
if (에러) return done(에러);
if (!결과)
return done(null, false, {
message: "존재하지 않는 아이디입니다.",
});
if (입력한비번 == 결과.pw) {
return done(null, 결과);
} else {
return done(null, false, { message: "잘못된 비밀번호입니다." });
}
}
);
}
)
);
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (아이디, done) {
db.collection("login").findOne({ id: 아이디 }, function (error, result) {
done(null, result);
});
});
//로그아웃
app.post("/logout", (req, res) => {
req.session.destroy((err) => {
if (err) {
console.log("세션 삭제시에 에러가 발생했습니다.");
return;
}
console.log("세션이 삭제됐습니다.");
});
const responseData = { redirectTo: "/login" };
res.json(responseData);
});
//회원가입
app.get("/register", (req, res) => {
res.sendFile(__dirname + "/register.html");
});
app.post("/register", isValid, (req, res) => {
// isValid: 아이디 유효한지랑 비밀번호 체크하는 함수. 성공했으면 회원가입 하기
//console.log(Object.values(req.body)[0]); //id
//console.log(Object.values(req.body)[1]); //pw
//console.log(Object.values(req.body)[2]); //pw_ck
// 아이디와 비번을 디비에 저장해주자
db.collection("login").insertOne(
{ id: Object.values(req.body)[0], pw: Object.values(req.body)[1] },
function (error, res) {
if (error) console.log(error);
console.log("저장완료");
}
);
const responseData = { result: "success", redirectTo: "/login" };
res.json(responseData);
});
async function isValid(req, res, next) {
if (await existId(Object.values(req.body)[0])) {
//디비에 아이디가 이미 있다
const responseData = {
result: "fail",
error: "아이디 중복",
};
res.json(responseData);
} else if (Object.values(req.body)[1] !== Object.values(req.body)[2]) {
// 비번 틀림
const responseData = {
result: "fail",
error: "비밀번호와 비밀번호 확인 문자가 서로 다름",
};
res.json(responseData);
}
next();
}
async function existId(입력한아이디) {
const exist = await db.collection("login").findOne({ id: 입력한아이디 });
if (exist === null) {
return false;
} else {
return true;
}
}
//소스코드 저장
app.post("/save", (req, res) => {
// console.log(Object.values(req.body)[0]); //source
// 소스코드를 현재 로그인중인 사람의 디비에 함께 저장하자
db.collection("login").update(req.user, {
$set: { source: Object.values(req.body)[0] },
});
const responseData = { message: "소스코드 저장 완료!" };
res.json(responseData);
});
//소스코드 불러오기
app.post("/getSource", (req, res) => {
if (req.user.source === undefined) {
const responseData = { status: "not_exist" };
res.json(responseData);
} else {
const responseData = { status: "exist", source: req.user.source };
res.json(responseData);
}
});
//에디터
app.get("/editor", isLogined, (req, res) => {
// 로그인 되어있으면
res.sendFile(__dirname + "/editor.html");
});
function isLogined(req, res, next) {
if (req.user) {
//console.log(req.user);
next();
} else {
//console.log(req.user);
res.sendFile(__dirname + "/login.html");
}
}
// 소스코드 실행
app.post("/run", (req, res) => {
console.log(req.body);
console.log(Object.values(req.body)[0]); //source
console.log(Object.values(req.body)[1]); //input
console.log("===========================");
fs.writeFile("main.txt", Object.values(req.body)[0], function (err) {
if (err) throw err;
console.log("source saved!");
});
fs.writeFile("input.txt", Object.values(req.body)[1], function (err) {
if (err) throw err;
console.log("input saved!");
});
const pythonCommand = `./tolelom`;
let pythonErrorCommand = `${pythonCommand}`; //`${pythonCommand} 2> error.txt`;
if (Object.values(req.body)[1].trim()) {
pythonErrorCommand = `${pythonCommand} < input.txt`; //`${pythonCommand} < input.txt 2> error.txt`
}
const startTime = new Date();
exec(pythonErrorCommand, (error, stdout, stderr) => {
const endTime = new Date();
const executionTime = (endTime - startTime) / 1000;
/*
let errorData = "";
if (error) {
console.error(`exec error: ${error}`);
errorData = fs.readFileSync("error.txt", "utf-8");
console.error(`stderr: ${errorData}`);
}
if (stderr) {
console.log(`stderr: ${stderr}`);
}*/
const memoryUsage = (os.freememPercentage() * os.totalmem()) / 1024;
os.cpuUsage((cpuUsage) => {
console.log(`Execution Time: ${executionTime} seconds`);
console.log(`Estimated Memory Usage: ${memoryUsage.toFixed(2)} KB`);
});
res.send(
JSON.stringify(
`${stdout}\n\nExecution Time: ${executionTime} seconds\nEstimated Memory Usage: ${memoryUsage.toFixed(
2
)} KB`
)
);
//파일 삭제
fs.unlinkSync("main.txt");
fs.unlinkSync("input.txt");
//fs.unlinkSync("error.txt");
});
});