This repository has been archived by the owner on Aug 13, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathgaps_server.rb
executable file
·470 lines (387 loc) · 11.8 KB
/
gaps_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
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
#!/usr/bin/env ruby
require File.expand_path('../lib/gaps', File.dirname(__FILE__))
require 'optparse'
require 'json'
require 'rack-flash'
require 'puma'
require 'einhorn/worker'
module Gaps
class GapsServer < Sinatra::Base
set :server, :puma_inherit
set :server_settings do
{
FD: (fd = ENV['EINHORN_FD_0']) ? fd.to_i : nil
}
end
set :root, File.expand_path('../..', __FILE__)
set :bind, '0.0.0.0'
set :port do
configatron.port
end
include Chalk::Log
include Gaps::Third::ERBUtils::Autoescape
use Gaps::Third::Healthcheck
use Sinatra::CommonLogger
### Authentication
before do
if user_id = session['user_id']
@user = Gaps::DB::User.find(user_id)
unless @user
log.error("Can't find user object for logged-in user_id", user_id: user_id)
log_out!
end
end
if logged_in?
@google_client = @user.client
else
@google_client = Gaps::Requestor.base_client
end
end
def logged_in?
!!@user
end
def log_in!(user_id)
session['user_id'] = user_id
end
def log_out!
session.delete('user_id')
end
set(:auth) do |requirement|
condition do
if requirement && !logged_in?
redirect('/login', 303)
elsif !requirement && logged_in?
redirect('/', 303)
end
end
end
def die(msg)
flash.now[:error] = msg
halt erb(:error)
end
get '/' do
redirect '/subs'
end
get '/opensearch.xml' do
content_type :xml
erb :opensearch, layout: nil
end
get '/status', auth: false do
if logged_in?
status 200
"OK"
else
status 401
"UNAUTHORIZED"
end
end
post '/refresh', auth: true do
Gaps::DB::Cache.purge!
Gaps::DB::Group.refresh
redirect '/'
end
get '/login', auth: false do
@has_lister = !!Gaps::DB::User.lister
erb :login
end
post '/login_as', auth: true do
die("Must be signed in as an admin") unless @user.admin?
die("Must provide a username") unless username = params[:username]
user = Gaps::DB::User.find_or_create_by_email("#{username}@#{configatron.info.domain}")
log_in!(user._id)
redirect '/'
end
get '/login/gafyd' do
type = params[:type] || 'normal'
authorization_options = {access_type: :online}
scopes = configatron.oauth.common_scopes.dup
case type
when 'normal'
when 'lister'
authorization_options[:access_type] = :offline
authorization_options[:approval_prompt] = :force
scopes += configatron.oauth.lister_scopes
else
die "Invalid login type: #{type.inspect}"
end
# Save this for later
session['gafyd'] = {
'type' => type,
'access_type' => authorization_options[:access_type].to_s
}
@google_client.authorization.scope = scopes.join(' ')
uri = @google_client.authorization.authorization_uri(authorization_options).to_s
redirect(uri)
end
get '/logout', auth: true do
flash.now[:notice] = 'Click the logout button to logout.'
erb :notice
end
post '/logout', auth: true do
log_out!
flash.now[:notice] = 'You have been logged out.'
erb :notice
end
get '/oauth2callback', auth: false do
die "There was an error trying to complete the OAuth flow: #{params[:error]}" if params[:error]
# In case the page was refreshed
redirect '/login' unless params[:code]
die "You seem to have corrupted session state. Try logging in again?" unless gafyd = session['gafyd']
# It'd be nice to figure out what scopes I actually have, but
# it's not clear if there's a good way to do it.
@google_client.authorization.code = params[:code]
begin
@google_client.authorization.fetch_access_token!
rescue StandardError => e
log.error("Couldn't complete OAuth flow", e)
die "There was an error while completing the OAuth flow: #{e}"
end
begin
id = Gaps::DB::User.persist(@google_client, gafyd['type'], gafyd['access_type'])
rescue Gaps::DB::User::InvalidUser => e
log.error("Signed in as an invalid user", e)
die "There was an error while completing the OAuth flow: #{e}"
rescue Google::APIClient::ClientError => e
if gafyd['type'] == 'lister'
e.message << " (HINT: are you sure you're a domain admin?)"
end
die "There was an error completing the OAuth flow: #{e}"
raise
end
log_in!(id)
log.info("Successfully logged in", user_id: id)
redirect('/')
end
## Subscriptions
get '/subs', auth: true do
if !Gaps::DB::State.initialized?
@group_count = Gaps::DB::Group.count
@cache_count = Gaps::DB::Cache.count
return erb(:subs_initializing)
end
@groups = Gaps::DB::Group.categorized(@user)
erb :subs, :locals => {:group_partial => :_subscription_group}
end
post '/subs', auth: true do
# TODO: bring back automated request logging
log.info('Updating subscriptions', group: params[:group], user: @user.email)
updates = 0
params[:group].each do |group_id, group_conf|
category = group_conf[:category].to_s
if category.length > 0
updates += 1
group = Gaps::DB::Group.find(group_id)
group.category = category
group.save!
end
# TODO: refactor this
member = !!group_conf[:member]
was_member = group_conf[:was_member] == 'true'
if member != was_member
group ||= Gaps::DB::Group.find(group_id)
if !group.viewable?(@user)
die("Trying to update subscription to a group you do not have permission to access: #{group_id}")
end
if member
@user.requestor.add_to_group(group.group_email)
else
@user.requestor.remove_from_group(group.group_email)
end
end
end
flash[:notice] = "Updated the category of #{updates} groups"
redirect '/'
end
## Filters
get '/filters', auth: true do
@groups = Gaps::DB::Group.categorized(@user, true)
erb :filters
end
get '/filters/generate', auth: true do
generic_lists = Gaps::Filter.translate_to_gmail_britta_filters(@user.filters)
user_name = @user.email.sub(/@.*/, '')
# Set non-xml content-type so Safari won't attempt to open the file.
# (Yes, safari and its "Open safe files" default are awful.)
content_type 'application/octet-stream'
headers['Content-Disposition'] = "attachment; filename=\"#{user_name}-gmail-filters.xml\""
Gaps::Filter.generate_filter_xml(@user.all_emails, generic_lists)
end
get '/filters/source', auth: true do
content_type :text
erb :filter_source, :layout => false
end
post '/filters/upload', auth: true do
failures = Gaps::Filter.upload_to_gmail(@user)
headers['Content-Type'] = "application/json"
if failures.length > 0
flash[:error] = "Failed to upload #{failures.length} filters"
else
flash[:notice] = "Successfully uploaded filters"
end
redirect '/filters'
end
## Suggested Sets
get '/sets', auth: true do
@sets = Gaps::DB::Set.find_each
erb :sets
end
post '/sets', auth: true do
set_id = params[:set]
log.info('Adding user to subscription set', set: set_id, user: @user.email)
Gaps::DB::Set.find(set_id).groups_.each do |group|
membership = @user.group_member?(group)
through_list = @user.group_member_through_list(group)
direct_membership = membership && !through_list
if !direct_membership
if !group.viewable?(@user)
die("Trying to update subscription to a group you do not have permission to access: #{group._id}")
end
@user.requestor.add_to_group(group.group_email)
end
end
@user.sets << set_id
@user.save
redirect '/'
end
get '/sets/:id', auth: true do
if params[:id] != 'new'
@set = Gaps::DB::Set.find(params[:id])
return not_found unless @set
end
@groups = Gaps::DB::Group.categorized(@user)
erb :set, :locals => {:group_partial => :_set_group}
end
post '/sets/:id', auth: true do
args = {
name: params[:name],
description: params[:description],
groups: params[:group].keys,
}
if params[:id] == 'new'
Gaps::DB::Set.new(args).save
else
set = Gaps::DB::Set.find(params[:id])
return not_found unless set
old_groups = set.groups
args.each do |key, value|
set.send(:"#{key}=", value)
end
set.save
set.notify_update(old_groups)
end
redirect '/sets'
end
## AJAXy things:
post '/ajax/groups/:group/move', auth: true do
content_type :json
category = params[:category]
if group = Gaps::DB::Group.find(params[:group])
log.info('Moving group categories', group: group._id, category: category)
group.move_category(category)
{'group' => params[:group], 'category' => category}.to_json
else
log.info('Group not found', group: params[:group])
not_found
end
end
post '/ajax/users/:user/alternate_email', auth: true do
unless user = Gaps::DB::User.find(params[:user])
not_found
end
user.alternate_emails << params[:email]
user.alternate_emails.uniq!
user.save
halt 201
end
# TODO: make this actually RESTful
post '/ajax/users/:user/alternate_email/delete', auth: true do
unless user = Gaps::DB::User.find(params[:user])
not_found
end
user.alternate_emails.delete(params[:email])
user.save
halt 201
end
post '/ajax/filters', auth: true do
@user.set_filters(params[:group])
@user.save
halt 201
end
helpers do
# Insert an hidden tag with the anti-CSRF token into your forms.
def csrf_tag
Rack::Csrf.csrf_tag(env)
end
# Return the anti-CSRF token
def csrf_token
Rack::Csrf.csrf_token(env)
end
# Return the field name which will be looked for in the requests.
def csrf_field
Rack::Csrf.csrf_field
end
def default_filter(user, group)
group.default_filter_label
end
def active_if_on(path)
if request.path_info == path
'active'
else
''
end
end
end
end
end
def einhorn_main
main
end
def main
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options]"
opts.on('-v', '--verbosity', 'Verbosity of debugging output') do
$log.level -= 1
end
opts.on('-h', '--help', 'Display this message') do
puts opts
exit(1)
end
end
optparse.parse!
if ARGV.length != 0
puts optparse
return 1
end
Gaps.init
Thread.new do
# Start out just by warming the transitive closure cache, so we
# have all of the group memberships warm and up to date.
Gaps::DB::Group.boot
while true
sleep(10 * 60)
# Every 10 minutes, go and refresh the list of all lists -- this
# call then executes `warm_transitive_closure_cache`.
Gaps::DB::Group.refresh_if_able
end
end
Gaps::GapsServer.use(Rack::Session::Cookie, key: 'gaps',
secret: configatron.session.secret,
secure: configatron.session.secure,
coder: Rack::Session::Cookie::Base64::JSON.new,
httponly: true,
expire_after: 12 * 30 * 7 * 24 * 60 * 60, # 1 year
)
Gaps::GapsServer.use(Rack::Flash)
Einhorn::Worker.ack
Gaps::GapsServer.run!
return 0
end
if $0 == __FILE__
ret = main
begin
exit(ret)
rescue TypeError
exit(0)
end
end