1 class ApiController < ApplicationController
2 skip_before_action :verify_authenticity_token
4 before_action :check_api_readable
9 # Set allowed request formats if no explicit format has been
10 # requested via a URL suffix. Allowed formats are taken from
11 # any HTTP Accept header with XML as the default.
12 def set_request_formats
13 unless params[:format]
14 accept_header = request.headers["HTTP_ACCEPT"]
17 # Some clients (such asJOSM) send Accept headers which cannot be
18 # parse by Rails, for example:
20 # Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
22 # where both "*" and ".2" as a quality do not adhere to the syntax
23 # described in RFC 7231, section 5.3.1, etc.
25 # As a workaround, and for back compatibility, default to XML format.
27 Mime::Type.parse(accept_header)
28 rescue Mime::Type::InvalidMimeType
32 # Allow XML and JSON formats, and treat an all formats wildcard
33 # as XML for backwards compatibility - all other formats are discarded
34 # which will result in a 406 Not Acceptable response being sent
35 formats = mimetypes.map do |mime|
36 if mime.symbol == :xml || mime == "*/*" then :xml
37 elsif mime.symbol == :json then :json
41 # Default to XML if no accept header was sent - this includes
42 # the unit tests which don't set one by default
46 request.formats = formats.compact
50 def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
51 # make the current_user object from any auth sources we have
54 # handle authenticate pass/fail
56 # no auth, the user does not exist or the password was wrong
57 if Settings.basic_auth_support
58 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
59 render :plain => errormessage, :status => :unauthorized
61 render :plain => errormessage, :status => :forbidden
69 # Use capabilities from the oauth token if it exists and is a valid access token
70 if doorkeeper_token&.accessible?
71 ApiAbility.new(nil).merge(ApiCapability.new(doorkeeper_token))
72 elsif Authenticator.new(self, [:token]).allow?
73 ApiAbility.new(nil).merge(ApiCapability.new(current_token))
75 ApiAbility.new(current_user)
79 def deny_access(_exception)
80 if doorkeeper_token || current_token
82 report_error t("oauth.permissions.missing"), :forbidden
85 elsif Settings.basic_auth_support
86 realm = "Web Password"
87 errormessage = "Couldn't authenticate you"
88 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
89 render :plain => errormessage, :status => :unauthorized
91 render :plain => errormessage, :status => :forbidden
96 status = database_status
97 status = "offline" if status == "online" && Settings.status == "gpx_offline"
102 # sets up the current_user for use by other methods. this is mostly called
103 # from the authorize method, but can be called elsewhere if authorisation
106 logger.info " setup_user_auth"
107 # try and setup using OAuth
108 if doorkeeper_token&.accessible?
109 self.current_user = User.find(doorkeeper_token.resource_owner_id)
110 elsif Authenticator.new(self, [:token]).allow?
111 if Settings.oauth_10a_support
112 # self.current_user setup by OAuth
114 report_error t("application.oauth_10a_disabled", :link => t("application.auth_disabled_link")), :forbidden
115 self.current_user = nil
118 username, passwd = auth_data # parse from headers
119 # authenticate per-scheme
120 self.current_user = if username.nil?
121 nil # no authentication provided - perhaps first connect (client should retry after 401)
123 User.authenticate(:username => username, :password => passwd) # basic auth
125 if username && current_user
126 if Settings.basic_auth_support
127 # log if we have authenticated using basic auth
128 logger.info "Authenticated as user #{current_user.id} using basic authentication"
130 report_error t("application.basic_auth_disabled", :link => t("application.auth_disabled_link")), :forbidden
135 # have we identified the user?
137 # check if the user has been banned
138 user_block = current_user.blocks.active.take
139 unless user_block.nil?
141 if user_block.zero_hour?
142 report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
144 report_error t("application.setup_user_auth.blocked"), :forbidden
148 # if the user hasn't seen the contributor terms then don't
149 # allow editing - they have to go to the web site and see
150 # (but can decline) the CTs to continue.
151 if !current_user.terms_seen && flash[:skip_terms].nil?
153 report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
158 def api_call_handle_error
160 rescue ActionController::UnknownFormat
162 rescue ActiveRecord::RecordNotFound => e
164 rescue LibXML::XML::Error, ArgumentError => e
165 report_error e.message, :bad_request
166 rescue ActiveRecord::RecordInvalid => e
167 message = "#{e.record.class} #{e.record.id}: "
168 e.record.errors.each { |error| message << "#{error.attribute}: #{error.message} (#{e.record[error.attribute].inspect})" }
169 report_error message, :bad_request
170 rescue OSM::APIError => e
171 report_error e.message, e.status
172 rescue AbstractController::ActionNotFound => e
174 rescue StandardError => e
175 logger.info("API threw unexpected #{e.class} exception: #{e.message}")
176 e.backtrace.each { |l| logger.info(l) }
177 report_error "#{e.class}: #{e.message}", :internal_server_error
181 # wrap an api call in a timeout
182 def api_call_timeout(&block)
183 Timeout.timeout(Settings.api_timeout, &block)
184 rescue ActionView::Template::Error => e
187 if e.is_a?(Timeout::Error) ||
188 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
189 ActiveRecord::Base.connection.raw_connection.cancel
190 raise OSM::APITimeoutError
194 rescue Timeout::Error
195 ActiveRecord::Base.connection.raw_connection.cancel
196 raise OSM::APITimeoutError
200 # check the api change rate limit
201 def check_rate_limit(new_changes = 1)
202 max_changes = ActiveRecord::Base.connection.select_value(
203 "SELECT api_rate_limit($1)", "api_rate_limit", [current_user.id]
206 raise OSM::APIRateLimitExceeded if new_changes > max_changes