]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
Fix new rubocop warnings
[rails.git] / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include SessionPersistence
3
4   protect_from_forgery :with => :exception
5
6   add_flash_types :warning, :error
7
8   rescue_from CanCan::AccessDenied, :with => :deny_access
9   check_authorization
10
11   before_action :fetch_body
12   around_action :better_errors_allow_inline, :if => proc { Rails.env.development? }
13
14   attr_accessor :current_user, :oauth_token
15
16   helper_method :current_user
17   helper_method :oauth_token
18   helper_method :preferred_langauges
19
20   private
21
22   def authorize_web
23     if session[:user]
24       self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
25
26       if current_user.status == "suspended"
27         session.delete(:user)
28         session_expires_automatically
29
30         redirect_to :controller => "users", :action => "suspended"
31
32       # don't allow access to any auth-requiring part of the site unless
33       # the new CTs have been seen (and accept/decline chosen).
34       elsif !current_user.terms_seen && flash[:skip_terms].nil?
35         flash[:notice] = t "users.terms.you need to accept or decline"
36         if params[:referer]
37           redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
38         else
39           redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
40         end
41       end
42     elsif session[:token]
43       session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
44     end
45   rescue StandardError => e
46     logger.info("Exception authorizing user: #{e}")
47     reset_session
48     self.current_user = nil
49   end
50
51   def require_user
52     unless current_user
53       if request.get?
54         redirect_to :controller => "users", :action => "login", :referer => request.fullpath
55       else
56         head :forbidden
57       end
58     end
59   end
60
61   def require_oauth
62     @oauth_token = current_user.access_token(Settings.oauth_key) if current_user && Settings.key?(:oauth_key)
63   end
64
65   ##
66   # require the user to have cookies enabled in their browser
67   def require_cookies
68     if request.cookies["_osm_session"].to_s == ""
69       if params[:cookie_test].nil?
70         session[:cookie_test] = true
71         redirect_to params.to_unsafe_h.merge(:only_path => true, :cookie_test => "true")
72         false
73       else
74         flash.now[:warning] = t "application.require_cookies.cookies_needed"
75       end
76     else
77       session.delete(:cookie_test)
78     end
79   end
80
81   def check_database_readable(need_api = false)
82     if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
83       if request.xhr?
84         report_error "Database offline for maintenance", :service_unavailable
85       else
86         redirect_to :controller => "site", :action => "offline"
87       end
88     end
89   end
90
91   def check_database_writable(need_api = false)
92     if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
93        (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
94       if request.xhr?
95         report_error "Database offline for maintenance", :service_unavailable
96       else
97         redirect_to :controller => "site", :action => "offline"
98       end
99     end
100   end
101
102   def check_api_readable
103     if api_status == "offline"
104       report_error "Database offline for maintenance", :service_unavailable
105       false
106     end
107   end
108
109   def check_api_writable
110     unless api_status == "online"
111       report_error "Database offline for maintenance", :service_unavailable
112       false
113     end
114   end
115
116   def database_status
117     case Settings.status
118     when "database_offline"
119       "offline"
120     when "database_readonly"
121       "readonly"
122     else
123       "online"
124     end
125   end
126
127   def api_status
128     status = database_status
129     if status == "online"
130       case Settings.status
131       when "api_offline"
132         status = "offline"
133       when "api_readonly"
134         status = "readonly"
135       end
136     end
137     status
138   end
139
140   def require_public_data
141     unless current_user.data_public?
142       report_error "You must make your edits public to upload new data", :forbidden
143       false
144     end
145   end
146
147   # Report and error to the user
148   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
149   #  rather than only a status code and having the web engine make up a
150   #  phrase from that, we can also put the error message into the status
151   #  message. For now, rails won't let us)
152   def report_error(message, status = :bad_request)
153     # TODO: some sort of escaping of problem characters in the message
154     response.headers["Error"] = message
155
156     if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
157       result = OSM::API.new.get_xml_doc
158       result.root.name = "osmError"
159       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
160       result.root << (XML::Node.new("message") << message)
161
162       render :xml => result.to_s
163     else
164       render :plain => message, :status => status
165     end
166   end
167
168   def preferred_languages(reset = false)
169     @preferred_languages = nil if reset
170     @preferred_languages ||= if params[:locale]
171                                Locale.list(params[:locale])
172                              elsif current_user
173                                current_user.preferred_languages
174                              else
175                                Locale.list(http_accept_language.user_preferred_languages)
176                              end
177   end
178
179   helper_method :preferred_languages
180
181   def set_locale(reset = false)
182     if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
183       current_user.languages = http_accept_language.user_preferred_languages
184       current_user.save
185     end
186
187     I18n.locale = Locale.available.preferred(preferred_languages(reset))
188
189     response.headers["Vary"] = "Accept-Language"
190     response.headers["Content-Language"] = I18n.locale.to_s
191   end
192
193   def api_call_handle_error
194     yield
195   rescue ActionController::UnknownFormat
196     head :not_acceptable
197   rescue ActiveRecord::RecordNotFound => e
198     head :not_found
199   rescue LibXML::XML::Error, ArgumentError => e
200     report_error e.message, :bad_request
201   rescue ActiveRecord::RecordInvalid => e
202     message = "#{e.record.class} #{e.record.id}: "
203     e.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{e.record[attr].inspect})" }
204     report_error message, :bad_request
205   rescue OSM::APIError => e
206     report_error e.message, e.status
207   rescue AbstractController::ActionNotFound => e
208     raise
209   rescue StandardError => e
210     logger.info("API threw unexpected #{e.class} exception: #{e.message}")
211     e.backtrace.each { |l| logger.info(l) }
212     report_error "#{e.class}: #{e.message}", :internal_server_error
213   end
214
215   ##
216   # asserts that the request method is the +method+ given as a parameter
217   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
218   def assert_method(method)
219     ok = request.send((method.to_s.downcase + "?").to_sym)
220     raise OSM::APIBadMethodError, method unless ok
221   end
222
223   ##
224   # wrap an api call in a timeout
225   def api_call_timeout
226     OSM::Timer.timeout(Settings.api_timeout, Timeout::Error) do
227       yield
228     end
229   rescue Timeout::Error
230     raise OSM::APITimeoutError
231   end
232
233   ##
234   # wrap a web page in a timeout
235   def web_timeout
236     OSM::Timer.timeout(Settings.web_timeout, Timeout::Error) do
237       yield
238     end
239   rescue ActionView::Template::Error => e
240     e = e.cause
241
242     if e.is_a?(Timeout::Error) ||
243        (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
244       render :action => "timeout"
245     else
246       raise
247     end
248   rescue Timeout::Error
249     render :action => "timeout"
250   end
251
252   ##
253   # ensure that there is a "user" instance variable
254   def lookup_user
255     render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
256   end
257
258   ##
259   # render a "no such user" page
260   def render_unknown_user(name)
261     @title = t "users.no_such_user.title"
262     @not_found_user = name
263
264     respond_to do |format|
265       format.html { render :template => "users/no_such_user", :status => :not_found }
266       format.all { head :not_found }
267     end
268   end
269
270   ##
271   # Unfortunately if a PUT or POST request that has a body fails to
272   # read it then Apache will sometimes fail to return the response it
273   # is given to the client properly, instead erroring:
274   #
275   #   https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
276   #
277   # To work round this we call rewind on the body here, which is added
278   # as a filter, to force it to be fetched from Apache into a file.
279   def fetch_body
280     request.body.rewind
281   end
282
283   def map_layout
284     append_content_security_policy_directives(
285       :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
286       :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
287       :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url],
288       :form_action => %w[render.openstreetmap.org],
289       :style_src => %w['unsafe-inline']
290     )
291
292     case Settings.status
293     when "database_offline", "api_offline"
294       flash.now[:warning] = t("layouts.osm_offline")
295     when "database_readonly", "api_readonly"
296       flash.now[:warning] = t("layouts.osm_read_only")
297     end
298
299     request.xhr? ? "xhr" : "map"
300   end
301
302   def allow_thirdparty_images
303     append_content_security_policy_directives(:img_src => %w[*])
304   end
305
306   def preferred_editor
307     if params[:editor]
308       params[:editor]
309     elsif current_user&.preferred_editor
310       current_user.preferred_editor
311     else
312       Settings.default_editor
313     end
314   end
315
316   helper_method :preferred_editor
317
318   def update_totp
319     if Settings.key?(:totp_key)
320       cookies["_osm_totp_token"] = {
321         :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
322         :domain => "openstreetmap.org",
323         :expires => 1.hour.from_now
324       }
325     end
326   end
327
328   def better_errors_allow_inline
329     yield
330   rescue StandardError
331     append_content_security_policy_directives(
332       :script_src => %w['unsafe-inline'],
333       :style_src => %w['unsafe-inline']
334     )
335
336     raise
337   end
338
339   def current_ability
340     Ability.new(current_user)
341   end
342
343   def deny_access(_exception)
344     if current_token
345       set_locale
346       report_error t("oauth.permissions.missing"), :forbidden
347     elsif current_user
348       set_locale
349       respond_to do |format|
350         format.html { redirect_to :controller => "errors", :action => "forbidden" }
351         format.any { report_error t("application.permission_denied"), :forbidden }
352       end
353     elsif request.get?
354       respond_to do |format|
355         format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
356         format.any { head :forbidden }
357       end
358     else
359       head :forbidden
360     end
361   end
362
363   # extract authorisation credentials from headers, returns user = nil if none
364   def get_auth_data
365     if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
366       authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
367     elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
368       authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
369     elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
370       authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
371     end
372     # only basic authentication supported
373     user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
374     [user, pass]
375   end
376
377   # override to stop oauth plugin sending errors
378   def invalid_oauth_response; end
379
380   # clean any referer parameter
381   def safe_referer(referer)
382     referer = URI.parse(referer)
383
384     if referer.scheme == "http" || referer.scheme == "https"
385       referer.scheme = nil
386       referer.host = nil
387       referer.port = nil
388     elsif referer.scheme || referer.host || referer.port
389       referer = nil
390     end
391
392     referer.to_s
393   end
394 end