forked from geordanr/xwing-backend
-
Notifications
You must be signed in to change notification settings - Fork 3
/
web.rb
433 lines (376 loc) · 12.7 KB
/
web.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
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
424
425
426
427
428
429
430
431
432
433
require 'time'
require 'sinatra/base'
require 'rack/cors'
require 'haml'
require 'couchrest'
require 'json'
require 'uuid'
require 'omniauth'
require 'omniauth-google-oauth2'
# require 'omniauth-facebook'
require 'omniauth-twitter'
require 'omniauth-discord'
PROVIDERS = {
:google_oauth2 => [ ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'] ],
# :facebook => [ ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'] ],
:twitter => [ ENV['TWITTER_KEY'], ENV['TWITTER_SECRET'] ],
:discord => [ ENV['DISCORD_CLIENT_ID'], ENV['DISCORD_CLIENT_SECRET'] ],
}
VALID_SETTINGS = [
'language',
'hugeShipMovedWarningSeen',
'showInitiativeInFrontOfPilotName',
'enableBanList'
]
INTERESTING_HEADERS = [
'HTTP_ACCEPT_LANGUAGE',
]
class XWingSquadDatabase < Sinatra::Base
# Config
configure do
enable :method_override
# https://github.com/sinatra/sinatra/issues/518
set :protection, :except => :json_csrf
end
configure :production do
set :db, CouchRest.database(ENV['CLOUDANT_URL'])
end
configure :development do
begin
File.open('dev_cloudant.url') do |f|
set :db, CouchRest.database(f.read.strip)
end
rescue
set :db, CouchRest.database(ENV['CLOUDANT_DEV_URL'])
end
end
# Middleware
use Rack::Session::Cookie, :expire_after => 2592000,
:secret => ENV['SESSION_SECRET'],
:same_site => :none,
:secure => true
use OmniAuth::Builder do
PROVIDERS.each do |provider_name, provider_args|
provider provider_name, *provider_args
end
end
use Rack::Cors do
ENV['ALLOWED_ORIGINS'].split do |origin|
allow do
origins origin
resource '*', :credentials => true,
:methods => [ :get, :post, :put, :delete ],
:headers => :any
end
end
end
# Auth stuff
helpers do
def require_authentication()
if session.has_key? :u
begin
user_doc = settings.db.get session[:u]
if user_doc.nil?
puts "User #{session[:u].inspect} not found"
halt 401, 'Invalid user; re-authenticate with OAuth'
end
rescue => e
puts "Could not get user doc: #{e}"
end
env['xwing.user'] = User.fromDoc(user_doc)
else
halt 401, 'Authentication via OAuth required'
end
end
def name_is_available?(name)
settings.db.view('squads/byUserName', { :key => [ env['xwing.user']['_id'], name ] })['rows'].empty?
end
def json(data)
content_type :json
if data.instance_of? Hash
data.to_json
else
{ :data => data }.to_json
end
end
def get_collection()
collection = Collection.new(env['xwing.user']['_id'], {}, {}, {})
begin
collection_doc = settings.db.get(collection['_id'])
if collection_doc.nil?
# If no collection already exists for the logged in user, create a new empty one.
res = settings.db.save_doc(collection)
collection_doc = settings.db.get(res['id'])
end
rescue => e
puts "Error getting collection for user #{env['xwing.user']['_id']}: #{e}"
halt 500
end
Collection.fromDoc(collection_doc)
end
end
before '/squads/*' do
require_authentication
end
# Support both GET and POST for callbacks
%w(get post).each do |method|
send(method, "/auth/:provider/callback") do
user = User.new(env['omniauth.auth']['provider'], env['omniauth.auth']['uid'])
# Check if user exists
begin
user_doc = settings.db.get user['_id']
session[:u] = user_doc['_id']
rescue
# If not, add it
res = settings.db.save_doc(user)
session[:u] = res['id']
end
haml :auth_success
end
end
get '/auth/failure' do
halt 403, 'Authentication failed'
end
get '/auth/logout' do
session.delete :u
json :message => 'Logged out; reauthenticate with OAuth'
end
# App routes
get '/' do
json :welcome => 'Yet Another X-Wing Database Backend'
end
get '/headers' do
data = {}
INTERESTING_HEADERS.each do |header|
data[header] = request.env[header]
end
json :headers => data
end
get '/settings' do
session[:settings] = {} if session[:settings].nil?
settings = session[:settings]
json :settings => settings
end
put '/settings' do
session[:settings] = {} if session[:settings].nil?
settings = session[:settings]
settings_set = {}
params.each_pair do |setting, value|
if VALID_SETTINGS.member? setting
settings[setting] = settings_set[setting] = value
end
end
json :set => settings_set
end
delete '/settings/:setting' do
setting = params[:setting]
if VALID_SETTINGS.member? setting
session[:settings] = {} if session[:settings].nil?
settings = session[:settings]
settings.delete setting if settings.has_key? setting
end
json :deleted => setting
end
get '/methods' do
json :methods => PROVIDERS.keys
end
# # Unprotected; everyone can view the full list
# get '/all' do
# out = {
# 'Rebel Alliance' => [],
# 'Galactic Empire' => [],
# 'Scum and Villainy' => [],
# 'Resistance' => [],
# 'First Order' => [],
# 'Galactic Republic' => [],
# 'Separatist Alliance' => [],
# }
# settings.db.view('squads/list', { :reduce => false })['rows'].each do |row|
# _, faction, name = row['key']
# out[faction].push({
# :id => row['id'],
# :name => name,
# :serialized => row['value']['serialized'] || nil,
# :additional_data => row['value']['additional_data'] || nil,
# })
# end
# json out
# end
get '/squads/list' do
out = {
'Rebel Alliance' => [],
'Galactic Empire' => [],
'Scum and Villainy' => [],
'Resistance' => [],
'First Order' => [],
'Galactic Republic' => [],
'Separatist Alliance' => [],
'All' => [],
}
settings.db.view('squads/list', { :reduce => false, :startkey => [ env['xwing.user']['_id'] ], :endkey => [ env['xwing.user']['_id'], {}, {} ] })['rows'].each do |row|
_, faction, name = row['key']
out[faction].push({
:id => row['id'],
:name => name,
:serialized => row['value']['serialized'] || nil,
:additional_data => row['value']['additional_data'] || nil,
})
end
json out
end
put '/squads/new' do
name = params[:name].strip
if name_is_available? name
new_squad = Squad.new(env['xwing.user']['_id'], params[:serialized].strip, name, params[:faction].strip, params[:additional_data])
begin
res = settings.db.save_doc(new_squad)
json :id => res['id'], :success => true, :error => nil
rescue
json :id => nil, :success => false, :error => 'Something bad happened saving that squad, try again later'
end
else
json :id => nil, :success => false, :error => 'You already have a squad with that name'
end
end
delete '/squads/:id' do
id = params[:id]
begin
squad_doc = settings.db.get(id)
rescue
json :id => nil, :success => false, :error => 'Something bad happened fetching that squad, try again later'
end
if squad_doc['user_id'] != env['xwing.user']['_id']
json :id => nil, :success => false, :error => "You don't own that squad"
else
begin
squad_doc.destroy
json :success => true, :error => nil
rescue
json :id => nil, :success => false, :error => 'Something bad happened deleting that squad, try again later'
end
end
end
post '/squads/namecheck' do
name = params[:name].strip
json :available => name_is_available?(name)
end
post '/squads/:id' do
id = params[:id].strip
begin
squad = Squad.fromDoc(settings.db.get(id))
rescue
json :id => nil, :success => false, :error => 'Something bad happened fetching that squad, try again later'
end
if squad['user_id'] != env['xwing.user']['_id']
json :id => nil, :success => false, :error => "You don't own that squad"
else
name = params[:name].strip
if name != squad['name'] and not name_is_available? name
json :id => nil, :success => false, :error => 'You already have a squad with that name'
else
squad.update({
'name' => name,
'serialized' => params[:serialized].strip,
'faction' => params[:faction].strip,
'additional_data' => params[:additional_data],
})
begin
settings.db.save_doc(squad)
json :id => squad['_id'], :success => true, :error => nil
rescue
json :id => nil, :success => false, :error => 'Something bad happened saving that squad, try again later'
end
end
end
end
get '/ping' do
require_authentication
json :success => true
end
get '/collection' do
require_authentication
collection = get_collection
json :collection => {
'expansions' => collection['expansions'],
'singletons' => collection['singletons'],
'checks' => collection['checks']
}
end
post '/collection' do
require_authentication
collection = get_collection
collection['expansions'] = params[:expansions]
collection['singletons'] = params[:singletons]
collection['checks'] = params[:checks]
begin
_ = settings.db.save_doc(collection)
json :success => true, :error => nil
rescue => e
puts "Error saving collection for user #{env['xwing.user']['_id']}: #{e}"
halt 500
end
end
# Demo
get '/protected' do
require_authentication
"It's a secret to everyone!"
end
get '/haml' do
haml :auth_success
end
end
class User < Hash
def initialize(provider, uid)
self['_id'] = "user-#{provider}-#{uid}"
self['type'] = 'user'
end
def self.fromDoc(doc)
new_obj = self.new(nil, nil)
new_obj.update(doc)
new_obj
end
def to_s
"#<User id=#{self['_id']}>"
end
end
class Squad < Hash
def initialize(user_id, serialized_str, name, faction, additional_data)
self['_id'] = "squad_#{UUID.generate}"
self['type'] = 'squad'
self['user_id'] = user_id
self['serialized'] = serialized_str
self['name'] = name
self['faction'] = faction
begin
self['additional_data'] = additional_data.to_hash
rescue
self['additional_data'] = {}
end
end
def self.fromDoc(doc)
new_obj = self.new(nil, nil, nil, nil, nil)
new_obj.update(doc)
new_obj
end
def to_s
"#<Squad user_id=#{self['_id']}, faction=#{self['faction']}, name=#{self['name']}>"
end
end
class Collection < Hash
def initialize(user_id, expansions, singletons, checks)
self['_id'] = "collection_#{user_id}"
self['type'] = 'collection'
self['user_id'] = user_id
self['expansions'] = expansions
self['singletons'] = singletons
self['checks'] = checks
end
def self.fromDoc(doc)
new_obj = self.new(nil, nil, nil, nil)
new_obj.update(doc)
new_obj
end
def to_s
"#<Collection id=#{self['_id']}, user_id=#{self['user_id']}, expansions=#{self['expansions']}, singletons=#{self['singletons']}, checks=#{self['checks']}>"
end
end