aboutsummaryrefslogtreecommitdiffstats
path: root/actionview/app/assets/javascripts/rails-ujs/utils/csrf.coffee
blob: 4eb5ebb414bbf5f40f357ae57e21acfbd2ef40c1 (plain) (blame)
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
#= require ./dom

{ $ } = Rails

# Up-to-date Cross-Site Request Forgery token
csrfToken = Rails.csrfToken = ->
  meta = document.querySelector('meta[name=csrf-token]')
  meta and meta.content

# URL param that must contain the CSRF token
csrfParam = Rails.csrfParam = ->
  meta = document.querySelector('meta[name=csrf-param]')
  meta and meta.content

# Make sure that every Ajax request sends the CSRF token
Rails.CSRFProtection = (xhr) ->
  token = csrfToken()
  xhr.setRequestHeader('X-CSRF-Token', token) if token?

# Make sure that all forms have actual up-to-date tokens (cached forms contain old ones)
Rails.refreshCSRFTokens = ->
  token = csrfToken()
  param = csrfParam()
  if token? and param?
    $('form input[name="' + param + '"]').forEach (input) -> input.value = token