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