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