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