Skip to content

Commit 1c6c6c3

Browse files
committed
updated validation
1 parent b909707 commit 1c6c6c3

File tree

2 files changed

+61
-15
lines changed

2 files changed

+61
-15
lines changed

server/api/services/code.service.js

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from "fs";
22
import path from "path";
33
import { execFile, spawn, exec } from "child_process";
4+
import ValidationService from "./validation.service";
45
const ROOT_DIR = `${process.cwd()}`;
56
const SOURCE_DIR = path.join(ROOT_DIR, "executor");
67
const TARGET_DIR = `/app/codes`;
@@ -10,8 +11,19 @@ class CodeService {
1011
async execute(code, input, lang, id) {
1112
try {
1213
!input ? (input = "") : null;
14+
1315
//validating code
14-
await this.validateCode(code, input, lang, id);
16+
const { isValid, message } = await ValidationService.execute(
17+
code,
18+
input,
19+
lang,
20+
id
21+
);
22+
if (!isValid) {
23+
throw {
24+
message,
25+
};
26+
}
1527

1628
//writing the code,input files
1729
const { file, inputFile } = await this.writeFile(code, lang, input, id);
@@ -42,20 +54,6 @@ class CodeService {
4254
}
4355
}
4456

45-
async validateCode(code, input, lang, id) {
46-
switch (lang) {
47-
case "javascript": {
48-
let words = ["require(", "exports.", "module.exports"];
49-
// prevent imports
50-
var valid = !words.some((el) => {
51-
return code.includes(el);
52-
});
53-
if (!valid) throw { message: "You have unacceptable libs imported" };
54-
}
55-
}
56-
// throw { message: "You librabry is not accepted : " + lib };
57-
}
58-
5957
async writeFile(code, lang, input, id) {
6058
let fileName = `${id}code`;
6159
switch (lang) {
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class ValidationService {
2+
async execute(code, input, lang, id) {
3+
switch (lang) {
4+
case "javascript": {
5+
let words = ["require(", "exports.", "module.exports"];
6+
// prevent imports
7+
var valid = !words.some((el) => {
8+
return code.includes(el);
9+
});
10+
return {
11+
isValid: valid,
12+
message: "You have unacceptable libs imported",
13+
};
14+
}
15+
case "python": {
16+
let reg1 = RegExp(
17+
/\bimport\W+(?:\w+\W+){0,}(?:os|subprocess|importlib)\b/g
18+
);
19+
words = ["open("];
20+
21+
if (code.match(reg1)) {
22+
return {
23+
isValid: false,
24+
message: "You have unacceptable libs imported",
25+
};
26+
} else if (
27+
words.every((el) => code.toLowerCase().includes(el.toLowerCase()))
28+
) {
29+
return {
30+
isValid: false,
31+
message: "You have unacceptable libs imported",
32+
};
33+
}
34+
return {
35+
isValid: true,
36+
};
37+
}
38+
default: {
39+
return {
40+
isValid: false,
41+
message: "Please select a valid language",
42+
};
43+
}
44+
}
45+
}
46+
}
47+
48+
export default new ValidationService();

0 commit comments

Comments
 (0)