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