Sha256: bc7b37bc10bded9db3e38dc07fdccd58d6c48f6f3db6901f513aae7ad17b6c58

Contents?: true

Size: 1.09 KB

Versions: 5

Compression:

Stored size: 1.09 KB

Contents

// This code was heavily inspired by the rails-ujs project.
// Copyright (c) 2007-2021 Rails Core team.
const $ = (selector) => Array.prototype.slice.call(document.querySelectorAll(selector))

// Up-to-date Cross-Site Request Forgery token
export const csrfToken = () => {
  const meta: HTMLMetaElement = document.querySelector("meta[name=csrf-token]")
  return meta && meta.content
}

// URL param that must contain the CSRF token
export const csrfParam = () => {
  const meta: HTMLMetaElement = document.querySelector("meta[name=csrf-param]")
  return meta && meta.content
}

// Make sure that every Ajax request sends the CSRF token
export const CSRFProtection = (xhr) => {
  const token = csrfToken()
  if (token != null) {
    return xhr.setRequestHeader("X-CSRF-Token", token)
  }
}

// Make sure that all forms have actual up-to-date tokens (cached forms contain old ones)
export const refreshCSRFTokens = () => {
  const token = csrfToken()
  const param = csrfParam()

  if (token != null && param != null) {
    return $('sl-form input[name="' + param + '"]').forEach((input) => (input.value = token))
  }
}

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
shoelace-rails-0.4.1 src/turbolinks/utils/csrf.ts
shoelace-rails-0.4.0 src/turbolinks/utils/csrf.ts
shoelace-rails-0.3.0 src/turbolinks/utils/csrf.ts
shoelace-rails-0.2.0 src/turbolinks/utils/csrf.ts
shoelace-rails-0.1.0 src/turbolinks/utils/csrf.ts