1 class ApiController < ApplicationController
2 skip_before_action :verify_authenticity_token
7 # Set allowed request formats if no explicit format has been
8 # requested via a URL suffix. Allowed formats are taken from
9 # any HTTP Accept header with XML as the default.
10 def set_request_formats
11 unless params[:format]
12 accept_header = request.headers["HTTP_ACCEPT"]
15 # Some clients (such asJOSM) send Accept headers which cannot be
16 # parse by Rails, for example:
18 # Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
20 # where both "*" and ".2" as a quality do not adhere to the syntax
21 # described in RFC 7231, section 5.3.1, etc.
23 # As a workaround, and for back compatibility, default to XML format.
25 Mime::Type.parse(accept_header)
26 rescue Mime::Type::InvalidMimeType
30 # Allow XML and JSON formats, and treat an all formats wildcard
31 # as XML for backwards compatibility - all other formats are discarded
32 # which will result in a 406 Not Acceptable response being sent
33 formats = mimetypes.map do |mime|
34 if mime.symbol == :xml || mime == "*/*" then :xml
35 elsif mime.symbol == :json then :json
39 # Default to XML if no accept header was sent - this includes
40 # the unit tests which don't set one by default
44 request.formats = formats.compact
48 def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
49 # make the current_user object from any auth sources we have
52 # handle authenticate pass/fail
54 # no auth, the user does not exist or the password was wrong
55 if Settings.basic_auth_support
56 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
57 render :plain => errormessage, :status => :unauthorized
59 render :plain => errormessage, :status => :forbidden
67 # Use capabilities from the oauth token if it exists and is a valid access token
68 if doorkeeper_token&.accessible?
69 ApiAbility.new(nil).merge(ApiCapability.new(doorkeeper_token))
70 elsif Authenticator.new(self, [:token]).allow?
71 ApiAbility.new(nil).merge(ApiCapability.new(current_token))
73 ApiAbility.new(current_user)
77 def deny_access(_exception)
78 if doorkeeper_token || current_token
80 report_error t("oauth.permissions.missing"), :forbidden
83 elsif Settings.basic_auth_support
84 realm = "Web Password"
85 errormessage = "Couldn't authenticate you"
86 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
87 render :plain => errormessage, :status => :unauthorized
89 render :plain => errormessage, :status => :forbidden
94 status = database_status
95 status = "offline" if status == "online" && Settings.status == "gpx_offline"
100 # sets up the current_user for use by other methods. this is mostly called
101 # from the authorize method, but can be called elsewhere if authorisation
104 logger.info " setup_user_auth"
105 # try and setup using OAuth
106 if doorkeeper_token&.accessible?
107 self.current_user = User.find(doorkeeper_token.resource_owner_id)
108 elsif Authenticator.new(self, [:token]).allow?
109 # self.current_user setup by OAuth
110 elsif Settings.basic_auth_support
111 username, passwd = auth_data # parse from headers
112 # authenticate per-scheme
113 self.current_user = if username.nil?
114 nil # no authentication provided - perhaps first connect (client should retry after 401)
115 elsif username == "token"
116 User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
118 User.authenticate(:username => username, :password => passwd) # basic auth
120 # log if we have authenticated using basic auth
121 logger.info "Authenticated as user #{current_user.id} using basic authentication" if current_user
124 # have we identified the user?
126 # check if the user has been banned
127 user_block = current_user.blocks.active.take
128 unless user_block.nil?
130 if user_block.zero_hour?
131 report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
133 report_error t("application.setup_user_auth.blocked"), :forbidden
137 # if the user hasn't seen the contributor terms then don't
138 # allow editing - they have to go to the web site and see
139 # (but can decline) the CTs to continue.
140 if !current_user.terms_seen && flash[:skip_terms].nil?
142 report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
147 def api_call_handle_error
149 rescue ActionController::UnknownFormat
151 rescue ActiveRecord::RecordNotFound => e
153 rescue LibXML::XML::Error, ArgumentError => e
154 report_error e.message, :bad_request
155 rescue ActiveRecord::RecordInvalid => e
156 message = "#{e.record.class} #{e.record.id}: "
157 e.record.errors.each { |error| message << "#{error.attribute}: #{error.message} (#{e.record[error.attribute].inspect})" }
158 report_error message, :bad_request
159 rescue OSM::APIError => e
160 report_error e.message, e.status
161 rescue AbstractController::ActionNotFound => e
163 rescue StandardError => e
164 logger.info("API threw unexpected #{e.class} exception: #{e.message}")
165 e.backtrace.each { |l| logger.info(l) }
166 report_error "#{e.class}: #{e.message}", :internal_server_error
170 # asserts that the request method is the +method+ given as a parameter
171 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
172 def assert_method(method)
173 ok = request.send(:"#{method.to_s.downcase}?")
174 raise OSM::APIBadMethodError, method unless ok
178 # wrap an api call in a timeout
179 def api_call_timeout(&block)
180 Timeout.timeout(Settings.api_timeout, Timeout::Error, &block)
181 rescue ActionView::Template::Error => e
184 if e.is_a?(Timeout::Error) ||
185 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
186 ActiveRecord::Base.connection.raw_connection.cancel
187 raise OSM::APITimeoutError
191 rescue Timeout::Error
192 ActiveRecord::Base.connection.raw_connection.cancel
193 raise OSM::APITimeoutError