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