Module: CacheableCSRFTokenRails

Defined in:
lib/cacheable-csrf-token-rails.rb

Overview

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
# File 'lib/cacheable-csrf-token-rails.rb', line 4

def self.included(base)

  ApplicationController.const_set "TOKEN_PLACEHOLDER", "__CROSS_SITE_REQUEST_FORGERY_PROTECTION_TOKEN__"
  base.class_eval do
    after_filter  :inject_csrf_token

    private
    def inject_csrf_token
      if protect_against_forgery? && token = session['_csrf_token']
        if body_with_token = response.body.gsub!(ApplicationController::TOKEN_PLACEHOLDER, token)
          response.body = body_with_token
        end
      end
    end
  end

  ActionView::Helpers::FormTagHelper.class_eval do
    alias_method :token_tag_rails, :token_tag

    def token_tag(token=nil)
      if token != false && protect_against_forgery?
        token ||= form_authenticity_token
        tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => ApplicationController::TOKEN_PLACEHOLDER)
      else
        ''
      end
    end
  end

  ActionView::Helpers::CsrfHelper.class_eval do
    def csrf_meta_tags
      if protect_against_forgery?
        [
          tag('meta', :name => 'csrf-param', :content => request_forgery_protection_token),
          tag('meta', :name => 'csrf-token', :content => ApplicationController::TOKEN_PLACEHOLDER)
        ].join("\n").html_safe
      end
    end
  end

end