"use strict";
// var crypto = require('crypto');
import sha1 from 'crypto-js/sha1';
import Base64 from 'crypto-js/enc-base64';
// var passwordDigest = require('../utils').passwordDigest;
import { passwordDigest } from '../utils';
var validPasswordTypes = ['PasswordDigest', 'PasswordText'];
export function WSSecurity(username, password, options) {
options = options || {};
this._username = username;
this._password = password;
//must account for backward compatibility for passwordType String param as well as object options defaults: passwordType = 'PasswordText', hasTimeStamp = true
if (typeof options === 'string') {
this._passwordType = options ? options : 'PasswordText';
options = {};
} else {
this._passwordType = options.passwordType ? options.passwordType : 'PasswordText';
}
if (validPasswordTypes.indexOf(this._passwordType) === -1) {
this._passwordType = 'PasswordText';
}
this._hasTimeStamp = options.hasTimeStamp || typeof options.hasTimeStamp === 'boolean' ? !!options.hasTimeStamp : true;
/*jshint eqnull:true */
if (options.hasNonce != null) {
this._hasNonce = !!options.hasNonce;
}
this._hasTokenCreated = options.hasTokenCreated || typeof options.hasTokenCreated === 'boolean' ? !!options.hasTokenCreated : true;
if (options.actor != null) {
this._actor = options.actor;
}
if (options.mustUnderstand != null) {
this._mustUnderstand = !!options.mustUnderstand;
}
}
WSSecurity.prototype.toXML = function() {
// avoid dependency on date formatting libraries
function getDate(d) {
function pad(n) {
return n < 10 ? '0' + n : n;
}
return d.getUTCFullYear() + '-'
+ pad(d.getUTCMonth() + 1) + '-'
+ pad(d.getUTCDate()) + 'T'
+ pad(d.getUTCHours()) + ':'
+ pad(d.getUTCMinutes()) + ':'
+ pad(d.getUTCSeconds()) + 'Z';
}
var now = new Date();
var created = getDate(now);
var timeStampXml = '';
if (this._hasTimeStamp) {
var expires = getDate( new Date(now.getTime() + (1000 * 600)) );
timeStampXml = "" +
""+created+"" +
""+expires+"" +
"";
}
var password, nonce;
if (this._hasNonce || this._passwordType !== 'PasswordText') {
// nonce = base64 ( sha1 ( created + random ) )
// var nHash = crypto.createHash('sha1');
// nHash.update(created + Math.random());
// nonce = nHash.digest('base64');
nonce = Base64.stringify(sha1(created + Math.random(), ''));
}
if (this._passwordType === 'PasswordText') {
password = "" + this._password + "";
if (nonce) {
password += "" + nonce + "";
}
} else {
password = "" + passwordDigest(nonce, created, this._password) + "" +
"" + nonce + "";
}
return "" +
timeStampXml +
"" +
"" + this._username + "" +
password +
(this._hasTokenCreated ? "" + created + "" : "") +
"" +
"";
};
// module.exports = WSSecurity;