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