]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
d4bbc1f9b7147ada16f015a77f73a0fb56168aac
[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   ##
122   # sets up the current_user for use by other methods. this is mostly called
123   # from the authorize method, but can be called elsewhere if authorisation
124   # is optional.
125   def setup_user_auth
126     # try and setup using OAuth
127     unless Authenticator.new(self, [:token]).allow?
128       username, passwd = get_auth_data # parse from headers
129       # authenticate per-scheme
130       self.current_user = if username.nil?
131                             nil # no authentication provided - perhaps first connect (client should retry after 401)
132                           elsif username == "token"
133                             User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
134                           else
135                             User.authenticate(:username => username, :password => passwd) # basic auth
136                           end
137     end
138
139     # have we identified the user?
140     if current_user
141       # check if the user has been banned
142       user_block = current_user.blocks.active.take
143       unless user_block.nil?
144         set_locale
145         if user_block.zero_hour?
146           report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
147         else
148           report_error t("application.setup_user_auth.blocked"), :forbidden
149         end
150       end
151
152       # if the user hasn't seen the contributor terms then don't
153       # allow editing - they have to go to the web site and see
154       # (but can decline) the CTs to continue.
155       if REQUIRE_TERMS_SEEN && !current_user.terms_seen && flash[:skip_terms].nil?
156         set_locale
157         report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
158       end
159     end
160   end
161
162   def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
163     # make the current_user object from any auth sources we have
164     setup_user_auth
165
166     # handle authenticate pass/fail
167     unless current_user
168       # no auth, the user does not exist or the password was wrong
169       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
170       render :plain => errormessage, :status => :unauthorized
171       return false
172     end
173   end
174
175   ##
176   # to be used as a before_filter *after* authorize. this checks that
177   # the user is a moderator and, if not, returns a forbidden error.
178   def authorize_moderator(errormessage = "Access restricted to moderators")
179     # check user is a moderator
180     unless current_user.moderator?
181       render :plain => errormessage, :status => :forbidden
182       false
183     end
184   end
185
186   def check_database_readable(need_api = false)
187     if STATUS == :database_offline || (need_api && STATUS == :api_offline)
188       if request.xhr?
189         report_error "Database offline for maintenance", :service_unavailable
190       else
191         redirect_to :controller => "site", :action => "offline"
192       end
193     end
194   end
195
196   def check_database_writable(need_api = false)
197     if STATUS == :database_offline || STATUS == :database_readonly ||
198        (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
199       if request.xhr?
200         report_error "Database offline for maintenance", :service_unavailable
201       else
202         redirect_to :controller => "site", :action => "offline"
203       end
204     end
205   end
206
207   def check_api_readable
208     if api_status == :offline
209       report_error "Database offline for maintenance", :service_unavailable
210       false
211     end
212   end
213
214   def check_api_writable
215     unless api_status == :online
216       report_error "Database offline for maintenance", :service_unavailable
217       false
218     end
219   end
220
221   def database_status
222     if STATUS == :database_offline
223       :offline
224     elsif STATUS == :database_readonly
225       :readonly
226     else
227       :online
228     end
229   end
230
231   def api_status
232     status = database_status
233     if status == :online
234       if STATUS == :api_offline
235         status = :offline
236       elsif STATUS == :api_readonly
237         status = :readonly
238       end
239     end
240     status
241   end
242
243   def gpx_status
244     status = database_status
245     status = :offline if status == :online && STATUS == :gpx_offline
246     status
247   end
248
249   def require_public_data
250     unless current_user.data_public?
251       report_error "You must make your edits public to upload new data", :forbidden
252       false
253     end
254   end
255
256   # Report and error to the user
257   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
258   #  rather than only a status code and having the web engine make up a
259   #  phrase from that, we can also put the error message into the status
260   #  message. For now, rails won't let us)
261   def report_error(message, status = :bad_request)
262     # TODO: some sort of escaping of problem characters in the message
263     response.headers["Error"] = message
264
265     if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
266       result = OSM::API.new.get_xml_doc
267       result.root.name = "osmError"
268       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
269       result.root << (XML::Node.new("message") << message)
270
271       render :xml => result.to_s
272     else
273       render :plain => message, :status => status
274     end
275   end
276
277   def preferred_languages(reset = false)
278     @preferred_languages = nil if reset
279     @preferred_languages ||= if params[:locale]
280                                Locale.list(params[:locale])
281                              elsif current_user
282                                current_user.preferred_languages
283                              else
284                                Locale.list(http_accept_language.user_preferred_languages)
285                              end
286   end
287
288   helper_method :preferred_languages
289
290   def set_locale(reset = false)
291     if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
292       current_user.languages = http_accept_language.user_preferred_languages
293       current_user.save
294     end
295
296     I18n.locale = Locale.available.preferred(preferred_languages(reset))
297
298     response.headers["Vary"] = "Accept-Language"
299     response.headers["Content-Language"] = I18n.locale.to_s
300   end
301
302   def api_call_handle_error
303     yield
304   rescue ActiveRecord::RecordNotFound => ex
305     head :not_found
306   rescue LibXML::XML::Error, ArgumentError => ex
307     report_error ex.message, :bad_request
308   rescue ActiveRecord::RecordInvalid => ex
309     message = "#{ex.record.class} #{ex.record.id}: "
310     ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
311     report_error message, :bad_request
312   rescue OSM::APIError => ex
313     report_error ex.message, ex.status
314   rescue AbstractController::ActionNotFound => ex
315     raise
316   rescue StandardError => ex
317     logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
318     ex.backtrace.each { |l| logger.info(l) }
319     report_error "#{ex.class}: #{ex.message}", :internal_server_error
320   end
321
322   ##
323   # asserts that the request method is the +method+ given as a parameter
324   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
325   def assert_method(method)
326     ok = request.send((method.to_s.downcase + "?").to_sym)
327     raise OSM::APIBadMethodError, method unless ok
328   end
329
330   ##
331   # wrap an api call in a timeout
332   def api_call_timeout
333     OSM::Timer.timeout(API_TIMEOUT, Timeout::Error) do
334       yield
335     end
336   rescue Timeout::Error
337     raise OSM::APITimeoutError
338   end
339
340   ##
341   # wrap a web page in a timeout
342   def web_timeout
343     OSM::Timer.timeout(WEB_TIMEOUT, Timeout::Error) do
344       yield
345     end
346   rescue ActionView::Template::Error => ex
347     ex = ex.cause
348
349     if ex.is_a?(Timeout::Error) ||
350        (ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/)
351       render :action => "timeout"
352     else
353       raise
354     end
355   rescue Timeout::Error
356     render :action => "timeout"
357   end
358
359   ##
360   # ensure that there is a "user" instance variable
361   def lookup_user
362     render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
363   end
364
365   ##
366   # render a "no such user" page
367   def render_unknown_user(name)
368     @title = t "users.no_such_user.title"
369     @not_found_user = name
370
371     respond_to do |format|
372       format.html { render :template => "users/no_such_user", :status => :not_found }
373       format.all { head :not_found }
374     end
375   end
376
377   ##
378   # Unfortunately if a PUT or POST request that has a body fails to
379   # read it then Apache will sometimes fail to return the response it
380   # is given to the client properly, instead erroring:
381   #
382   #   https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
383   #
384   # To work round this we call rewind on the body here, which is added
385   # as a filter, to force it to be fetched from Apache into a file.
386   def fetch_body
387     request.body.rewind
388   end
389
390   def map_layout
391     append_content_security_policy_directives(
392       :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
393       :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
394       :connect_src => [NOMINATIM_URL, OVERPASS_URL, OSRM_URL, GRAPHHOPPER_URL],
395       :form_action => %w[render.openstreetmap.org],
396       :script_src => [MAPQUEST_DIRECTIONS_URL],
397       :img_src => %w[developer.mapquest.com]
398     )
399
400     if STATUS == :database_offline || STATUS == :api_offline
401       flash.now[:warning] = t("layouts.osm_offline")
402     elsif STATUS == :database_readonly || STATUS == :api_readonly
403       flash.now[:warning] = t("layouts.osm_read_only")
404     end
405
406     request.xhr? ? "xhr" : "map"
407   end
408
409   def allow_thirdparty_images
410     append_content_security_policy_directives(:img_src => %w[*])
411   end
412
413   def preferred_editor
414     editor = if params[:editor]
415                params[:editor]
416              elsif current_user&.preferred_editor
417                current_user.preferred_editor
418              else
419                DEFAULT_EDITOR
420              end
421
422     editor
423   end
424
425   helper_method :preferred_editor
426
427   def update_totp
428     if defined?(TOTP_KEY)
429       cookies["_osm_totp_token"] = {
430         :value => ROTP::TOTP.new(TOTP_KEY, :interval => 3600).now,
431         :domain => "openstreetmap.org",
432         :expires => 1.hour.from_now
433       }
434     end
435   end
436
437   def better_errors_allow_inline
438     yield
439   rescue StandardError
440     append_content_security_policy_directives(
441       :script_src => %w['unsafe-inline'],
442       :style_src => %w['unsafe-inline']
443     )
444
445     raise
446   end
447
448   def current_ability
449     # Use capabilities from the oauth token if it exists and is a valid access token
450     if Authenticator.new(self, [:token]).allow?
451       Ability.new(nil).merge(Capability.new(current_token))
452     else
453       Ability.new(current_user)
454     end
455   end
456
457   def deny_access(exception)
458     if @api_deny_access_handling
459       api_deny_access(exception)
460     else
461       web_deny_access(exception)
462     end
463   end
464
465   def web_deny_access(_exception)
466     if current_token
467       set_locale
468       report_error t("oauth.permissions.missing"), :forbidden
469     elsif current_user
470       set_locale
471       respond_to do |format|
472         format.html { redirect_to :controller => "errors", :action => "forbidden" }
473         format.any { report_error t("application.permission_denied"), :forbidden }
474       end
475     elsif request.get?
476       respond_to do |format|
477         format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
478         format.any { head :forbidden }
479       end
480     else
481       head :forbidden
482     end
483   end
484
485   def api_deny_access(_exception)
486     if current_token
487       set_locale
488       report_error t("oauth.permissions.missing"), :forbidden
489     elsif current_user
490       head :forbidden
491     else
492       realm = "Web Password"
493       errormessage = "Couldn't authenticate you"
494       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
495       render :plain => errormessage, :status => :unauthorized
496     end
497   end
498
499   attr_accessor :api_access_handling
500
501   def api_deny_access_handler
502     @api_deny_access_handling = true
503   end
504
505   private
506
507   # extract authorisation credentials from headers, returns user = nil if none
508   def get_auth_data
509     if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
510       authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
511     elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
512       authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
513     elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
514       authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
515     end
516     # only basic authentication supported
517     user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
518     [user, pass]
519   end
520
521   # override to stop oauth plugin sending errors
522   def invalid_oauth_response; end
523 end