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