]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
Add <title> to /blocks and don't Camel Case headings
[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   # Utility methods to make the controller filter methods easier to read and write.
43   def require_allow_read_prefs
44     require_capability(:allow_read_prefs)
45   end
46   def require_allow_write_prefs
47     require_capability(:allow_write_prefs)
48   end
49   def require_allow_write_diary
50     require_capability(:allow_write_diary)
51   end
52   def require_allow_write_api
53     require_capability(:allow_write_api)
54   end
55   def require_allow_read_gpx
56     require_capability(:allow_read_gpx)
57   end
58   def require_allow_write_gpx
59     require_capability(:allow_write_gpx)
60   end
61
62   ##
63   # sets up the @user object for use by other methods. this is mostly called
64   # from the authorize method, but can be called elsewhere if authorisation
65   # is optional.
66   def setup_user_auth
67     # try and setup using OAuth
68     if oauthenticate
69       @user = current_token.user
70     else
71       username, passwd = get_auth_data # parse from headers
72       # authenticate per-scheme
73       if username.nil?
74         @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
75       elsif username == 'token'
76         @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
77       else
78         @user = User.authenticate(:username => username, :password => passwd) # basic auth
79       end
80     end
81
82     # check if the user has been banned
83     unless @user.nil? or @user.active_blocks.empty?
84       # NOTE: need slightly more helpful message than this.
85       render :text => t('application.setup_user_auth.blocked'), :status => :forbidden
86     end
87   end
88
89   def authorize(realm='Web Password', errormessage="Couldn't authenticate you") 
90     # make the @user object from any auth sources we have
91     setup_user_auth
92
93     # handle authenticate pass/fail
94     unless @user
95       # no auth, the user does not exist or the password was wrong
96       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\"" 
97       render :text => errormessage, :status => :unauthorized
98       return false
99     end 
100   end 
101
102   def check_database_readable(need_api = false)
103     if OSM_STATUS == :database_offline or (need_api and OSM_STATUS == :api_offline)
104       redirect_to :controller => 'site', :action => 'offline'
105     end
106   end
107
108   def check_database_writable(need_api = false)
109     if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
110        (need_api and (OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly))
111       redirect_to :controller => 'site', :action => 'offline'
112     end
113   end
114
115   def check_api_readable
116     if OSM_STATUS == :database_offline or OSM_STATUS == :api_offline
117       response.headers['Error'] = "Database offline for maintenance"
118       render :nothing => true, :status => :service_unavailable
119       return false
120     end
121   end
122
123   def check_api_writable
124     if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
125        OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly
126       response.headers['Error'] = "Database offline for maintenance"
127       render :nothing => true, :status => :service_unavailable
128       return false
129     end
130   end
131
132   def require_public_data
133     unless @user.data_public?
134       response.headers['Error'] = "You must make your edits public to upload new data"
135       render :nothing => true, :status => :forbidden
136       return false
137     end
138   end
139
140   # Report and error to the user
141   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
142   #  rather than only a status code and having the web engine make up a 
143   #  phrase from that, we can also put the error message into the status
144   #  message. For now, rails won't let us)
145   def report_error(message, status = :bad_request)
146     # Todo: some sort of escaping of problem characters in the message
147     response.headers['Error'] = message
148     render :text => message, :status => status
149   end
150   
151   def set_locale
152     response.header['Vary'] = 'Accept-Language'
153
154     if @user
155       if !@user.languages.empty?
156         request.user_preferred_languages = @user.languages
157         response.header['Vary'] = '*'
158       elsif !request.user_preferred_languages.empty?
159         @user.languages = request.user_preferred_languages
160         @user.save
161       end
162     end
163
164     I18n.locale = request.compatible_language_from(I18n.available_locales)
165
166     response.headers['Content-Language'] = I18n.locale.to_s
167   end
168
169   def api_call_handle_error
170     begin
171       yield
172     rescue ActiveRecord::RecordNotFound => ex
173       render :nothing => true, :status => :not_found
174     rescue LibXML::XML::Error, ArgumentError => ex
175       report_error ex.message, :bad_request
176     rescue ActiveRecord::RecordInvalid => ex
177       message = "#{ex.record.class} #{ex.record.id}: "
178       ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
179       report_error message, :bad_request
180     rescue OSM::APIError => ex
181       report_error ex.message, ex.status
182     rescue Exception => ex
183       logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
184       ex.backtrace.each { |l| logger.info(l) }
185       report_error "#{ex.class}: #{ex.message}", :internal_server_error
186     end
187   end
188
189   ##
190   # asserts that the request method is the +method+ given as a parameter
191   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
192   def assert_method(method)
193     ok = request.send((method.to_s.downcase + "?").to_sym)
194     raise OSM::APIBadMethodError.new(method) unless ok
195   end
196
197   def api_call_timeout
198     Timeout::timeout(APP_CONFIG['api_timeout'], OSM::APITimeoutError) do
199       yield
200     end
201   end
202
203 private 
204   # extract authorisation credentials from headers, returns user = nil if none
205   def get_auth_data 
206     if request.env.has_key? 'X-HTTP_AUTHORIZATION'          # where mod_rewrite might have put it 
207       authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split 
208     elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION'          # mod_fcgi 
209       authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split 
210     elsif request.env.has_key? 'HTTP_AUTHORIZATION'         # regular location
211       authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
212     end 
213     # only basic authentication supported
214     if authdata and authdata[0] == 'Basic' 
215       user, pass = Base64.decode64(authdata[1]).split(':',2)
216     end 
217     return [user, pass] 
218   end 
219
220 end