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