-
Notifications
You must be signed in to change notification settings - Fork 17
/
routes.rb
83 lines (73 loc) · 2.75 KB
/
routes.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
module Warden
module GitHub
module Rails
module Routes
# Enforces an authenticated GitHub user for the routes. If not
# authenticated, it initiates the OAuth flow.
#
# Team and organization memberships can be checked by specifying a hash
# such as `team: 'foobar'` or `org: 'my_company'`.
def github_authenticate(scope=nil, options={}, &routes_block)
github_constraint(scope, options, routes_block) do |warden, scope|
warden.authenticate!(scope: scope)
end
end
# The routes will only be visible to authenticated GitHub users. When
# not authenticated, it does not initiate the OAuth flow.
#
# Team and organization memberships can be checked by specifying a hash
# such as `team: 'foobar'` or `org: 'my_company'`.
def github_authenticated(scope=nil, options={}, &routes_block)
github_constraint(scope, options, routes_block) do |warden, scope|
warden.authenticated?(scope: scope)
end
end
# The routes will only be visible to all but authenticated GitHub users.
#
# This constraint currently does not check for memberships since of its
# limited usage.
def github_unauthenticated(scope=nil, options={}, &routes_block)
github_constraint(scope, options, routes_block) do |warden, scope|
not warden.authenticated?(scope: scope)
end
end
private
def github_constraint(scope, options, routes_block, &block)
options, scope = scope, nil if scope.is_a? Hash
scope ||= Rails.default_scope
constraint = lambda do |request|
warden = request.env['warden']
if block.call(warden, scope)
if (user = warden.user(scope))
evaled_options = github_eval_options(options, request)
github_enforce_options(user, evaled_options)
else
true
end
end
end
constraints(constraint, &routes_block)
end
def github_enforce_options(user, options)
if (teams = options[:team])
Array(teams).any? { |team| user.team_member?(Rails.team_id(team)) }
elsif (org = options[:org] || options[:organization])
user.organization_member?(org)
else
true
end
end
def github_eval_options(options, request)
Hash[options.map { |k,v|
if v.is_a?(Proc)
[k, v.call(request)]
else
[k, v]
end
}]
end
end
end
end
end
ActionDispatch::Routing::Mapper.send(:include, Warden::GitHub::Rails::Routes)