-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes-vote.js
313 lines (276 loc) · 9.39 KB
/
routes-vote.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
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
const express = require('express');
const foreign = require('./foreign');
const tokenUtils = require('./utils-token');
const models = require('./models');
const config = require('./config.json');
const l10nMsg = {
'BALLOT_INFO_INCONSISTENT': '身份驗證方式衝突',
'ALREADY_VOTED': '此人已經投過票',
'TX_NOT_FOUND': '授權碼不存在或已使用過',
'MISSING_TX': '未提供授權碼'
};
function logRequest(req, resp, level, content) {
const clientId = (resp.locals.client || {}).id || null;
return models.Log.log(level, req.route.path, content, clientId);
}
/* Pass on the error in a Express route handler.
* it may be concatenated at the end of Promise that should eventually respond to the request.
* if a rejection happens and is only caught by Bluebird,
* the response will not be returned, resulting a timeout.
* the handler emits a 500 instead.
*/
function promiseErrorHandler(next) {
return err => next(err);
}
// check for a valid token and infer its corresponding client
function requestHook(req, resp, next) {
const ret = resp.locals.ret = {
ok: false,
msg: null
};
let token = req.query.token;
if (!token) {
// token is not given in query
ret.msg = 'Unauthorized';
return resp.status(401).send(ret);
}
const authCode = tokenUtils.doHash(token);
models.Client
.find({ where: { auth_code: authCode } })
.then(inst => {
if (inst == null) {
ret.msg = 'Invalid token';
return resp.status(401).send(ret);
}
resp.locals.client = inst;
next();
});
}
// load overriding data
let overrideDict = {};
if (config.VOTE_ENABLE_OVERRIDE) {
console.log('Loading overriding data...');
overrideDict = require('./meta/region-override.json');
}
app = new express();
app.set('x-powered-by', false);
app.use(require('body-parser').text());
app.use(express.urlencoded({ extended: true }));
app.get('/ping', requestHook, (req, resp) => {
resp.locals.client
.set({ last_ping: models.db.fn('NOW', 3) })
.save({ silent: true })
.then(client => {
logRequest(req, resp, 'verbose', `ping`);
return client.reload();
})
.then(client => {
resp.json({
ok: true,
msg: null,
client: {
id: client.id,
name: client.name,
comment: client.comment
}
});
})
.catch(err => {
resp.json({
ok: false,
msg: err.message
});
});
});
app.get('/query', requestHook, (req, resp, next) => {
let ret = resp.locals.ret;
let stuid = req.query.stuid;
let bypass_serial = (req.query.bypass_serial == 'true' ||
(req.query.bypass_serial - 0) > 0);
if (!stuid) {
// stuid is required
ret.msg = 'Access denied, meow :3';
resp.status(400);
return resp.json(ret);
}
// normalize the first letter (others are digits)
stuid = stuid.toLowerCase();
if (stuid.length != 9 || (!req.query.serial && !bypass_serial)) {
// stuid should have exact length,
// and either serial should be given or explicitly bypass it
// the behavior of bypassing will be recorded!
logRequest(req, resp, 'verbose',
`invalid query, stuid [${stuid}], ` +
`ser ${req.query.serial}, byp ${bypass_serial}`);
ret.msg = 'Bad request, meow :3';
resp.status(400);
return resp.json(ret);
}
ret.can_vote = false;
ret.tx = null;
let requestChain;
if (bypass_serial) {
requestChain = foreign.query(stuid + '0')
.then(result => {
if (!result.error) {
// case #1: guessed serial number is correct
ret.serial = '0';
return Promise.resolve(result);
}
const mat = result.error.match(/.+:(\d+)/);
if (mat == null) {
// case #2: other type of error; no need to try again
ret.serial = null;
return Promise.resolve(result);
}
// case #3: serial number is retrieved from foreign request
ret.serial = mat[1];
logRequest(req, resp, 'debug', `serial bypassing: ${stuid} => ${ret.serial}`);
return foreign.query(stuid + ret.serial);
});
} else {
// case #4: serial number is provided within request
ret.serial = req.query.serial;
requestChain = foreign.query(stuid + ret.serial);
}
// ret.serial is set to a valid serial or null in requestChain.then
requestChain
.then(result => {
ret.ok = true;
// check pre-condition by foreign response
var isLegitIdent = result.webok && result.incampus;
ret.result = result;
logRequest(req, resp, 'debug', `recv result ${JSON.stringify(result)}`);
// hide sensitive information from error message
result.error = result.error.replace(/(.+?):\d+/, '$1:***');
if (!isLegitIdent) {
ret.msg = result.error;
logRequest(req, resp, 'verbose', `is not legitimate: [${stuid}]: ${result.error}`);
return Promise.resolve(null);
}
// if bypass then do not record its serial
let recordedSerial = bypass_serial ? null : ret.serial;
// retrieve ballot, check if consistent
// if do (or new), generate a new tx
// (not new and yet commited), leave intact
// if not, reject inconsistent state
// if commited, reject duplicates
return models.Ballot.findOrBuild({
where: { uid: stuid },
defaults: {
serial: recordedSerial,
client_id: resp.locals.client.id,
stutype: result.stutype,
college: result.college,
dept: result.dptcode,
card_sec: req.query.card_sec
}
}).spread((ballot, inited) => {
if (overrideDict.hasOwnProperty(stuid)) {
// if found overriding, do override
ballot.set('college', overrideDict[stuid]);
result.college = overrideDict[stuid];
// TODO: log!
}
if (inited) {
// new
ballot.tx = tokenUtils.generateTxString();
return ballot.save();
}
// not new, check (1) commited, (2) consistency
if (ballot.commit) {
logRequest(req, resp, 'verbose', `already voted: ${ballot.uid}`);
return Promise.reject(l10nMsg['ALREADY_VOTED']);
}
if (ballot.serial != recordedSerial ||
ballot.client_id != resp.locals.client.id) {
logRequest(req, resp, 'verbose', `ballot info inconsistent: ${ballot.uid}`);
return Promise.reject(l10nMsg['BALLOT_INFO_INCONSISTENT']);
}
return Promise.resolve(ballot);
});
})
.then(ballot => {
// null if error
if (ballot) {
ret.can_vote = true;
ret.tx = ballot.tx;
}
resp.json(ret);
})
.catch(err => (typeof err == 'string'), errStr => {
// XXX, WTF String class
ret.msg = errStr;
resp.status(400).json({
ok: false,
msg: errStr,
can_vote: false
});
return null;
})
.catch(promiseErrorHandler(next));
});
app.post('/commit', requestHook, (req, resp, next) => {
let ret = resp.locals.ret;
if (!req.body.tx) {
ret.msg = l10nMsg['MISSING_TX'];
return resp.status(400).json(ret);
}
models.Ballot.find({
where: {
tx: req.body.tx,
client_id: resp.locals.client.id,
commit: { [models.db.Op.not]: true }
},
}).then(ballot => {
if (!ballot) {
// tx
ret.msg = l10nMsg['TX_NOT_FOUND'];
logRequest(req, resp, 'verbose', `tx not found: ${req.body.tx}`);
return Promise.reject(null);
}
// need refactoring
return ballot.set('commit', true).save()
.then(() => {
ret.ok = true;
resp.json(ret);
});
})
.catch(e => e == null, () => {
// do nothing to let everything pass through
resp.status(403).json(ret);
})
.error(promiseErrorHandler(next));
});
app.post('/log', requestHook, (req, resp, next) => {
let ret = resp.locals.ret;
if (typeof req.body != 'string') {
ret.msg = 'Unsupported media type';
return resp.status(415).json(ret);
}
let lines = req.body.split('\n');
models.Log.create({
level: 'info',
tag: 'client-log',
content: req.body,
client_id: resp.locals.client.id
}).then(logObj => {
ret.recv_lines = lines.length;
resp.json(ret);
}).catch(promiseErrorHandler(next));
});
app.use((err, req, resp, next) => {
errMsg = app.get('debug') ? (err.message || err) : 'Internal server error QQ';
models.Log.log('error', 'express-server', err.stack || err);
let ret = {
ok: false,
msg: errMsg
};
// XXX: a track code can be added here to help recognizing log entry
// corresponding to client
if (app.get('debug')) {
ret.stacktrace = err.stack;
}
resp.status(500).json(ret);
});
module.exports = app;