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