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