This module depends on
js-cookie
, which is marked as anoptionalDependency
of@uu-cdh/backbone-util
.
This module provides a wrapper for Backbone.sync
that automatically adds the CSRF token header to modifying, same-origin requests. This is useful if the backend uses session authentication (which is the default for frameworks such as Django). The wrapped function can be used as a drop-in replacement for Backbone.sync
. You can also wrap another function with the same interface as Backbone.sync
. In this way, you could create a version of sync
with multiple layers of extensions.
import Backbone from 'backbone';
import { wrapWithCSRF } from '@uu-cdh/backbone-util';
// In this case, we override the sync method for the entire
// application, but you could also override it only for particular
// model or collection classes. See the next section for the meaning
// of the arguments.
Backbone.sync = wrapWithCSRF(null, 'X-CSRFToken', 'csrftoken');
Default export of @uu-cdh/backbone-util/src/csrf.js
, reexported by name from the package index.
Parameters:
sync
, the implementation ofBackbone.sync
that you want to extend. The originalBackbone.sync
is automatically used as a fallback if you passnull
orundefined
.header
, nonempty string with the name of the request header that should contain the CSRF token. There is no default value; consult the documentation of your backend framework on what it should be. In case of uncertainty, tryX-CSRFToken
.cookie
, the name of the cookie that contains the CSRF token. There is no default value; consult the documentation of your backend framework on what it should be. In case of uncertainty, trycsrftoken
.
Return value: a new function with the same interface as Backbone.sync
, described next
Side effects: none
This function is obtained by calling wrapWithCSRF
, described above.
Parameters: identical to those of Backbone.sync
: method
, model
, options
.
Return value: identical to that of the sync
function that was passed as the first argument to wrapWithCSRF
. This is generally a promise-like interface, most likely a jQuery.jqXHR
.
Side effect: almost identical to that of the sync
function that was passed as the first argument to wrapWithCSRF
. Generally, an XMLHttpRequest
is sent (there is no point in adding a CSRF token header otherwise). The response determines the resolution of the returned promise. The only difference with the underlying sync
function is that a request header with the CSRF token is added under the following conditions:
method
is not'read'
.options.method
is not'GET'
or'HEAD'
(it can be unset).- The request URL is on the same host as the current Backbone application.