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