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