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