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