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