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