-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.rb
345 lines (258 loc) · 7.11 KB
/
server.rb
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
require 'sinatra'
require 'redis'
require 'json'
require 'set'
require 'fast_secure_compare'
$redis = Redis.new
$redis.set("votelock", "editing")
#`set :public_folder, File.dirname(__FILE__) + '/public'
get '/' do
redirect '/index.html'
end
def candidates_for(election)
$redis.hgetall("election:#{election}").delete_if do |k,v|
not k.match /[0-9]+/
end.invert # end up with {"u555555" => "1"}
end
before '/admin/*' do
given_token = params["token"] || ""
actual_token = ENV["AUTH_TOKEN"] || ""
if not FastSecureCompare.compare(actual_token, given_token)
status 401
halt
end
end
def locked_req!
if $redis.get("votelock") == "voting"
status 403
halt
end
end
def locked_pub_req!
if $redis.get("votelock") != "voting"
status 403
halt
end
end
get('/admin/votelock') do
content_type 'text/json'
JSON.generate({state: $redis.get("votelock")})
end
post('/admin/votelock') do
input = JSON.parse(request.body.read)
$redis.set("votelock", input["state"])
200
end
get('/admin/candidates') do
content_type 'text/json'
payload = $redis.smembers("candidates").map do |uid|
{
id: uid,
elections: $redis.smembers("elections:#{uid}")
}.merge($redis.hgetall("candidate:#{uid}"))
end
JSON.generate(payload)
end
post('/admin/candidates') do
locked_req!
input = JSON.parse(request.body.read)
input.each {|n| return 500 unless n["id"] }
# Clear out the current candidates
$redis.smembers("candidates").each do |n|
$redis.smembers("elections").each do |e|
candidates_for(e).each do |c,pos|
$redis.hdel("election:#{e}", c)
end
end
$redis.del("candidate:#{n}")
$redis.del("elections:#{n}")
end
$redis.del("candidates")
input.each {|n| $redis.sadd("candidates", n["id"]) }
input.each do |n|
$redis.hmset("candidate:#{n["id"]}", "name", n["name"])
# add each candidate to their allotted elections
n["elections"].each do |e|
$redis.sadd("elections:#{n["id"]}", e)
$redis.hmset("election:#{e}", candidates_for(e).length + 1, n["id"])
end
end
200
end
get('/admin/elections') do
content_type 'text/json'
payload = $redis.smembers("elections").map do |election|
{
name: election,
positions: $redis.hget("election:#{election}", "positions")
}
end
JSON.generate(payload)
end
post('/admin/elections') do
locked_req!
input = JSON.parse(request.body.read)
input.each do |election|
$redis.sadd("elections", election["name"])
$redis.hmset("election:#{election["name"]}",
"positions", election["positions"]
)
end
200
end
get('/admin/votingcodes') do
content_type 'text/json'
payload = $redis.smembers("votingcodes").map do |code|
info = $redis.hgetall("votingcode:#{code}")
{
code: code,
used: info["used"],
new: info["new"]
}
end
JSON.generate(payload)
end
get('/admin/votingcodes/more') do
input = $redis.get("votingcode_increment").to_i
$redis.set("votingcode_increment", 0) unless input
10.times do
code = (Digest::SHA2.new() << input.to_s + Time.now.to_s).to_s.slice(0,7)
if $redis.sismember("votingcodes", code)
input += 1
redo
end
$redis.sadd("votingcodes", code)
$redis.hmset("votingcode:#{code}",
"code", code,
"token", nil,
"used", false,
"new", true
)
input += 1
end
$redis.set("votingcode_increment", input)
200
end
post('/admin/votingcodes') do
locked_req!
input = JSON.parse(request.body.read)
input.each do |n|
$redis.sadd("votingcodes", n["code"])
$redis.hmset("votingcode:#{n["code"]}",
"code", n["code"],
"used", n["used"],
"new", n["new"]
)
end
200
end
get('/admin/votes.blt') do
content_type 'text/plain'
cached = $redis.get("cache:votes.blt")
return cached if cached
output = ""
# For each election
$redis.smembers("elections").each do |election|
output += "#{election}\n\n"
positions = $redis.hget("election:#{election}", "positions")
# Work out what order the candidates are in
candidates = candidates_for(election)
output += "#{candidates.length} #{positions}\n"
votes = $redis.lrange("votes:#{election}", 0, $redis.llen("votes:#{election}")).sort
counter = 0
votes.length.times do |i|
if votes[i] == votes[i+1]
counter += 1
elsif counter > 0 # there have been a few
output += "#{counter} #{votes[i]} 0\n"
counter = 0
else
counter = 0
output += "1 #{votes[i]} 0\n"
end
end
output += "0\n"
candidates.sort {|a,b| a[1] <=> b[1] }.each do |i|
output += "\"#{i[0]}\"\n"
end
output += "\n\n"
end
$redis.set("cache:votes.blt", output)
output
end
post('/votingcode') do
locked_pub_req!
content_type 'text/json'
input = JSON.parse(request.body.read)
return 400 unless input["votingcode"]
if settings.development?
$redis.sadd("votingcodes", input["votingcode"])
$redis.hmset("votingcode:#{input["votingcode"]}",
"used", false,
"new", true,
"code", input["votingcode"]
)
end
return 404 unless $redis.sismember("votingcodes", input["votingcode"])
code = $redis.hgetall("votingcode:#{input["votingcode"]}")
return 404 if code["used"] == "true"
code["token"] = (Digest::SHA2.new << code["code"] + Time.now.to_s).to_s
$redis.hmset("votingcode:#{code["code"]}",
"used", true,
"token", code["token"]
)
$redis.sadd("tokens", code["token"])
JSON.generate({token: code["token"]})
end
get('/elections') do
locked_pub_req!
content_type 'text/json'
payload = $redis.smembers("elections").map do |n|
candidates = candidates_for(n).map do |id,pos|
{
"name" => $redis.hget("candidate:#{id}", "name"),
"id" => id
}
end
{
election: n,
positions: $redis.hget("election:#{n}", "positions"),
candidates: candidates
}
end
JSON.generate(payload)
end
post('/votes') do
locked_pub_req!
if (not $redis.sismember("tokens", params["token"])) and (not settings.development?)
return 403
end
input = JSON.parse(request.body.read)
# check election votes are numbered 1..no_candidates inclusive
input.each do |n|
return 400 if not ["votes"]
vote_set = n["votes"].map {|v| v["rank"].to_i}.to_set
return 400 if vote_set.length != n["votes"].length or #no repeat numbers
vote_set.min != 1 or #starts at pref 1
vote_set.max != n["votes"].length # 1..length inclusive
end
input.each do |n|
return 400 if not n["election"]
return 400 if not $redis.sismember("elections", n["election"])
votes = []
candidates = candidates_for(n["election"])
n["votes"].map do |c|
return 400 if not c["id"]
return 400 if not candidates[c["id"]]
return 400 if not c["rank"].match(/[0-9]+/)
votes[ candidates[c["id"]].to_i ] = c["rank"]
end
votes.delete_if {|n| not n } # clear nils
votes = votes.reduce("") {|memo, obj| memo += obj + " " }.strip
$redis.lpush("votes:#{n["election"]}", votes)
end
# invalidate the BLT cache
$redis.del("cache:votes.blt")
$redis.srem("tokens", params["token"])
200
end