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