]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
Clear notifications after trace import tests
[rails.git] / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include SessionPersistence
3
4   protect_from_forgery :with => :exception
5
6   rescue_from CanCan::AccessDenied, :with => :deny_access
7   check_authorization
8
9   before_action :fetch_body
10   around_action :better_errors_allow_inline, :if => proc { Rails.env.development? }
11
12   attr_accessor :current_user
13   helper_method :current_user
14
15   def authorize_web
16     if session[:user]
17       self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
18
19       if current_user.status == "suspended"
20         session.delete(:user)
21         session_expires_automatically
22
23         redirect_to :controller => "users", :action => "suspended"
24
25       # don't allow access to any auth-requiring part of the site unless
26       # the new CTs have been seen (and accept/decline chosen).
27       elsif !current_user.terms_seen && flash[:skip_terms].nil?
28         flash[:notice] = t "users.terms.you need to accept or decline"
29         if params[:referer]
30           redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
31         else
32           redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
33         end
34       end
35     elsif session[:token]
36       session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
37     end
38   rescue StandardError => ex
39     logger.info("Exception authorizing user: #{ex}")
40     reset_session
41     self.current_user = nil
42   end
43
44   def require_user
45     unless current_user
46       if request.get?
47         redirect_to :controller => "users", :action => "login", :referer => request.fullpath
48       else
49         head :forbidden
50       end
51     end
52   end
53
54   def require_oauth
55     @oauth = current_user.access_token(OAUTH_KEY) if current_user && defined? OAUTH_KEY
56   end
57
58   ##
59   # require the user to have cookies enabled in their browser
60   def require_cookies
61     if request.cookies["_osm_session"].to_s == ""
62       if params[:cookie_test].nil?
63         session[:cookie_test] = true
64         redirect_to params.to_unsafe_h.merge(:cookie_test => "true")
65         false
66       else
67         flash.now[:warning] = t "application.require_cookies.cookies_needed"
68       end
69     else
70       session.delete(:cookie_test)
71     end
72   end
73
74   ##
75   # sets up the current_user for use by other methods. this is mostly called
76   # from the authorize method, but can be called elsewhere if authorisation
77   # is optional.
78   def setup_user_auth
79     # try and setup using OAuth
80     unless Authenticator.new(self, [:token]).allow?
81       username, passwd = get_auth_data # parse from headers
82       # authenticate per-scheme
83       self.current_user = if username.nil?
84                             nil # no authentication provided - perhaps first connect (client should retry after 401)
85                           elsif username == "token"
86                             User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
87                           else
88                             User.authenticate(:username => username, :password => passwd) # basic auth
89                           end
90     end
91
92     # have we identified the user?
93     if current_user
94       # check if the user has been banned
95       user_block = current_user.blocks.active.take
96       unless user_block.nil?
97         set_locale
98         if user_block.zero_hour?
99           report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
100         else
101           report_error t("application.setup_user_auth.blocked"), :forbidden
102         end
103       end
104
105       # if the user hasn't seen the contributor terms then don't
106       # allow editing - they have to go to the web site and see
107       # (but can decline) the CTs to continue.
108       if REQUIRE_TERMS_SEEN && !current_user.terms_seen && flash[:skip_terms].nil?
109         set_locale
110         report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
111       end
112     end
113   end
114
115   def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
116     # make the current_user object from any auth sources we have
117     setup_user_auth
118
119     # handle authenticate pass/fail
120     unless current_user
121       # no auth, the user does not exist or the password was wrong
122       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
123       render :plain => errormessage, :status => :unauthorized
124       return false
125     end
126   end
127
128   def check_database_readable(need_api = false)
129     if STATUS == :database_offline || (need_api && STATUS == :api_offline)
130       if request.xhr?
131         report_error "Database offline for maintenance", :service_unavailable
132       else
133         redirect_to :controller => "site", :action => "offline"
134       end
135     end
136   end
137
138   def check_database_writable(need_api = false)
139     if STATUS == :database_offline || STATUS == :database_readonly ||
140        (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
141       if request.xhr?
142         report_error "Database offline for maintenance", :service_unavailable
143       else
144         redirect_to :controller => "site", :action => "offline"
145       end
146     end
147   end
148
149   def check_api_readable
150     if api_status == :offline
151       report_error "Database offline for maintenance", :service_unavailable
152       false
153     end
154   end
155
156   def check_api_writable
157     unless api_status == :online
158       report_error "Database offline for maintenance", :service_unavailable
159       false
160     end
161   end
162
163   def database_status
164     if STATUS == :database_offline
165       :offline
166     elsif STATUS == :database_readonly
167       :readonly
168     else
169       :online
170     end
171   end
172
173   def api_status
174     status = database_status
175     if status == :online
176       if STATUS == :api_offline
177         status = :offline
178       elsif STATUS == :api_readonly
179         status = :readonly
180       end
181     end
182     status
183   end
184
185   def gpx_status
186     status = database_status
187     status = :offline if status == :online && STATUS == :gpx_offline
188     status
189   end
190
191   def require_public_data
192     unless current_user.data_public?
193       report_error "You must make your edits public to upload new data", :forbidden
194       false
195     end
196   end
197
198   # Report and error to the user
199   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
200   #  rather than only a status code and having the web engine make up a
201   #  phrase from that, we can also put the error message into the status
202   #  message. For now, rails won't let us)
203   def report_error(message, status = :bad_request)
204     # TODO: some sort of escaping of problem characters in the message
205     response.headers["Error"] = message
206
207     if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
208       result = OSM::API.new.get_xml_doc
209       result.root.name = "osmError"
210       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
211       result.root << (XML::Node.new("message") << message)
212
213       render :xml => result.to_s
214     else
215       render :plain => message, :status => status
216     end
217   end
218
219   def preferred_languages(reset = false)
220     @preferred_languages = nil if reset
221     @preferred_languages ||= if params[:locale]
222                                Locale.list(params[:locale])
223                              elsif current_user
224                                current_user.preferred_languages
225                              else
226                                Locale.list(http_accept_language.user_preferred_languages)
227                              end
228   end
229
230   helper_method :preferred_languages
231
232   def set_locale(reset = false)
233     if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
234       current_user.languages = http_accept_language.user_preferred_languages
235       current_user.save
236     end
237
238     I18n.locale = Locale.available.preferred(preferred_languages(reset))
239
240     response.headers["Vary"] = "Accept-Language"
241     response.headers["Content-Language"] = I18n.locale.to_s
242   end
243
244   def api_call_handle_error
245     yield
246   rescue ActiveRecord::RecordNotFound => ex
247     head :not_found
248   rescue LibXML::XML::Error, ArgumentError => ex
249     report_error ex.message, :bad_request
250   rescue ActiveRecord::RecordInvalid => ex
251     message = "#{ex.record.class} #{ex.record.id}: "
252     ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
253     report_error message, :bad_request
254   rescue OSM::APIError => ex
255     report_error ex.message, ex.status
256   rescue AbstractController::ActionNotFound => ex
257     raise
258   rescue StandardError => ex
259     logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
260     ex.backtrace.each { |l| logger.info(l) }
261     report_error "#{ex.class}: #{ex.message}", :internal_server_error
262   end
263
264   ##
265   # asserts that the request method is the +method+ given as a parameter
266   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
267   def assert_method(method)
268     ok = request.send((method.to_s.downcase + "?").to_sym)
269     raise OSM::APIBadMethodError, method unless ok
270   end
271
272   ##
273   # wrap an api call in a timeout
274   def api_call_timeout
275     OSM::Timer.timeout(API_TIMEOUT, Timeout::Error) do
276       yield
277     end
278   rescue Timeout::Error
279     raise OSM::APITimeoutError
280   end
281
282   ##
283   # wrap a web page in a timeout
284   def web_timeout
285     OSM::Timer.timeout(WEB_TIMEOUT, Timeout::Error) do
286       yield
287     end
288   rescue ActionView::Template::Error => ex
289     ex = ex.cause
290
291     if ex.is_a?(Timeout::Error) ||
292        (ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/)
293       render :action => "timeout"
294     else
295       raise
296     end
297   rescue Timeout::Error
298     render :action => "timeout"
299   end
300
301   ##
302   # ensure that there is a "user" instance variable
303   def lookup_user
304     render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
305   end
306
307   ##
308   # render a "no such user" page
309   def render_unknown_user(name)
310     @title = t "users.no_such_user.title"
311     @not_found_user = name
312
313     respond_to do |format|
314       format.html { render :template => "users/no_such_user", :status => :not_found }
315       format.all { head :not_found }
316     end
317   end
318
319   ##
320   # Unfortunately if a PUT or POST request that has a body fails to
321   # read it then Apache will sometimes fail to return the response it
322   # is given to the client properly, instead erroring:
323   #
324   #   https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
325   #
326   # To work round this we call rewind on the body here, which is added
327   # as a filter, to force it to be fetched from Apache into a file.
328   def fetch_body
329     request.body.rewind
330   end
331
332   def map_layout
333     append_content_security_policy_directives(
334       :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
335       :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
336       :connect_src => [NOMINATIM_URL, OVERPASS_URL, OSRM_URL, GRAPHHOPPER_URL],
337       :form_action => %w[render.openstreetmap.org],
338       :style_src => %w['unsafe-inline'],
339       :script_src => [MAPQUEST_DIRECTIONS_URL],
340       :img_src => %w[developer.mapquest.com]
341     )
342
343     if STATUS == :database_offline || STATUS == :api_offline
344       flash.now[:warning] = t("layouts.osm_offline")
345     elsif STATUS == :database_readonly || STATUS == :api_readonly
346       flash.now[:warning] = t("layouts.osm_read_only")
347     end
348
349     request.xhr? ? "xhr" : "map"
350   end
351
352   def allow_thirdparty_images
353     append_content_security_policy_directives(:img_src => %w[*])
354   end
355
356   def preferred_editor
357     editor = if params[:editor]
358                params[:editor]
359              elsif current_user&.preferred_editor
360                current_user.preferred_editor
361              else
362                DEFAULT_EDITOR
363              end
364
365     editor
366   end
367
368   helper_method :preferred_editor
369
370   def update_totp
371     if defined?(TOTP_KEY)
372       cookies["_osm_totp_token"] = {
373         :value => ROTP::TOTP.new(TOTP_KEY, :interval => 3600).now,
374         :domain => "openstreetmap.org",
375         :expires => 1.hour.from_now
376       }
377     end
378   end
379
380   def better_errors_allow_inline
381     yield
382   rescue StandardError
383     append_content_security_policy_directives(
384       :script_src => %w['unsafe-inline'],
385       :style_src => %w['unsafe-inline']
386     )
387
388     raise
389   end
390
391   def current_ability
392     # Use capabilities from the oauth token if it exists and is a valid access token
393     if Authenticator.new(self, [:token]).allow?
394       Ability.new(nil).merge(Capability.new(current_token))
395     else
396       Ability.new(current_user)
397     end
398   end
399
400   def deny_access(exception)
401     if @api_deny_access_handling
402       api_deny_access(exception)
403     else
404       web_deny_access(exception)
405     end
406   end
407
408   def web_deny_access(_exception)
409     if current_token
410       set_locale
411       report_error t("oauth.permissions.missing"), :forbidden
412     elsif current_user
413       set_locale
414       respond_to do |format|
415         format.html { redirect_to :controller => "errors", :action => "forbidden" }
416         format.any { report_error t("application.permission_denied"), :forbidden }
417       end
418     elsif request.get?
419       respond_to do |format|
420         format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
421         format.any { head :forbidden }
422       end
423     else
424       head :forbidden
425     end
426   end
427
428   def api_deny_access(_exception)
429     if current_token
430       set_locale
431       report_error t("oauth.permissions.missing"), :forbidden
432     elsif current_user
433       head :forbidden
434     else
435       realm = "Web Password"
436       errormessage = "Couldn't authenticate you"
437       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
438       render :plain => errormessage, :status => :unauthorized
439     end
440   end
441
442   attr_accessor :api_access_handling
443
444   def api_deny_access_handler
445     @api_deny_access_handling = true
446   end
447
448   private
449
450   # extract authorisation credentials from headers, returns user = nil if none
451   def get_auth_data
452     if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
453       authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
454     elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
455       authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
456     elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
457       authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
458     end
459     # only basic authentication supported
460     user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
461     [user, pass]
462   end
463
464   # override to stop oauth plugin sending errors
465   def invalid_oauth_response; end
466 end