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