plivo
Version:
A Node.js SDK to make voice calls and send SMS using Plivo and to generate Plivo XML
79 lines (71 loc) • 2.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AccessToken = AccessToken;
var jwt = require('jsonwebtoken');
function AccessToken(authId, authToken, username) {
var validityOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var uid = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
this.authId = authId || process.env.PLIVO_AUTH_ID;
this.key = authToken || process.env.PLIVO_AUTH_TOKEN;
this.username = username;
if (this.authId == null) {
throw new Error("Please provide authId");
}
if (this.key == null) {
throw new Error("Please provide authToken");
}
if (this.username == null) {
throw new Error("Please provide username");
}
if (validityOptions.validFrom != null) {
if (validityOptions.lifetime != null && validityOptions.validTill != null) {
throw new Error("Please define at maximum any two of validFrom, lifetime and validTill");
}
this.validFrom = validityOptions.validFrom;
if (validityOptions.validTill != null) {
this.lifetime = validityOptions.validTill - this.validFrom;
} else {
this.lifetime = validityOptions.lifetime || 86400;
}
} else {
this.lifetime = validityOptions.lifetime || 86400;
if (validityOptions.validTill != null) {
this.validFrom = validityOptions.validTill - this.lifetime;
} else {
this.validFrom = new Date().getTime() / 1000;
}
}
this.uid = uid || this.username + "-" + new Date().getTime();
}
AccessToken.prototype = {
addVoiceGrants: function addVoiceGrants() {
var incoming = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var outgoing = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
this.grants = {
voice: {
incoming_allow: incoming,
outgoing_allow: outgoing
}
};
},
toJwt: function toJwt() {
var payload = {
jti: this.uid,
iss: this.authId,
sub: this.username,
nbf: Math.floor(this.validFrom),
exp: Math.floor(this.validFrom + this.lifetime),
grants: this.grants
};
var options = {
header: {
typ: "JWT",
cty: "plivo;v=1"
},
noTimestamp: true
};
return jwt.sign(payload, this.key, options);
}
};