]> git.openstreetmap.org Git - rails.git/blob - app/controllers/api_controller.rb
Update to rails 7.1.3.3
[rails.git] / app / controllers / api_controller.rb
1 class ApiController < ApplicationController
2   skip_before_action :verify_authenticity_token
3
4   private
5
6   ##
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"]
13
14       if accept_header
15         # Some clients (such asJOSM) send Accept headers which cannot be
16         # parse by Rails, for example:
17         #
18         #   Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
19         #
20         # where both "*" and ".2" as a quality do not adhere to the syntax
21         # described in RFC 7231, section 5.3.1, etc.
22         #
23         # As a workaround, and for back compatibility, default to XML format.
24         mimetypes = begin
25           Mime::Type.parse(accept_header)
26         rescue Mime::Type::InvalidMimeType
27           Array(Mime[:xml])
28         end
29
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
36           end
37         end
38       else
39         # Default to XML if no accept header was sent - this includes
40         # the unit tests which don't set one by default
41         formats = Array(:xml)
42       end
43
44       request.formats = formats.compact
45     end
46   end
47
48   def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
49     # make the current_user object from any auth sources we have
50     setup_user_auth
51
52     # handle authenticate pass/fail
53     unless current_user
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
58       else
59         render :plain => errormessage, :status => :forbidden
60       end
61
62       false
63     end
64   end
65
66   def current_ability
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))
72     else
73       ApiAbility.new(current_user)
74     end
75   end
76
77   def deny_access(_exception)
78     if doorkeeper_token || current_token
79       set_locale
80       report_error t("oauth.permissions.missing"), :forbidden
81     elsif current_user
82       head :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
88     else
89       render :plain => errormessage, :status => :forbidden
90     end
91   end
92
93   def gpx_status
94     status = database_status
95     status = "offline" if status == "online" && Settings.status == "gpx_offline"
96     status
97   end
98
99   ##
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
102   # is optional.
103   def setup_user_auth
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       if Settings.oauth_10a_support
110         # self.current_user setup by OAuth
111       else
112         report_error t("application.oauth_10a_disabled", :link => t("application.auth_disabled_link")), :forbidden
113       end
114     else
115       username, passwd = auth_data # parse from headers
116       # authenticate per-scheme
117       self.current_user = if username.nil?
118                             nil # no authentication provided - perhaps first connect (client should retry after 401)
119                           else
120                             User.authenticate(:username => username, :password => passwd) # basic auth
121                           end
122       if username && current_user
123         if Settings.basic_auth_support
124           # log if we have authenticated using basic auth
125           logger.info "Authenticated as user #{current_user.id} using basic authentication"
126         else
127           report_error t("application.basic_auth_disabled", :link => t("application.auth_disabled_link")), :forbidden
128         end
129       end
130     end
131
132     # have we identified the user?
133     if current_user
134       # check if the user has been banned
135       user_block = current_user.blocks.active.take
136       unless user_block.nil?
137         set_locale
138         if user_block.zero_hour?
139           report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
140         else
141           report_error t("application.setup_user_auth.blocked"), :forbidden
142         end
143       end
144
145       # if the user hasn't seen the contributor terms then don't
146       # allow editing - they have to go to the web site and see
147       # (but can decline) the CTs to continue.
148       if !current_user.terms_seen && flash[:skip_terms].nil?
149         set_locale
150         report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
151       end
152     end
153   end
154
155   def api_call_handle_error
156     yield
157   rescue ActionController::UnknownFormat
158     head :not_acceptable
159   rescue ActiveRecord::RecordNotFound => e
160     head :not_found
161   rescue LibXML::XML::Error, ArgumentError => e
162     report_error e.message, :bad_request
163   rescue ActiveRecord::RecordInvalid => e
164     message = "#{e.record.class} #{e.record.id}: "
165     e.record.errors.each { |error| message << "#{error.attribute}: #{error.message} (#{e.record[error.attribute].inspect})" }
166     report_error message, :bad_request
167   rescue OSM::APIError => e
168     report_error e.message, e.status
169   rescue AbstractController::ActionNotFound => e
170     raise
171   rescue StandardError => e
172     logger.info("API threw unexpected #{e.class} exception: #{e.message}")
173     e.backtrace.each { |l| logger.info(l) }
174     report_error "#{e.class}: #{e.message}", :internal_server_error
175   end
176
177   ##
178   # wrap an api call in a timeout
179   def api_call_timeout(&block)
180     Timeout.timeout(Settings.api_timeout, &block)
181   rescue ActionView::Template::Error => e
182     e = e.cause
183
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
188     else
189       raise
190     end
191   rescue Timeout::Error
192     ActiveRecord::Base.connection.raw_connection.cancel
193     raise OSM::APITimeoutError
194   end
195
196   ##
197   # check the api change rate limit
198   def check_rate_limit(new_changes = 1)
199     max_changes = ActiveRecord::Base.connection.select_value(
200       "SELECT api_rate_limit($1)", "api_rate_limit", [current_user.id]
201     )
202
203     raise OSM::APIRateLimitExceeded if new_changes > max_changes
204   end
205 end