-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rb
More file actions
65 lines (47 loc) · 1.3 KB
/
main.rb
File metadata and controls
65 lines (47 loc) · 1.3 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
require "json"
require "mongo"
require 'bcrypt'
require "sinatra"
require "open-uri"
require "net/http"
set :bind, "0.0.0.0"
FlaptusDB = Mongo::Client.new(ENV["mongouri"], database: "flaptus")[:leaderboard]
def get_scores
FlaptusDB.find({}, sort: { score: -1 }).map do |col|
{
score: col[:score],
username: col[:username]
}
end
end
get "/" do
@scores = get_scores
erb :index
end
get "/api/leaderboard" do
get_scores.to_json
end
post "/api/newuser" do
return halt 403, "Invalid secret provided" if params[:secret] != ENV["SECRET"]
username = params[:username]
return halt 400, "Username length > 12" if username.length > 12
return halt 400, "Username not available" if FlaptusDB.find({ username_low: username.downcase }).first != nil
token = BCrypt::Password.create(username + ENV["SECRET"]).to_s
FlaptusDB.insert_one({
score: 0,
token: token,
username: username,
username_low: username.downcase
})
token
end
post "/api/newscore" do
return halt 403, "Invalid secret provided" if params[:secret] != ENV["SECRET"]
score = params[:score].to_i
token = params[:token]
user = FlaptusDB.find({ token: token }).first
return 400 if user == nil
return 200 if score <= user[:score]
FlaptusDB.update_one({ token: token }, { "$set" => { score: score } })
200
end