]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api_controller.rb
27f262d00341aa8cabfcf7e5d54e6c11f0541c95
[rails.git] / app / controllers / api_controller.rb
1 class ApiController < ApplicationController
2   skip_before_action :verify_authenticity_token
3
4   before_action :check_api_readable
5
6   around_action :api_call_handle_error, :api_call_timeout
7
8   private
9
10   ##
11   # Set allowed request formats if no explicit format has been
12   # requested via a URL suffix. Allowed formats are taken from
13   # any HTTP Accept header with XML as the default.
14   def set_request_formats
15     unless params[:format]
16       accept_header = request.headers["HTTP_ACCEPT"]
17
18       if accept_header
19         # Some clients (such asJOSM) send Accept headers which cannot be
20         # parse by Rails, for example:
21         #
22         #   Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
23         #
24         # where both "*" and ".2" as a quality do not adhere to the syntax
25         # described in RFC 7231, section 5.3.1, etc.
26         #
27         # As a workaround, and for back compatibility, default to XML format.
28         mimetypes = begin
29           Mime::Type.parse(accept_header)
30         rescue Mime::Type::InvalidMimeType
31           Array(Mime[:xml])
32         end
33
34         # Allow XML and JSON formats, and treat an all formats wildcard
35         # as XML for backwards compatibility - all other formats are discarded
36         # which will result in a 406 Not Acceptable response being sent
37         formats = mimetypes.map do |mime|
38           if mime.symbol == :xml || mime == "*/*" then :xml
39           elsif mime.symbol == :json then :json
40           end
41         end
42       else
43         # Default to XML if no accept header was sent - this includes
44         # the unit tests which don't set one by default
45         formats = Array(:xml)
46       end
47
48       request.formats = formats.compact
49     end
50   end
51
52   def authorize(errormessage: "Couldn't authenticate you", skip_terms: false)
53     # make the current_user object from any auth sources we have
54     setup_user_auth(:skip_terms => skip_terms)
55
56     # handle authenticate pass/fail
57     unless current_user
58       # no auth, the user does not exist or the password was wrong
59       render :plain => errormessage, :status => :unauthorized
60
61       false
62     end
63   end
64
65   def current_ability
66     # Use capabilities from the oauth token if it exists and is a valid access token
67     if doorkeeper_token&.accessible?
68       user = User.find(doorkeeper_token.resource_owner_id)
69       ApiAbility.new(user, doorkeeper_token)
70     else
71       ApiAbility.new(nil, nil)
72     end
73   end
74
75   def deny_access(_exception)
76     if doorkeeper_token
77       set_locale
78       report_error t("oauth.permissions.missing"), :forbidden
79     elsif current_user
80       head :forbidden
81     else
82       head :unauthorized
83     end
84   end
85
86   def gpx_status
87     status = database_status
88     status = "offline" if status == "online" && Settings.status == "gpx_offline"
89     status
90   end
91
92   ##
93   # sets up the current_user for use by other methods. this is mostly called
94   # from the authorize method, but can be called elsewhere if authorisation
95   # is optional.
96   def setup_user_auth(skip_terms: false)
97     logger.info " setup_user_auth"
98     # try and setup using OAuth
99     self.current_user = User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token&.accessible?
100
101     # have we identified the user?
102     if current_user
103       # check if the user has been banned
104       user_block = current_user.blocks.active.take
105       unless user_block.nil?
106         set_locale
107         if user_block.zero_hour?
108           report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
109         else
110           report_error t("application.setup_user_auth.blocked"), :forbidden
111         end
112       end
113
114       # if the user hasn't seen the contributor terms then don't
115       # allow editing - they have to go to the web site and see
116       # (but can decline) the CTs to continue.
117       if !current_user.terms_seen && !skip_terms
118         set_locale
119         report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
120       end
121     end
122   end
123
124   def api_call_handle_error
125     yield
126   rescue ActionController::UnknownFormat
127     head :not_acceptable
128   rescue ActiveRecord::RecordNotFound => e
129     head :not_found
130   rescue LibXML::XML::Error, ArgumentError => e
131     report_error e.message, :bad_request
132   rescue ActiveRecord::RecordInvalid => e
133     message = "#{e.record.class} #{e.record.id}: "
134     e.record.errors.each { |error| message << "#{error.attribute}: #{error.message} (#{e.record[error.attribute].inspect})" }
135     report_error message, :bad_request
136   rescue OSM::APIError => e
137     report_error e.message, e.status
138   rescue AbstractController::ActionNotFound, CanCan::AccessDenied => e
139     raise
140   rescue StandardError => e
141     logger.info("API threw unexpected #{e.class} exception: #{e.message}")
142     e.backtrace.each { |l| logger.info(l) }
143     report_error "#{e.class}: #{e.message}", :internal_server_error
144   end
145
146   ##
147   # wrap an api call in a timeout
148   def api_call_timeout(&)
149     Timeout.timeout(Settings.api_timeout, &)
150   rescue ActionView::Template::Error => e
151     e = e.cause
152
153     if e.is_a?(Timeout::Error) ||
154        (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
155       ActiveRecord::Base.connection.raw_connection.cancel
156       raise OSM::APITimeoutError
157     else
158       raise
159     end
160   rescue Timeout::Error
161     ActiveRecord::Base.connection.raw_connection.cancel
162     raise OSM::APITimeoutError
163   end
164
165   ##
166   # check the api change rate limit
167   def check_rate_limit(new_changes = 1)
168     max_changes = ActiveRecord::Base.connection.select_value(
169       "SELECT api_rate_limit($1)", "api_rate_limit", [current_user.id]
170     )
171
172     raise OSM::APIRateLimitExceeded if new_changes > max_changes
173   end
174
175   def scope_enabled?(scope)
176     doorkeeper_token&.includes_scope?(scope)
177   end
178
179   helper_method :scope_enabled?
180 end