@peer5/user-auth
Version:
Library to generate user token for the Peer5 user authentication system
36 lines (33 loc) • 1.46 kB
JavaScript
const ectoken = require('ectoken').V3;
const IPV4_REGEX = /\b(?:(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b/i;
/**
*
* @param {string} secret - secret shared between Peer5 and the authenticating partner
* @param {string} customerId - identifier of the account being used to authenticate
* @param {{ip: string | null, expirationMinutes: number}} [options]
* @returns {String}
*/
exports.encrypt = function(secret, customerId, options) {
const opts = options || {};
if (!secret || !customerId) {
throw new Error('secret and customerId are mandatory parameters');
}
if (typeof secret !== 'string' || typeof customerId !== 'string') {
throw new Error('secret and customerId must be string values');
}
if(customerId.length !== 20){
throw new Error('invalid customerId, value should be 20 characters only');
}
if (opts.expirationMinutes && typeof opts.expirationMinutes !== 'number') {
throw new Error('options.expirationMinutes must be a number');
}
if (opts.ip && (typeof opts.ip !== 'string' || !IPV4_REGEX.test(opts.ip))) {
throw new Error('options.ip must be a string and valid IPv4');
}
const authObj = {
customerId: customerId,
expiration: Date.now() + (opts.expirationMinutes || 3) * 60 * 1000,
ip: opts.ip
};
return ectoken.encrypt(secret, JSON.stringify(authObj), false);
};