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