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