1 class ApiController < ApplicationController
2 skip_before_action :verify_authenticity_token
4 before_action :check_api_readable
6 around_action :api_call_handle_error, :api_call_timeout
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"]
19 # Some clients (such asJOSM) send Accept headers which cannot be
20 # parse by Rails, for example:
22 # Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
24 # where both "*" and ".2" as a quality do not adhere to the syntax
25 # described in RFC 7231, section 5.3.1, etc.
27 # As a workaround, and for back compatibility, default to XML format.
29 Mime::Type.parse(accept_header)
30 rescue Mime::Type::InvalidMimeType
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
43 # Default to XML if no accept header was sent - this includes
44 # the unit tests which don't set one by default
48 request.formats = formats.compact
52 def authorize(errormessage = "Couldn't authenticate you")
53 # make the current_user object from any auth sources we have
56 # handle authenticate pass/fail
58 # no auth, the user does not exist or the password was wrong
59 render :plain => errormessage, :status => :unauthorized
66 # Use capabilities from the oauth token if it exists and is a valid access token
67 if doorkeeper_token&.accessible?
68 ApiAbility.new(nil).merge(ApiCapability.new(doorkeeper_token))
70 ApiAbility.new(current_user)
74 def deny_access(_exception)
77 report_error t("oauth.permissions.missing"), :forbidden
86 status = database_status
87 status = "offline" if status == "online" && Settings.status == "gpx_offline"
92 # sets up the current_user for use by other methods. this is mostly called
93 # from the authorize method, but can be called elsewhere if authorisation
96 logger.info " setup_user_auth"
97 # try and setup using OAuth
98 self.current_user = User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token&.accessible?
100 # have we identified the user?
102 # check if the user has been banned
103 user_block = current_user.blocks.active.take
104 unless user_block.nil?
106 if user_block.zero_hour?
107 report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
109 report_error t("application.setup_user_auth.blocked"), :forbidden
113 # if the user hasn't seen the contributor terms then don't
114 # allow editing - they have to go to the web site and see
115 # (but can decline) the CTs to continue.
116 if !current_user.terms_seen && flash[:skip_terms].nil?
118 report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
123 def api_call_handle_error
125 rescue ActionController::UnknownFormat
127 rescue ActiveRecord::RecordNotFound => e
129 rescue LibXML::XML::Error, ArgumentError => e
130 report_error e.message, :bad_request
131 rescue ActiveRecord::RecordInvalid => e
132 message = "#{e.record.class} #{e.record.id}: "
133 e.record.errors.each { |error| message << "#{error.attribute}: #{error.message} (#{e.record[error.attribute].inspect})" }
134 report_error message, :bad_request
135 rescue OSM::APIError => e
136 report_error e.message, e.status
137 rescue AbstractController::ActionNotFound, CanCan::AccessDenied => e
139 rescue StandardError => e
140 logger.info("API threw unexpected #{e.class} exception: #{e.message}")
141 e.backtrace.each { |l| logger.info(l) }
142 report_error "#{e.class}: #{e.message}", :internal_server_error
146 # wrap an api call in a timeout
147 def api_call_timeout(&)
148 Timeout.timeout(Settings.api_timeout, &)
149 rescue ActionView::Template::Error => e
152 if e.is_a?(Timeout::Error) ||
153 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
154 ActiveRecord::Base.connection.raw_connection.cancel
155 raise OSM::APITimeoutError
159 rescue Timeout::Error
160 ActiveRecord::Base.connection.raw_connection.cancel
161 raise OSM::APITimeoutError
165 # check the api change rate limit
166 def check_rate_limit(new_changes = 1)
167 max_changes = ActiveRecord::Base.connection.select_value(
168 "SELECT api_rate_limit($1)", "api_rate_limit", [current_user.id]
171 raise OSM::APIRateLimitExceeded if new_changes > max_changes