Repository navigation
Expand file tree
/
Copy pathturbolinks.rb
More file actions
78 lines (67 loc) · 2.14 KB
/
Copy pathturbolinks.rb
File metadata and controls
78 lines (67 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
module Turbolinks
module XHRHeaders
extend ActiveSupport::Concern
included do
alias_method_chain :_compute_redirect_to_location, :xhr_referer
end
private
def _compute_redirect_to_location_with_xhr_referer(options)
session[:_turbolinks_redirect_to] =
if options == :back && request.headers["X-XHR-Referer"]
_compute_redirect_to_location_without_xhr_referer(request.headers["X-XHR-Referer"])
else
_compute_redirect_to_location_without_xhr_referer(options)
end
end
def set_xhr_redirected_to
if session[:_turbolinks_redirect_to]
response.headers['X-XHR-Redirected-To'] = session.delete :_turbolinks_redirect_to
end
end
end
module Cookies
private
def set_request_method_cookie
cookies[:request_method] = request.request_method
end
end
module XDomainBlocker
private
def same_origin?(a, b)
a = URI.parse URI.escape(a)
b = URI.parse URI.escape(b)
[a.scheme, a.host, a.port] == [b.scheme, b.host, b.port]
end
def abort_xdomain_redirect
to_uri = response.headers['Location'] || ""
current = request.headers['X-XHR-Referer'] || ""
unless to_uri.blank? || current.blank? || same_origin?(current, to_uri)
self.status = 403
end
end
end
module Redirection
extend ActiveSupport::Concern
def redirect_via_turbolinks_to(url = {}, response_status = {})
redirect_to(url, response_status)
self.status = 200
self.response_body = "Turbolinks.visit('#{location}');"
response.content_type = Mime::JS
end
end
class Engine < ::Rails::Engine
initializer :turbolinks_xhr_headers do |config|
ActionController::Base.class_eval do
include XHRHeaders, Cookies, XDomainBlocker, Redirection
before_filter :set_xhr_redirected_to, :set_request_method_cookie
after_filter :abort_xdomain_redirect
end
ActionDispatch::Request.class_eval do
def referer
self.headers['X-XHR-Referer'] || super
end
alias referrer referer
end
end
end
end