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