@webgap/token
Version:
WebGAP Tokenizer module. Handles JWT encoding / decoding features.
105 lines (96 loc) • 2.8 kB
JavaScript
/**
* (C) Copyright 2014 WebGAP (http://www.webgap.eu/).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Created by: ManuelMartins
* Created on: 23-05-2014
*
*/
;
var configuration = require('@webgap/configuration');
var moment = require('moment');
var jwt = require('jwt-simple');
var assert = require('assert');
/**
* Abstract Token utilities
*
* @param {Object} options
* @param {string} options.host - the token generator host
* @param {string} options.validityThreshold - the validation threshold in milliseconds
*
* @returns {AbstractAlgorithm}
* @constructor
*/
function AbstractAlgorithm(options) {
var self = this;
options = options || {};
// algorithm
self.ALGORITHM = 'NONE';
self.host = options.host || configuration.get('SERVER.HOST');
self.validityThreshold = options.validityThreshold || configuration.get('GENERAL.TOKEN.VALIDITY_TIME');
// imports
this.jwt = jwt;
}
/**
* Encodes an object using The
*
* @param data the data to encode
* @returns {*}
*/
AbstractAlgorithm.prototype.encode = function (data) {
assert.ok(data);
throw new Error('Not implemented');
};
/**
* Decodes a specific token encoded in HS512
*
* @param token the token to decode
* @returns {*}
*/
AbstractAlgorithm.prototype.decode = function (token, complete) {
assert.ok(token);
assert.ok(complete);
throw new Error('Not implemented');
};
/**
* Wraps the data into an object containing:
*
* {String} data - the data passed as argument (can be an object)
* {String} host - the host creating the token
* {String} issuedAt - the creation date
* {String} expiresAt - the expire date
*
* @param data the data to encode
* @returns {*}
*/
AbstractAlgorithm.prototype.generateJWTObject = function (data) {
var self = this;
return {
data: data,
host: self.host,
issuedAt: moment(),
expiresAt: moment().add(self.validityThreshold, 'milliseconds')
};
};
/**
* Check whether a token is valid by check is integrity and validity
*
* @param token the token to validate
* @returns {*}
*/
AbstractAlgorithm.prototype.isValid = function (token) {
var decodedToken = this.decode(token, true);
return decodedToken && moment().isBefore(moment(decodedToken.expiresAt));
};
module.exports = AbstractAlgorithm;