]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
localized link to home location
[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 OSM_STATUS == :database_readonly or OSM_STATUS == :database_offline
6     session :off
7   end
8
9   def authorize_web
10     if session[:user]
11       @user = User.find(session[:user], :conditions => {:visible => true})
12     elsif session[:token]
13       @user = User.authenticate(:token => session[:token])
14       session[:user] = @user.id
15     end
16   rescue Exception => ex
17     logger.info("Exception authorizing user: #{ex.to_s}")
18     @user = nil
19   end
20
21   def require_user
22     redirect_to :controller => 'user', :action => 'login', :referer => request.request_uri unless @user
23   end
24
25   ##
26   # sets up the @user object for use by other methods. this is mostly called
27   # from the authorize method, but can be called elsewhere if authorisation
28   # is optional.
29   def setup_user_auth
30     username, passwd = get_auth_data # parse from headers
31     # authenticate per-scheme
32     if username.nil?
33       @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
34     elsif username == 'token' 
35       @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
36     else
37       @user = User.authenticate(:username => username, :password => passwd) # basic auth
38     end
39   end
40
41   def authorize(realm='Web Password', errormessage="Couldn't authenticate you") 
42     # make the @user object from any auth sources we have
43     setup_user_auth
44
45     # handle authenticate pass/fail
46     unless @user
47       # no auth, the user does not exist or the password was wrong
48       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\"" 
49       render :text => errormessage, :status => :unauthorized
50       return false
51     end 
52   end 
53
54   def check_database_readable(need_api = false)
55     if OSM_STATUS == :database_offline or (need_api and OSM_STATUS == :api_offline)
56       redirect_to :controller => 'site', :action => 'offline'
57     end
58   end
59
60   def check_database_writable(need_api = false)
61     if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
62        (need_api and (OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly))
63       redirect_to :controller => 'site', :action => 'offline'
64     end
65   end
66
67   def check_api_readable
68     if OSM_STATUS == :database_offline or OSM_STATUS == :api_offline
69       response.headers['Error'] = "Database offline for maintenance"
70       render :nothing => true, :status => :service_unavailable
71       return false
72     end
73   end
74
75   def check_api_writable
76     if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
77        OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly
78       response.headers['Error'] = "Database offline for maintenance"
79       render :nothing => true, :status => :service_unavailable
80       return false
81     end
82   end
83
84   def require_public_data
85     unless @user.data_public?
86       response.headers['Error'] = "You must make your edits public to upload new data"
87       render :nothing => true, :status => :forbidden
88       return false
89     end
90   end
91
92   # Report and error to the user
93   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
94   #  rather than only a status code and having the web engine make up a 
95   #  phrase from that, we can also put the error message into the status
96   #  message. For now, rails won't let us)
97   def report_error(message, status = :bad_request)
98     # Todo: some sort of escaping of problem characters in the message
99     response.headers['Error'] = message
100     render :text => message, :status => status
101   end
102   
103   def set_locale
104     response.header['Vary'] = 'Accept-Language'
105
106     if @user
107       if !@user.languages.empty?
108         request.user_preferred_languages = @user.languages
109         response.header['Vary'] = '*'
110       elsif !request.user_preferred_languages.empty?
111         @user.languages = request.user_preferred_languages
112         @user.save
113       end
114     end
115
116     I18n.locale = request.compatible_language_from(I18n.available_locales)
117
118     response.headers['Content-Language'] = I18n.locale.to_s
119   end
120
121   def api_call_handle_error
122     begin
123       yield
124     rescue ActiveRecord::RecordNotFound => ex
125       render :nothing => true, :status => :not_found
126     rescue LibXML::XML::Error, ArgumentError => ex
127       report_error ex.message, :bad_request
128     rescue ActiveRecord::RecordInvalid => ex
129       message = "#{ex.record.class} #{ex.record.id}: "
130       ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
131       report_error message, :bad_request
132     rescue OSM::APIError => ex
133       report_error ex.message, ex.status
134     rescue Exception => ex
135       logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
136       ex.backtrace.each { |l| logger.info(l) }
137       report_error "#{ex.class}: #{ex.message}", :internal_server_error
138     end
139   end
140
141   ##
142   # asserts that the request method is the +method+ given as a parameter
143   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
144   def assert_method(method)
145     ok = request.send((method.to_s.downcase + "?").to_sym)
146     raise OSM::APIBadMethodError.new(method) unless ok
147   end
148
149   def api_call_timeout
150     Timeout::timeout(APP_CONFIG['api_timeout'], OSM::APITimeoutError) do
151       yield
152     end
153   end
154
155 private 
156   # extract authorisation credentials from headers, returns user = nil if none
157   def get_auth_data 
158     if request.env.has_key? 'X-HTTP_AUTHORIZATION'          # where mod_rewrite might have put it 
159       authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split 
160     elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION'          # mod_fcgi 
161       authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split 
162     elsif request.env.has_key? 'HTTP_AUTHORIZATION'         # regular location
163       authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
164     end 
165     # only basic authentication supported
166     if authdata and authdata[0] == 'Basic' 
167       user, pass = Base64.decode64(authdata[1]).split(':',2)
168     end 
169     return [user, pass] 
170   end 
171
172 end