csrf/csrfUtil.js
/**
* @copyright 2016 Tridium, Inc. All Rights Reserved.
* @author Vikram N
*/
/*jshint browser:true*//* eslint-env browser */
/*global niagara*/
define([], function () {
'use strict';
/**
* An API to get the CSRF token.
*
* @exports nmodule/js/rc/csrf/csrfUtil
*/
var csrfUtil = {};
/**
* Get the URI encoded form of the csrf token.
* @returns {String} CSRF string (encoded)
*
* @example
* <caption>Access the CSRF token and pass to AJAX as a header</caption>
* define(["nmodule/js/rc/csrf/csrfUtil"], function(csrfUtil){
* var csrfToken = csrfUtil.getCsrfToken();
* var headers = {};
* headers[csrfUtil.CSRF_TOKEN_HEADER_KEY] = csrfToken;
* $.ajax("someURI", {
* method: "POST",
* data: "someContent",
* headers : headers
* });
* });
*
*/
csrfUtil.getCsrfToken = function () {
var csrfToken;
if (typeof niagara !== 'undefined' && niagara.env)/*part of global niagara env object*/ {
csrfToken = niagara.env.csrfToken;
}
if (!csrfToken) {
/*Embedded in the form*/
var csrfTokenElem = document.getElementById("csrfToken");
csrfToken = csrfTokenElem && csrfTokenElem.value;
}
return csrfToken && encodeURIComponent(csrfToken);
};
/**
* Csrf token http header key name.
*
* @type {string}
*/
csrfUtil.CSRF_TOKEN_HEADER_KEY = 'x-niagara-csrfToken';
return csrfUtil;
});