]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
Serve embedded maps through the assets pipeline
[rails.git] / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include SessionPersistence
3
4   protect_from_forgery
5
6   before_filter :fetch_body
7
8   if STATUS == :database_readonly or STATUS == :database_offline
9     def self.cache_sweeper(*sweepers)
10     end
11   end
12
13   def authorize_web
14     if session[:user]
15       @user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
16
17       if @user.display_name != cookies["_osm_username"]
18         logger.info "Session user '#{@user.display_name}' does not match cookie user '#{cookies['_osm_username']}'"
19         reset_session
20         @user = nil
21       elsif @user.status == "suspended"
22         session.delete(:user)
23         session_expires_automatically
24
25         redirect_to :controller => "user", :action => "suspended"
26
27         # don't allow access to any auth-requiring part of the site unless
28         # the new CTs have been seen (and accept/decline chosen).
29       elsif !@user.terms_seen and flash[:skip_terms].nil?
30         flash[:notice] = t 'user.terms.you need to accept or decline'
31         if params[:referer]
32           redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
33         else
34           redirect_to :controller => "user", :action => "terms", :referer => request.fullpath
35         end
36       end
37     elsif session[:token]
38       if @user = User.authenticate(:token => session[:token])
39         session[:user] = @user.id
40       end
41     end
42   rescue Exception => ex
43     logger.info("Exception authorizing user: #{ex.to_s}")
44     reset_session
45     @user = nil
46   end
47
48   def require_user
49     unless @user
50       if request.get?
51         redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath
52       else
53         render :nothing => true, :status => :forbidden
54       end
55     end
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         report_error "OAuth token doesn't have that capability.", :forbidden
70         return false
71       end
72     end
73   end
74
75   ##
76   # require the user to have cookies enabled in their browser
77   def require_cookies
78     if request.cookies["_osm_session"].to_s == ""
79       if params[:cookie_test].nil?
80         session[:cookie_test] = true
81         redirect_to params.merge(:cookie_test => "true")
82         return false
83       else
84         flash.now[:warning] = t 'application.require_cookies.cookies_needed'
85       end
86     else
87       session.delete(:cookie_test)
88     end
89   end
90
91   # Utility methods to make the controller filter methods easier to read and write.
92   def require_allow_read_prefs
93     require_capability(:allow_read_prefs)
94   end
95   def require_allow_write_prefs
96     require_capability(:allow_write_prefs)
97   end
98   def require_allow_write_diary
99     require_capability(:allow_write_diary)
100   end
101   def require_allow_write_api
102     require_capability(:allow_write_api)
103
104     if REQUIRE_TERMS_AGREED and @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   def require_allow_read_gpx
110     require_capability(:allow_read_gpx)
111   end
112   def require_allow_write_gpx
113     require_capability(:allow_write_gpx)
114   end
115
116   ##
117   # require that the user is a moderator, or fill out a helpful error message
118   # and return them to the index for the controller this is wrapped from.
119   def require_moderator
120     unless @user.moderator?
121       if request.get?
122         flash[:error] = t('application.require_moderator.not_a_moderator')
123         redirect_to :action => 'index'
124       else
125         render :nothing => true, :status => :forbidden
126       end
127     end
128   end
129
130   ##
131   # sets up the @user object for use by other methods. this is mostly called
132   # from the authorize method, but can be called elsewhere if authorisation
133   # is optional.
134   def setup_user_auth
135     # try and setup using OAuth
136     if not Authenticator.new(self, [:token]).allow?
137       username, passwd = get_auth_data # parse from headers
138       # authenticate per-scheme
139       if username.nil?
140         @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
141       elsif username == 'token'
142         @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
143       else
144         @user = User.authenticate(:username => username, :password => passwd) # basic auth
145       end
146     end
147
148     # have we identified the user?
149     if @user
150       # check if the user has been banned
151       if @user.blocks.active.exists?
152         # NOTE: need slightly more helpful message than this.
153         report_error t('application.setup_user_auth.blocked'), :forbidden
154       end
155
156       # if the user hasn't seen the contributor terms then don't
157       # allow editing - they have to go to the web site and see
158       # (but can decline) the CTs to continue.
159       if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
160         set_locale
161         report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
162       end
163     end
164   end
165
166   def authorize(realm='Web Password', errormessage="Couldn't authenticate you") 
167     # make the @user object from any auth sources we have
168     setup_user_auth
169
170     # handle authenticate pass/fail
171     unless @user
172       # no auth, the user does not exist or the password was wrong
173       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\"" 
174       render :text => errormessage, :status => :unauthorized
175       return false
176     end 
177   end 
178
179   ##
180   # to be used as a before_filter *after* authorize. this checks that
181   # the user is a moderator and, if not, returns a forbidden error.
182   #
183   # NOTE: this isn't a very good way of doing it - it duplicates logic
184   # from require_moderator - but what we really need to do is a fairly
185   # drastic refactoring based on :format and respond_to? but not a 
186   # good idea to do that in this branch.
187   def authorize_moderator(errormessage="Access restricted to moderators") 
188     # check user is a moderator
189     unless @user.moderator?
190       render :text => errormessage, :status => :forbidden
191       return false
192     end 
193   end 
194
195   def check_database_readable(need_api = false)
196     if STATUS == :database_offline or (need_api and STATUS == :api_offline)
197       redirect_to :controller => 'site', :action => 'offline'
198     end
199   end
200
201   def check_database_writable(need_api = false)
202     if STATUS == :database_offline or STATUS == :database_readonly or
203        (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
204       redirect_to :controller => 'site', :action => 'offline'
205     end
206   end
207
208   def check_api_readable
209     if STATUS == :database_offline or STATUS == :api_offline
210       report_error "Database offline for maintenance", :service_unavailable
211       return false
212     end
213   end
214
215   def check_api_writable
216     if STATUS == :database_offline or STATUS == :database_readonly or
217        STATUS == :api_offline or STATUS == :api_readonly
218       report_error "Database offline for maintenance", :service_unavailable
219       return false
220     end
221   end
222
223   def require_public_data
224     unless @user.data_public?
225       report_error "You must make your edits public to upload new data", :forbidden
226       return false
227     end
228   end
229
230   # Report and error to the user
231   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
232   #  rather than only a status code and having the web engine make up a 
233   #  phrase from that, we can also put the error message into the status
234   #  message. For now, rails won't let us)
235   def report_error(message, status = :bad_request)
236     # Todo: some sort of escaping of problem characters in the message
237     response.headers['Error'] = message
238
239     if request.headers['X-Error-Format'] and
240        request.headers['X-Error-Format'].downcase == "xml"
241       result = OSM::API.new.get_xml_doc
242       result.root.name = "osmError"
243       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
244       result.root << (XML::Node.new("message") << message)
245
246       render :text => result.to_s, :content_type => "text/xml"
247     else
248       render :text => message, :status => status
249     end
250   end
251   
252   def set_locale
253     response.header['Vary'] = 'Accept-Language'
254
255     if @user
256       if !@user.languages.empty?
257         request.user_preferred_languages = @user.languages
258         response.header['Vary'] = '*'
259       elsif !request.user_preferred_languages.empty?
260         @user.languages = request.user_preferred_languages
261         @user.save
262       end
263     end
264
265     if request.compatible_language_from(I18n.available_locales).nil?
266       request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
267         pls = [ pl ]
268
269         while pl.match(/^(.*)-[^-]+$/)
270           pls.push($1) if I18n.available_locales.include?($1.to_sym)
271           pl = $1
272         end
273
274         pls
275       end.flatten
276
277       if @user and not request.compatible_language_from(I18n.available_locales).nil?
278         @user.languages = request.user_preferred_languages
279         @user.save        
280       end
281     end
282
283     I18n.locale = params[:locale] || request.compatible_language_from(I18n.available_locales) || I18n.default_locale
284
285     response.headers['Content-Language'] = I18n.locale.to_s
286   end
287
288   def api_call_handle_error
289     begin
290       yield
291     rescue ActiveRecord::RecordNotFound => ex
292       render :nothing => true, :status => :not_found
293     rescue LibXML::XML::Error, ArgumentError => ex
294       report_error ex.message, :bad_request
295     rescue ActiveRecord::RecordInvalid => ex
296       message = "#{ex.record.class} #{ex.record.id}: "
297       ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
298       report_error message, :bad_request
299     rescue OSM::APIError => ex
300       report_error ex.message, ex.status
301     rescue AbstractController::ActionNotFound => ex
302       raise
303     rescue Exception => ex
304       logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
305       ex.backtrace.each { |l| logger.info(l) }
306       report_error "#{ex.class}: #{ex.message}", :internal_server_error
307     end
308   end
309
310   ##
311   # asserts that the request method is the +method+ given as a parameter
312   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
313   def assert_method(method)
314     ok = request.send((method.to_s.downcase + "?").to_sym)
315     raise OSM::APIBadMethodError.new(method) unless ok
316   end
317
318   ##
319   # wrap an api call in a timeout
320   def api_call_timeout
321     OSM::Timer.timeout(API_TIMEOUT) do
322       yield
323     end
324   rescue Timeout::Error
325     raise OSM::APITimeoutError
326   end
327
328   ##
329   # wrap a web page in a timeout
330   def web_timeout
331     OSM::Timer.timeout(WEB_TIMEOUT) do
332       yield
333     end
334   rescue ActionView::Template::Error => ex
335     ex = ex.original_exception
336
337     if ex.is_a?(ActiveRecord::StatementInvalid) and ex.message =~ /^Timeout::Error/
338       ex = Timeout::Error.new
339     end
340
341     if ex.is_a?(Timeout::Error)
342       render :action => "timeout"
343     else
344       raise
345     end
346   rescue Timeout::Error
347     render :action => "timeout"
348   end
349
350   ##
351   # extend caches_action to include the parameters, locale and logged in
352   # status in all cache keys
353   def self.caches_action(*actions)
354     options = actions.extract_options!
355     cache_path = options[:cache_path] || Hash.new
356
357     options[:unless] = case options[:unless]
358                        when NilClass then Array.new
359                        when Array then options[:unless]
360                        else unlessp = [ options[:unless] ]
361                        end
362
363     options[:unless].push(Proc.new do |controller|
364       controller.params.include?(:page)
365     end)
366
367     options[:cache_path] = Proc.new do |controller|
368       cache_path.merge(controller.params).merge(:host => SERVER_URL, :locale => I18n.locale)
369     end
370
371     actions.push(options)
372
373     super *actions
374   end
375
376   ##
377   # extend expire_action to expire all variants
378   def expire_action(options = {})
379     I18n.available_locales.each do |locale|
380       super options.merge(:host => SERVER_URL, :locale => locale)
381     end
382   end
383
384   ##
385   # is the requestor logged in?
386   def logged_in?
387     !@user.nil?
388   end
389
390   ##
391   # ensure that there is a "this_user" instance variable
392   def lookup_this_user
393     unless @this_user = User.active.find_by_display_name(params[:display_name])
394       render_unknown_user params[:display_name]
395     end
396   end
397
398   ##
399   # render a "no such user" page
400   def render_unknown_user(name)
401     @title = t "user.no_such_user.title"
402     @not_found_user = name
403
404     respond_to do |format|
405       format.html { render :template => "user/no_such_user", :status => :not_found }
406       format.all { render :nothing => true, :status => :not_found }
407     end
408   end
409
410   ##
411   # Unfortunately if a PUT or POST request that has a body fails to
412   # read it then Apache will sometimes fail to return the response it
413   # is given to the client properly, instead erroring:
414   #
415   #   https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
416   #
417   # To work round this we call rewind on the body here, which is added
418   # as a filter, to force it to be fetched from Apache into a file.
419   def fetch_body
420     request.body.rewind
421   end
422
423 private 
424
425   # extract authorisation credentials from headers, returns user = nil if none
426   def get_auth_data 
427     if request.env.has_key? 'X-HTTP_AUTHORIZATION'          # where mod_rewrite might have put it 
428       authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split 
429     elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION'          # mod_fcgi 
430       authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split 
431     elsif request.env.has_key? 'HTTP_AUTHORIZATION'         # regular location
432       authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
433     end 
434     # only basic authentication supported
435     if authdata and authdata[0] == 'Basic' 
436       user, pass = Base64.decode64(authdata[1]).split(':',2)
437     end 
438     return [user, pass] 
439   end 
440
441   # used by oauth plugin to get the current user
442   def current_user
443     @user
444   end
445
446   # used by oauth plugin to set the current user
447   def current_user=(user)
448     @user=user
449   end
450
451   # override to stop oauth plugin sending errors
452   def invalid_oauth_response
453   end
454
455 end