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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
|
"use strict";
const cmn = require("../$common.js");
const crypto = require("crypto");
const basicAuth = require("basic-auth");
const fs = require("fs");
const sqlite3 = require("sqlite3");
const mkdirp = require("mkdirp");
let moddir = null;
const ROOT_ENDPOINT = "/timetrack3";
const DB_DIR = cmn.persistdir + "/timetrack3";
const DB_PATH = DB_DIR + "/db";
let DB = null;
function openDatabase() {
const predb = new sqlite3.Database(DB_PATH, sqlite3.OPEN_READWRITE, err => {
if (err && err.code == "SQLITE_CANTOPEN") {
mkdirp.sync(DB_DIR);
const predb2 = new sqlite3.Database(DB_PATH, err => {
if (err) {
console.error("Cannot create database:", err);
process.exit(1);
}
predb2.serialize();
predb2.exec(`
pragma foreign_keys = ON;
create table users (
id integer primary key autoincrement not null,
name text not null,
pwhash text not null, -- 16-byte salt + "$" + scrypt(keylen=64)
cursheet text null,
curdescr text null,
curindate integer null, -- unix timestamp
unique (name)
) strict;
create table events (
id integer primary key autoincrement not null,
username integer not null,
sheet text not null,
descr text not null,
indate integer not null, -- unix timestamp
outdate integer not null, -- unix timestamp
foreign key (username) references users (name) on delete cascade
)
`);
DB = predb2;
});
} else if (err) {
console.error("Cannot open database:", err);
process.exit(1);
} else {
predb.serialize();
predb.exec("pragma foreign_keys = ON;");
DB = predb;
}
});
}
function scryptHash(password, cb) {
crypto.randomBytes(16, function(err, salt) {
if (err) {
cb(err, null);
return;
}
crypto.scrypt(password, salt, 64, (err, key) => {
if (err) cb(err, null);
else cb(null, salt.toString("hex") + "$" + key.toString("hex"));
});
});
}
function scryptCompare(password, hash, cb) {
hash = hash.split("$");
if (hash.length != 2) {
cb(new Error("Invalid hash in database"), null);
return;
}
const salt = Buffer.from(hash[0], "hex"), shash = hash[1];
crypto.scrypt(password, salt, 64, (err, key) => {
if (err) cb(err, null);
else if(key.toString("hex") == shash) cb(null, true);
else cb(null, false);
});
}
function sendUnauth(res) {
res.set("WWW-Authenticate", "Basic realm=Authorization required");
return res.sendStatus(401);
}
function unknownUserHandler(req, res, next){
res.sendFile(moddir + "/unknownuser.html");
}
function authMiddleware(req, res, next){
const user = basicAuth(req);
req.authuser = null;
if (!user || !user.name) {
sendUnauth(res);
return;
}
req.authuser = user.name;
DB.get("select pwhash from users where name = ?", [user.name], (err, row) => {
if (err || row == undefined) {
unknownUserHandler(req, res, next);
return;
}
scryptCompare(user.pass, row.pwhash, (err, ok) => {
if (ok) next();
else sendUnauth(res);
});
});
}
function asciiValid(str) {
for (let i = 0; i < str.length; i++) {
const c = str.charCodeAt(i);
if (c < 32 || c >= 127) return false;
}
return true;
}
function dbCallback(res, fn) {
return function(err) {
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
} else {
fn(...Array.from(arguments).slice(1));
}
};
}
function fatalRollback() {
DB.exec("rollback", err => {
if (err) {
console.log("ROLLBACK", err);
process.exit(1);
}
});
}
module.exports = function(app, io, _moddir){
openDatabase();
moddir = _moddir;
// first the endpoints that need to bypass authMiddleware
// - -> html
app.get(ROOT_ENDPOINT + "/authfail", (req, res) => {
sendUnauth(res);
});
// - -> html (account info is in basic auth)
app.post(ROOT_ENDPOINT + "/createuser", (req, res) => {
const user = basicAuth(req);
if (!user || !user.name) {
res.status(400).send("No credentials sent");
return;
}
if (user.name.length < 3 || user.name.length > 32 || !asciiValid(user.name)) {
res.status(400).send("Invalid username");
return;
}
if (user.pass.length < 3 || user.pass.length > 32 || !asciiValid(user.pass)) {
res.status(400).send("Invalid password");
return;
}
DB.get("select id from users where name = ?", [user.name], dbCallback(res, row => {
if (row != undefined) {
res.status(400).send("User already exists");
return;
}
DB.get("select count(*) as cnt from users", dbCallback(res, row => {
if (row.cnt >= 20) {
res.status(500).send("Too many accounts created, please contact Tom...");
return;
}
scryptHash(user.pass, (err, hash) => {
if (!hash) {
res.status(500).send("Something went wrong...");
console.log(err);
return;
}
DB.run("insert into users (name, pwhash) values (?, ?)", [user.name, hash]);
res.status(200).end();
});
}));
}));
});
// for all the other endpoints, authorisation is needed
app.all([ROOT_ENDPOINT, ROOT_ENDPOINT + "/*"], authMiddleware);
// - -> html
app.get(ROOT_ENDPOINT, (req, res) => {
res.sendFile(moddir + "/timetrack.html");
});
// - -> {sheet, descr, indate} (date in unix timestamp)
app.get(ROOT_ENDPOINT + "/current", (req, res) => {
DB.get("select cursheet, curdescr, curindate from users where name = ?", [req.authuser], dbCallback(res, row => {
res.json({
sheet: row.cursheet,
descr: row.curdescr,
indate: row.curindate,
});
}));
});
// - -> [{id, sheet, descr, indate, outdate}] (dates in unix timestamp)
app.get(ROOT_ENDPOINT + "/recent", (req, res) => {
DB.all("select id, sheet, descr, indate, outdate from events where username = ? order by indate desc limit 20", [req.authuser], dbCallback(res, rows => {
// We got the rows in descending order so that we could apply the limit clause; reorder them in ascending order again
rows.reverse();
res.json(rows.map(row => ({
id: row.id,
sheet: row.sheet,
descr: row.descr,
indate: row.indate,
outdate: row.outdate,
})));
}));
});
// - -> [{sheet, total}] (totals in seconds)
app.get(ROOT_ENDPOINT + "/sheets", (req, res) => {
DB.all("select sheet, sum(outdate - indate) as total from events where username = ? group by sheet", [req.authuser], dbCallback(res, rows => {
res.json(rows.map(row => ({
sheet: row.sheet,
total: row.total,
})));
}));
});
// id -> -
app.delete(ROOT_ENDPOINT + "/event", (req, res) => {
const id = +req.body;
if (id < 0 || ~~id != id || isNaN(id)) {
res.status(404).send("Unknown id");
return;
}
DB.run("delete from events where username = ? and id = ?", [req.authuser, id], function(err) { // uses 'this'
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
return;
}
if (this.changes == 0) {
res.status(404).send("Event not found");
} else {
res.status(200).send();
}
});
});
// {sheet, descr, date} -> - (date in unix timestamp)
app.post(ROOT_ENDPOINT + "/checkin", (req, res) => {
let obj;
try {
obj = JSON.parse(req.body);
} catch (e) {
res.status(400).send("Invalid request");
return;
}
const sheet = obj.sheet + "", descr = obj.descr + "", date = new Date(obj.date * 1000);
if (sheet.length == 0 || isNaN(date.getTime())) {
res.status(400).send("Invalid data");
return;
}
// 'immediate' to make this a write transaction
DB.exec("begin immediate", err => {
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
return;
}
DB.get("select (select count(*) from events where username = ?) as cnt, (select cursheet from users where name = ?) as cursheet", [req.authuser, req.authuser], (err, row) => {
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
fatalRollback();
return;
}
if (row.cnt >= 10000) {
res.status(400).send("Isn't 10000 events enough for you?");
fatalRollback();
return;
}
if (row.cursheet) {
res.status(409).send("Already checked in");
fatalRollback();
return;
}
DB.run("update users set cursheet = ?, curdescr = ?, curindate = ? where name = ?", [sheet, descr, ~~(date.getTime() / 1000), req.authuser], err => {
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
fatalRollback();
return;
}
DB.exec("commit", err => {
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
fatalRollback();
return;
}
res.status(200).end();
});
});
});
});
});
// {date} -> - (date in unix timestamp)
app.post(ROOT_ENDPOINT + "/checkout", (req, res) => {
let obj;
try {
obj = JSON.parse(req.body);
} catch (e) {
res.status(400).send("Invalid request");
return;
}
const date = new Date(obj.date * 1000);
if (isNaN(date.getTime())) {
res.status(400).send("Invalid data");
return;
}
// 'immediate' to make this a write transaction
DB.exec("begin immediate", err => {
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
return;
}
DB.get("select count(*) as cnt from events where username = ?", [req.authuser], (err, row) => {
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
fatalRollback();
return;
}
if (row.cnt >= 10000) {
res.status(400).send("Isn't 10000 events enough for you?");
fatalRollback();
return;
}
DB.get("select cursheet, curdescr, curindate from users where name = ?", [req.authuser], (err, row) => {
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
fatalRollback();
return;
}
if (!row.cursheet) {
res.status(409).send("Not checked in");
fatalRollback();
return;
}
const sheet = row.cursheet, descr = row.curdescr, indate = row.curindate;
DB.run("update users set cursheet = null, curdescr = null, curindate = null where name = ?", [req.authuser], err => {
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
fatalRollback();
return;
}
DB.run("insert into events(username, sheet, descr, indate, outdate) values (?, ?, ?, ?, ?)", [req.authuser, sheet, descr, indate, ~~(date.getTime() / 1000)], err => {
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
fatalRollback();
return;
}
DB.exec("commit", err => {
if (err) {
console.error(err);
res.status(500).send("Something went wrong...");
fatalRollback();
return;
}
res.status(200).end();
});
});
});
});
});
});
});
};
|