]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
Rework the user details screen to be less crap... Highlights include:
[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   # requires the user to be logged in by the token or HTTP methods, or have an 
27   # OAuth token with the right capability. this method is a bit of a pain to call 
28   # directly, since it's cumbersome to call filters with arguments in rails. to
29   # make it easier to read and write the code, there are some utility methods
30   # below.
31   def require_capability(cap)
32     # when the current token is nil, it means the user logged in with a different
33     # method, otherwise an OAuth token was used, which has to be checked.
34     unless current_token.nil?
35       unless current_token.read_attribute(cap)
36         render :text => "OAuth token doesn't have that capability.", :status => :forbidden
37         return false
38       end
39     end
40   end
41
42   ##
43   # require the user to have cookies enabled in their browser
44   def require_cookies
45     if request.cookies["_osm_session"].to_s == ""
46       if params[:cookie_test].nil?
47         redirect_to params.merge(:cookie_test => "true")
48         return false
49       else
50         flash.now[:warning] = t 'application.require_cookies.cookies_needed'
51       end
52     end
53   end
54
55   # Utility methods to make the controller filter methods easier to read and write.
56   def require_allow_read_prefs
57     require_capability(:allow_read_prefs)
58   end
59   def require_allow_write_prefs
60     require_capability(:allow_write_prefs)
61   end
62   def require_allow_write_diary
63     require_capability(:allow_write_diary)
64   end
65   def require_allow_write_api
66     require_capability(:allow_write_api)
67   end
68   def require_allow_read_gpx
69     require_capability(:allow_read_gpx)
70   end
71   def require_allow_write_gpx
72     require_capability(:allow_write_gpx)
73   end
74
75   ##
76   # sets up the @user object for use by other methods. this is mostly called
77   # from the authorize method, but can be called elsewhere if authorisation
78   # is optional.
79   def setup_user_auth
80     # try and setup using OAuth
81     if oauthenticate
82       @user = current_token.user
83     else
84       username, passwd = get_auth_data # parse from headers
85       # authenticate per-scheme
86       if username.nil?
87         @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
88       elsif username == 'token'
89         @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
90       else
91         @user = User.authenticate(:username => username, :password => passwd) # basic auth
92       end
93     end
94
95     # check if the user has been banned
96     unless @user.nil? or @user.active_blocks.empty?
97       # NOTE: need slightly more helpful message than this.
98       render :text => t('application.setup_user_auth.blocked'), :status => :forbidden
99     end
100   end
101
102   def authorize(realm='Web Password', errormessage="Couldn't authenticate you") 
103     # make the @user object from any auth sources we have
104     setup_user_auth
105
106     # handle authenticate pass/fail
107     unless @user
108       # no auth, the user does not exist or the password was wrong
109       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\"" 
110       render :text => errormessage, :status => :unauthorized
111       return false
112     end 
113   end 
114
115   def check_database_readable(need_api = false)
116     if OSM_STATUS == :database_offline or (need_api and OSM_STATUS == :api_offline)
117       redirect_to :controller => 'site', :action => 'offline'
118     end
119   end
120
121   def check_database_writable(need_api = false)
122     if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
123        (need_api and (OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly))
124       redirect_to :controller => 'site', :action => 'offline'
125     end
126   end
127
128   def check_api_readable
129     if OSM_STATUS == :database_offline or OSM_STATUS == :api_offline
130       response.headers['Error'] = "Database offline for maintenance"
131       render :nothing => true, :status => :service_unavailable
132       return false
133     end
134   end
135
136   def check_api_writable
137     if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
138        OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly
139       response.headers['Error'] = "Database offline for maintenance"
140       render :nothing => true, :status => :service_unavailable
141       return false
142     end
143   end
144
145   def require_public_data
146     unless @user.data_public?
147       response.headers['Error'] = "You must make your edits public to upload new data"
148       render :nothing => true, :status => :forbidden
149       return false
150     end
151   end
152
153   # Report and error to the user
154   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
155   #  rather than only a status code and having the web engine make up a 
156   #  phrase from that, we can also put the error message into the status
157   #  message. For now, rails won't let us)
158   def report_error(message, status = :bad_request)
159     # Todo: some sort of escaping of problem characters in the message
160     response.headers['Error'] = message
161     render :text => message, :status => status
162   end
163   
164   def set_locale
165     response.header['Vary'] = 'Accept-Language'
166
167     if @user
168       if !@user.languages.empty?
169         request.user_preferred_languages = @user.languages
170         response.header['Vary'] = '*'
171       elsif !request.user_preferred_languages.empty?
172         @user.languages = request.user_preferred_languages
173         @user.save
174       end
175     end
176
177     I18n.locale = request.compatible_language_from(I18n.available_locales)
178
179     response.headers['Content-Language'] = I18n.locale.to_s
180   end
181
182   def api_call_handle_error
183     begin
184       yield
185     rescue ActiveRecord::RecordNotFound => ex
186       render :nothing => true, :status => :not_found
187     rescue LibXML::XML::Error, ArgumentError => ex
188       report_error ex.message, :bad_request
189     rescue ActiveRecord::RecordInvalid => ex
190       message = "#{ex.record.class} #{ex.record.id}: "
191       ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
192       report_error message, :bad_request
193     rescue OSM::APIError => ex
194       report_error ex.message, ex.status
195     rescue ActionController::UnknownAction => ex
196       raise
197     rescue Exception => ex
198       logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
199       ex.backtrace.each { |l| logger.info(l) }
200       report_error "#{ex.class}: #{ex.message}", :internal_server_error
201     end
202   end
203
204   ##
205   # asserts that the request method is the +method+ given as a parameter
206   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
207   def assert_method(method)
208     ok = request.send((method.to_s.downcase + "?").to_sym)
209     raise OSM::APIBadMethodError.new(method) unless ok
210   end
211
212   def api_call_timeout
213     SystemTimer.timeout_after(APP_CONFIG['api_timeout']) do
214       yield
215     end
216   rescue Timeout::Error
217     raise OSM::APITimeoutError
218   end
219
220   ##
221   # extend caches_action to include the parameters, locale and logged in
222   # status in all cache keys
223   def self.caches_action(*actions)
224     options = actions.extract_options!
225     cache_path = options[:cache_path] || Hash.new
226
227     options[:cache_path] = Proc.new do |controller|
228       user = controller.instance_variable_get("@user")
229
230       case
231       when user.nil? then user = :none
232       when user.display_name == controller.params[:display_name] then user = :self
233       when user.administrator? then user = :administrator
234       when user.moderator? then user = :moderator
235       else user = :other
236       end
237
238       cache_path.merge(controller.params).merge(:locale => I18n.locale, :user => user)
239     end
240
241     actions.push(options)
242
243     super *actions
244   end
245
246   ##
247   # extend expire_action to expire all variants
248   def expire_action(options = {})
249     path = ActionCachePath.path_for(self, options, false).gsub('?', '.').gsub(':', '.')
250     expire_fragment(Regexp.new(Regexp.escape(path) + "\\..*"))
251   end
252
253   ##
254   # is the requestor logged in?
255   def logged_in?
256     !@user.nil?
257   end
258
259 private 
260
261   # extract authorisation credentials from headers, returns user = nil if none
262   def get_auth_data 
263     if request.env.has_key? 'X-HTTP_AUTHORIZATION'          # where mod_rewrite might have put it 
264       authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split 
265     elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION'          # mod_fcgi 
266       authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split 
267     elsif request.env.has_key? 'HTTP_AUTHORIZATION'         # regular location
268       authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
269     end 
270     # only basic authentication supported
271     if authdata and authdata[0] == 'Basic' 
272       user, pass = Base64.decode64(authdata[1]).split(':',2)
273     end 
274     return [user, pass] 
275   end 
276
277 end