-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
232 lines (210 loc) · 7.29 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
const express = require('express');
const cors = require('express-cors');
const bodyParser = require('body-parser');
const bcrypt = require("bcryptjs");
const sqlite = require("better-sqlite3");
const session = require("express-session");
const serveStatic = require('serve-static');
const captcha = require('trek-captcha');
const { v4 } = require('uuid');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(serveStatic(__dirname + "/static"))
app.use(cors());
const port = process.env.PORT || 4000;
const SqliteStore = require("better-sqlite3-session-store")(session)
const sess_db = new sqlite("sessions.db");
const captchas = {}
app.use(
session({
store: new SqliteStore({
client: sess_db,
expired: {
clear: true,
intervalMs: 900000 //ms = 15min
}
}),
secret: "keyboard cat",
resave: false,
saveUninitialized: false
})
)
app.listen(port, () => {
console.log(`Server is running on port ${port}.`);
});
const db = sqlite('secret-santa.db');
db.exec('CREATE TABLE IF NOT EXISTS users (username TEXT unique, password TEXT)');
db.exec('CREATE TABLE IF NOT EXISTS games (participants TEXT, admin TEXT, pairs TEXT, name TEXT unique, budget INTEGER)');
app.post('/register', (req, res) => {
const { username, password, captchaId, captchaValue } = req.body;
const exists = db.prepare('SELECT * FROM users WHERE username=?').get(username);
if (!exists) {
if (req.body.nicetry) return res.send({ msg: "Unknown error" });
if (captchas[captchaId] !== captchaValue) {
return res.send({ msg: "Invalid or expired captcha. Refresh the page if this persists." });
}
delete captchas[captchaId];
db.prepare('INSERT INTO users(username,password) VALUES (?,?)').run(username, bcrypt.hashSync(password));
res.send({ msg: 'User Registered' });
}
else {
res.send({ msg: 'User Already Exists' });
}
});
app.get('/whoami', (req, res) => {
res.type('json').send(JSON.stringify(req.session.user.username));
})
app.get('/captcha', async (req, res) => {
const uuid = v4();
const { token, buffer } = await captcha();
captchas[uuid] = token;
res.send({
buf: buffer.toString('base64'),
uuid
})
})
app.post('/login', (req, res) => {
const { username, password } = req.body;
const user = db.prepare('SELECT * FROM users WHERE username=?').get(username);
if (user) {
if (bcrypt.compareSync(password, user.password)) {
req.session.user = user;
res.send({ msg: 'Logged In' });
}
else {
res.send({ msg: 'Incorrect Password' });
}
}
else {
res.send({ msg: 'User Not Found' });
}
});
app.get('/logout', (req, res) => {
req.session.destroy();
res.redirect('/');
});
app.get('/is-logged-in', (req, res) => {
res.send(!!req.session.user);
});
function* priorityIterator(array, cmp) {
let i = 0;
const yielded = new Set();
while (i++ < array.length) {
const next = array.filter(a => !yielded.has(a)).reduce((a, b) => (cmp(a, b) < 0 ? a : b));
yielded.add(next);
yield next;
}
}
function createPairs(participants, exclusions, { disallowDuplexPairing = false } = {}) {
const _exclusions = { ...exclusions };
for (const participant of participants) {
if (!_exclusions[participant]) {
_exclusions[participant] = [];
}
}
const allowedPairings = Object.fromEntries(
participants.map(participant => [
participant,
participants
.filter(p => p !== participant)
.filter(p => !_exclusions[participant].includes(p)),
])
);
const pairings = {};
const randomChoice = arr => arr[Math.floor(Math.random() * arr.length)];
const generator = priorityIterator(
participants,
(a, b) => allowedPairings[a].length - allowedPairings[b].length
);
for (const gifter of generator) {
const giftee = randomChoice(allowedPairings[gifter]);
if (!giftee) {
return false;
}
pairings[gifter] = giftee;
for (const participant of participants) {
allowedPairings[participant] = allowedPairings[participant].filter(p => p !== giftee);
}
if (disallowDuplexPairing) {
allowedPairings[giftee] = allowedPairings[giftee].filter(p => p !== gifter);
}
}
return pairings;
}
app.post('/create-game', (req, res) => {
if (!req.session.user) {
return res.status(401).send({
msg: "Not Logged In"
})
}
const { participants, exclusions, name, budget } = req.body;
const row = db.prepare('SELECT * FROM games WHERE name=?').get(name);
if (row) {
return res.status(409).send({ msg: 'Game Exists' });
}
const participantList = participants.split(',');
const participants_s = JSON.stringify(participantList);
// validate participants to make sure they exist in the database
// if not send back an error message
let pairs = null;
while (!(pairs = createPairs(participantList, JSON.parse(exclusions), { disallowDuplexPairing: true })));
try {
const pairString = JSON.stringify(pairs);
db.prepare('INSERT INTO games(participants,admin,pairs,name,budget) VALUES (?,?,?,?,?)').run(participants_s, req.session.user.username, pairString, name, budget);
res.send({ msg: "Ok" });
}
catch (e) {
res.send({ msg: e.message });
}
});
app.get('/users', (req, res) => {
const users = db.prepare('SELECT * FROM users').all();
res.send(users.map(user => user.username));
});
app.post('/delete-game', (req, res) => {
if (!req.session.user) {
return res.status(401).send({
msg: "Not Logged In"
})
}
const { name } = req.body;
const row = db.prepare('SELECT * FROM games WHERE name=?').get(name);
if (row.admin !== req.session.user.username) {
res.status(401).send({ msg: 'Only the creator of a game can delete it.' });
}
db.prepare('DELETE FROM games WHERE name=?').run(name);
res.send({ msg: 'Game Deleted' });
});
app.post('/results', (req, res) => {
const { name } = req.body;
const row = db.prepare('SELECT * FROM games WHERE name=?').get(name);
if (!row) {
res.status(404).send({ msg: 'Game Not Found' });
}
res.send({ msg: JSON.parse(row.pairs)[req.session.user.username] });
});
app.get('/games', (req, res) => {
if (!req.session.user) {
return res.status(401).send({
msg: "Not Logged In"
})
}
const games = db.prepare('SELECT * FROM games').all();
res.send(games
.filter(game => JSON.parse(game.participants).includes(req.session.user.username))
.map(game => {
return { name: game.name, budget: game.budget, admin: game.admin, participants: game.participants }
}));
});
app.get('/adminned-games', (req, res) => {
if (!req.session.user) {
return res.status(401).send({
msg: "Not Logged In"
})
}
const games = db.prepare('SELECT * FROM games').all();
res.send(games
.filter(game => game.admin === req.session.user.username)
.map(game => game.name));
});