forked from juice-shop/juice-shop
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvulnCodeFixes.ts
98 lines (87 loc) · 2.62 KB
/
vulnCodeFixes.ts
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
import { type NextFunction, type Request, type Response } from 'express'
import * as accuracy from '../lib/accuracy'
const challengeUtils = require('../lib/challengeUtils')
const fs = require('fs')
const yaml = require('js-yaml')
const FixesDir = 'data/static/codefixes'
interface codeFix {
fixes: string[]
correct: number
}
type cache = Record<string, codeFix>
const CodeFixes: cache = {}
export const readFixes = (key: string) => {
if (CodeFixes[key]) {
return CodeFixes[key]
}
const files = fs.readdirSync(FixesDir)
const fixes: string[] = []
let correct: number = -1
for (const file of files) {
if (file.startsWith(`${key}_`)) {
const fix = fs.readFileSync(`${FixesDir}/${file}`).toString()
const metadata = file.split('_')
const number = metadata[1]
fixes.push(fix)
if (metadata.length === 3) {
correct = parseInt(number, 10)
correct--
}
}
}
CodeFixes[key] = {
fixes,
correct
}
return CodeFixes[key]
}
interface FixesRequestParams {
key: string
}
interface VerdictRequestBody {
key: string
selectedFix: number
}
export const serveCodeFixes = () => (req: Request<FixesRequestParams, Record<string, unknown>, Record<string, unknown>>, res: Response, next: NextFunction) => {
const key = req.params.key
const fixData = readFixes(key)
if (fixData.fixes.length === 0) {
res.status(404).json({
error: 'No fixes found for the snippet!'
})
return
}
res.status(200).json({
fixes: fixData.fixes
})
}
export const checkCorrectFix = () => async (req: Request<Record<string, unknown>, Record<string, unknown>, VerdictRequestBody>, res: Response, next: NextFunction) => {
const key = req.body.key
const selectedFix = req.body.selectedFix
const fixData = readFixes(key)
if (fixData.fixes.length === 0) {
res.status(404).json({
error: 'No fixes found for the snippet!'
})
} else {
let explanation
if (fs.existsSync('./data/static/codefixes/' + key + '.info.yml')) {
const codingChallengeInfos = yaml.load(fs.readFileSync('./data/static/codefixes/' + key + '.info.yml', 'utf8'))
const selectedFixInfo = codingChallengeInfos?.fixes.find(({ id }: { id: number }) => id === selectedFix + 1)
if (selectedFixInfo?.explanation) explanation = res.__(selectedFixInfo.explanation)
}
if (selectedFix === fixData.correct) {
await challengeUtils.solveFixIt(key)
res.status(200).json({
verdict: true,
explanation
})
} else {
accuracy.storeFixItVerdict(key, false)
res.status(200).json({
verdict: false,
explanation
})
}
}
}