]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
Initialise locale before looking up user blocked error
[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       if @user.blocks.active.exists?
156         # NOTE: need slightly more helpful message than this.
157         set_locale
158         report_error t("application.setup_user_auth.blocked"), :forbidden
159       end
160
161       # if the user hasn't seen the contributor terms then don't
162       # allow editing - they have to go to the web site and see
163       # (but can decline) the CTs to continue.
164       if REQUIRE_TERMS_SEEN && !@user.terms_seen && flash[:skip_terms].nil?
165         set_locale
166         report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
167       end
168     end
169   end
170
171   def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
172     # make the @user object from any auth sources we have
173     setup_user_auth
174
175     # handle authenticate pass/fail
176     unless @user
177       # no auth, the user does not exist or the password was wrong
178       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
179       render :text => errormessage, :status => :unauthorized
180       return false
181     end
182   end
183
184   ##
185   # to be used as a before_filter *after* authorize. this checks that
186   # the user is a moderator and, if not, returns a forbidden error.
187   #
188   # NOTE: this isn't a very good way of doing it - it duplicates logic
189   # from require_moderator - but what we really need to do is a fairly
190   # drastic refactoring based on :format and respond_to? but not a
191   # good idea to do that in this branch.
192   def authorize_moderator(errormessage = "Access restricted to moderators")
193     # check user is a moderator
194     unless @user.moderator?
195       render :text => errormessage, :status => :forbidden
196       false
197     end
198   end
199
200   def check_database_readable(need_api = false)
201     if STATUS == :database_offline || (need_api && STATUS == :api_offline)
202       if request.xhr?
203         report_error "Database offline for maintenance", :service_unavailable
204       else
205         redirect_to :controller => "site", :action => "offline"
206       end
207     end
208   end
209
210   def check_database_writable(need_api = false)
211     if STATUS == :database_offline || STATUS == :database_readonly ||
212        (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
213       if request.xhr?
214         report_error "Database offline for maintenance", :service_unavailable
215       else
216         redirect_to :controller => "site", :action => "offline"
217       end
218     end
219   end
220
221   def check_api_readable
222     if api_status == :offline
223       report_error "Database offline for maintenance", :service_unavailable
224       false
225     end
226   end
227
228   def check_api_writable
229     unless api_status == :online
230       report_error "Database offline for maintenance", :service_unavailable
231       false
232     end
233   end
234
235   def database_status
236     if STATUS == :database_offline
237       :offline
238     elsif STATUS == :database_readonly
239       :readonly
240     else
241       :online
242     end
243   end
244
245   def api_status
246     status = database_status
247     if status == :online
248       if STATUS == :api_offline
249         status = :offline
250       elsif STATUS == :api_readonly
251         status = :readonly
252       end
253     end
254     status
255   end
256
257   def gpx_status
258     status = database_status
259     status = :offline if status == :online && STATUS == :gpx_offline
260     status
261   end
262
263   def require_public_data
264     unless @user.data_public?
265       report_error "You must make your edits public to upload new data", :forbidden
266       false
267     end
268   end
269
270   # Report and error to the user
271   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
272   #  rather than only a status code and having the web engine make up a
273   #  phrase from that, we can also put the error message into the status
274   #  message. For now, rails won't let us)
275   def report_error(message, status = :bad_request)
276     # TODO: some sort of escaping of problem characters in the message
277     response.headers["Error"] = message
278
279     if request.headers["X-Error-Format"] &&
280        request.headers["X-Error-Format"].casecmp("xml").zero?
281       result = OSM::API.new.get_xml_doc
282       result.root.name = "osmError"
283       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
284       result.root << (XML::Node.new("message") << message)
285
286       render :text => result.to_s, :content_type => "text/xml"
287     else
288       render :text => message, :status => status, :content_type => "text/plain"
289     end
290   end
291
292   def preferred_languages
293     @languages ||= if params[:locale]
294                      Locale.list(params[:locale])
295                    elsif @user
296                      @user.preferred_languages
297                    else
298                      Locale.list(http_accept_language.user_preferred_languages)
299                    end
300   end
301
302   helper_method :preferred_languages
303
304   def set_locale
305     if @user && @user.languages.empty? && !http_accept_language.user_preferred_languages.empty?
306       @user.languages = http_accept_language.user_preferred_languages
307       @user.save
308     end
309
310     I18n.locale = Locale.available.preferred(preferred_languages)
311
312     response.headers["Vary"] = "Accept-Language"
313     response.headers["Content-Language"] = I18n.locale.to_s
314   end
315
316   def api_call_handle_error
317     yield
318   rescue ActiveRecord::RecordNotFound => ex
319     render :text => "", :status => :not_found
320   rescue LibXML::XML::Error, ArgumentError => ex
321     report_error ex.message, :bad_request
322   rescue ActiveRecord::RecordInvalid => ex
323     message = "#{ex.record.class} #{ex.record.id}: "
324     ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
325     report_error message, :bad_request
326   rescue OSM::APIError => ex
327     report_error ex.message, ex.status
328   rescue AbstractController::ActionNotFound => ex
329     raise
330   rescue StandardError => ex
331     logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
332     ex.backtrace.each { |l| logger.info(l) }
333     report_error "#{ex.class}: #{ex.message}", :internal_server_error
334   end
335
336   ##
337   # asserts that the request method is the +method+ given as a parameter
338   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
339   def assert_method(method)
340     ok = request.send((method.to_s.downcase + "?").to_sym)
341     raise OSM::APIBadMethodError.new(method) unless ok
342   end
343
344   ##
345   # wrap an api call in a timeout
346   def api_call_timeout
347     OSM::Timer.timeout(API_TIMEOUT, Timeout::Error) do
348       yield
349     end
350   rescue Timeout::Error
351     raise OSM::APITimeoutError
352   end
353
354   ##
355   # wrap a web page in a timeout
356   def web_timeout
357     OSM::Timer.timeout(WEB_TIMEOUT, Timeout::Error) do
358       yield
359     end
360   rescue ActionView::Template::Error => ex
361     ex = ex.original_exception
362
363     if ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/
364       render :action => "timeout"
365     else
366       raise
367     end
368   rescue Timeout::Error
369     render :action => "timeout"
370   end
371
372   ##
373   # ensure that there is a "this_user" instance variable
374   def lookup_this_user
375     unless @this_user = User.active.find_by(:display_name => params[:display_name])
376       render_unknown_user params[:display_name]
377     end
378   end
379
380   ##
381   # render a "no such user" page
382   def render_unknown_user(name)
383     @title = t "user.no_such_user.title"
384     @not_found_user = name
385
386     respond_to do |format|
387       format.html { render :template => "user/no_such_user", :status => :not_found }
388       format.all { render :text => "", :status => :not_found }
389     end
390   end
391
392   ##
393   # Unfortunately if a PUT or POST request that has a body fails to
394   # read it then Apache will sometimes fail to return the response it
395   # is given to the client properly, instead erroring:
396   #
397   #   https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
398   #
399   # To work round this we call rewind on the body here, which is added
400   # as a filter, to force it to be fetched from Apache into a file.
401   def fetch_body
402     request.body.rewind
403   end
404
405   def map_layout
406     request.xhr? ? "xhr" : "map"
407   end
408
409   def preferred_editor
410     editor = if params[:editor]
411                params[:editor]
412              elsif @user && @user.preferred_editor
413                @user.preferred_editor
414              else
415                DEFAULT_EDITOR
416              end
417
418     editor
419   end
420
421   helper_method :preferred_editor
422
423   def update_totp
424     if defined?(TOTP_KEY)
425       cookies["_osm_totp_token"] = {
426         :value => ROTP::TOTP.new(TOTP_KEY, :interval => 3600).now,
427         :domain => "openstreetmap.org",
428         :expires => 1.hour.from_now
429       }
430     end
431   end
432
433   private
434
435   # extract authorisation credentials from headers, returns user = nil if none
436   def get_auth_data
437     if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
438       authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
439     elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
440       authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
441     elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
442       authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
443     end
444     # only basic authentication supported
445     if authdata && authdata[0] == "Basic"
446       user, pass = Base64.decode64(authdata[1]).split(":", 2)
447     end
448     [user, pass]
449   end
450
451   # used by oauth plugin to get the current user
452   def current_user
453     @user
454   end
455
456   # used by oauth plugin to set the current user
457   def current_user=(user)
458     @user = user
459   end
460
461   # override to stop oauth plugin sending errors
462   def invalid_oauth_response; end
463 end