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