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