-
Notifications
You must be signed in to change notification settings - Fork 457
Expand file tree
/
Copy pathbase_controller.rb
More file actions
76 lines (60 loc) 路 2.12 KB
/
Copy pathbase_controller.rb
File metadata and controls
76 lines (60 loc) 路 2.12 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
66
67
68
69
70
71
72
73
74
75
76
class Api::BaseController < ApplicationController
prepend_before_action :require_api_authentication
helper :all
private
def require_api_authentication
return if user_signed_in?
if (user = user_from_token)
sign_in user, store: false
elsif %w[api/v1/version api/v2/version].include?(params["controller"])
# Version endpoints are public
nil
elsif request.headers.key?("Authorization") || request.headers.key?("X-User-Token")
# The user is trying to authenticate with a bad token
head :unauthorized
elsif !Settings.allow_anonymous
# When anonymous access is disabled, API endpoints require authentication.
head :unauthorized
elsif params["controller"] == "api/v2/pushes"
if %w[audit active expired notify_by_email].include?(params["action"])
# These v2 endpoints require a valid token
head :unauthorized
end
elsif request.path.start_with?("/p")
if %w[audit active expired].include?(params["action"])
# These paths require a valid token
head :unauthorized
end
elsif request.path.start_with?("/f")
if %w[create audit active expired].include?(params["action"])
# These paths require a valid token
head :unauthorized
end
elsif request.path.start_with?("/r")
if %w[create audit active expired].include?(params["action"])
# These paths require a valid token
head :unauthorized
end
else
head :unauthorized
end
end
def token_from_header
# Legacy PWPUSH API token
if request.headers.key?("X-User-Email") && request.headers.key?("X-User-Token")
return request.headers["X-User-Token"]
end
# Authorization: Bearer <token>
request.headers.fetch("Authorization", "").split(" ").last
end
def user_from_token
api_token = token_from_header
return nil if api_token.blank?
User.find_by(authentication_token: api_token)
end
rescue_from ActionController::ParameterMissing do |exception|
respond_to do |format|
format.json { render json: {error: exception.message}, status: :bad_request }
end
end
end