-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
105 lines (85 loc) · 2.64 KB
/
Copy pathserver.js
File metadata and controls
105 lines (85 loc) · 2.64 KB
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
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
import { oneLine } from 'common-tags';
// Connect to the database
var pgp = require('pg-promise')();
var cn = {
user: 'postgres',
password: '1234',
host: 'localhost',
database: 'challenges',
};
var db = pgp(cn);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('view engine', 'ejs');
// Cookie handling logic
app.use(cookieParser());
// Set UUID if nonexistant
const uuidgen = require('node-uuid');
app.use((req, res, next) => {
let uuid = req.cookies.uuid;
if (uuid === undefined) {
uuid = uuidgen.v4();
res.cookie('uuid', uuid, { maxAge: 900000, httpOnly: true });
}
console.log(`[${req.method}]\t${req.url}\t${uuid}`);
res.locals.uuid = uuid;
next();
});
function checkProblemStatus(uuid, level) {
return () => {
return db.any(oneLine `SELECT * FROM records
WHERE uuid=$1 AND level=$2
ORDER BY datetime ASC`,
[uuid, level])
.then((rows) => {
let hasSolved = false;
let timeSolved;
let attempts = 0;
rows.forEach((row) => {
if (!hasSolved) {
if (row.correct) {
hasSolved = true;
timeSolved = row.datetime;
} else {
attempts++;
}
}
});
return {
hasSolved,
timeSolved,
attempts
};
})
}
}
// Host static files
app.use(express.static(__dirname + '/public'));
}
}
// Handle problem submission
app.post('/submit', (req, res) => {
let uuid = req.cookies.uuid;
let submission = req.body.submission;
let level = req.body.level;
let {correct, message} = handleProblem(level, submission);
db.none(oneLine `INSERT INTO records
(uuid, datetime, level, submission, correct)
VALUES ($1, $2, $3, $4, $5)`,
[uuid, new Date(), level, submission, correct]
)
.then(checkProblemStatus(uuid, level))
.then(({hasSolved, timeSolved, attempts}) => {
res.send(message);
})
});
// Start the server
const server = app.listen(80, () => {
const host = server.address().address;
const port = server.address().port;
console.log('Listening at http://%s:%s', host, port);
});