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