All files / app/assets/javascripts/lib/utils csrf.js

100% Statements 11/11
100% Branches 4/4
100% Functions 4/4
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                        1996x   2003x   2003x 5x   1998x         3001x       2443x       140x 1x       139x       1996x      
/*
This module provides easy access to the CSRF token and caches
it for re-use. It also exposes some values commonly used in relation
to the CSRF token (header key and headers object).
 
If you need to refresh the csrfToken for some reason, just call `init` and
then use the accessors as you would normally.
 
If you need to compose a headers object, use the spread operator:
 
```
  headers: {
    ...csrf.headers,
    someOtherHeader: '12345',
  }
```
 
see also http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf
and https://github.com/rails/jquery-rails/blob/v4.3.1/vendor/assets/javascripts/jquery_ujs.js#L59-L62
 */
const csrf = {
  init() {
    const tokenEl = document.querySelector('meta[name=csrf-token]');
 
    if (tokenEl !== null) {
      this.csrfToken = tokenEl.getAttribute('content');
    } else {
      this.csrfToken = null;
    }
  },
 
  get token() {
    return this.csrfToken;
  },
 
  get headerKey() {
    return 'X-CSRF-Token';
  },
 
  get headers() {
    if (this.csrfToken !== null) {
      return {
        [this.headerKey]: this.token,
      };
    }
    return {};
  },
};
 
csrf.init();
 
export default csrf;