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