srv2srv_jwtauth_client
Version:
Module for server to server authentication via JWT tokens. Client side. Alpha version. NOT READY FOR USAGE
85 lines (77 loc) • 2.22 kB
JavaScript
let hashing = require('./hashing');
let conn = require('./connection');
/**
* srv_2_srv_jwt is node.js module for server t oserver authentication through the JWT Tokens.
* @constructor
*/
class Srv2srv {
constructor() {
this.credentials = {};
this.token = undefined;
this.passwordHashed = undefined;
this.key = undefined;
}
/**
* Initializes srv_2_srv_jwt has to be called before any methods are called.
* @param {String} user -
* @param {String} password -
* @param {String} name -
* @param {Object} options -
* @param {String} key - key for encrypting and hashing password
*/
init(name = '', user, password, options, key) {
if (!user || !password || !key) {
throw new Error('Credentials and key has to be provided');
}
this.credentials.user = user;
this.credentials.password = password;
this.credentials.name = name;
this.key = key;
this.passwordHashed = (options.passwordHashed) ?
options.passwordHashed :
true;
if (!this.passwordHashed) {
//this.credentials.salt = hashing.getRandomString();
this.credentials.password = hashing.hashingString(
this.credentials.password, this.key);
}
//console.log('[SRV2SRV:] this are credentials: \n', this.credentials);
};
/**
*
* @param {String} address -
*/
auth(address) {
return new Promise ((resolve, reject) => {
if (!address) {
const error = new Error('Address has to be provided');
reject(error);
}
conn.login(this.credentials, address)
.then(response => {
if (response.code === 1) {
this.token = response.token;
console.log('[SRV2SRV]: Auth returned');
resolve(this.token);
} else {
console.log('[SRV2SRV]: ', response.message);
reject(response.message);
}
}).catch(error => {
reject(new Error(error));
})
});
};
/**
*
*/
getToken() {
if (this.token) {
console.log('[SRV2SRV]: in GETTOKEN: ', this.token);
return this.token;
} else {
throw new Error('Token is not defined');
}
}
}
module.exports = new Srv2srv();