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