UNPKG

@webgap/token

Version:

WebGAP Tokenizer module. Handles JWT encoding / decoding features.

78 lines (70 loc) 2.24 kB
/** * (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 * */ "use strict"; var AbstractAlgorithm = require('./abstract.js'); var fs = require('fs'); var util = require('util'); /** * RS256 Algorithm implementation * * @param {Object} options * @param {string} options.privateKeyPath * @param {string} options.publicKeyPath * @constructor */ function RS256Algorithm(options) { RS256Algorithm.super_.apply(this, arguments); var self = this; options = options || {}; // algorithm self.ALGORITHM = 'RS256'; // load certificates if (!options.privateKeyPath || !options.publicKeyPath) { console.error('Parameter \'options.privateKeyPath\' or \'options.publicKeyPath\' are missing.'); throw new Error('Parameter \'options.privateKeyPath\' or \'options.publicKeyPath\' are missing.'); } self.pem = fs.readFileSync(options.privateKeyPath).toString('ascii'); self.cert = fs.readFileSync(options.publicKeyPath).toString('ascii'); } /* inherit AbstractAlgorithm Module */ util.inherits(RS256Algorithm, AbstractAlgorithm); /** * {@inheritDoc} */ RS256Algorithm.prototype.encode = function (data) { return this.jwt.encode(this.generateJWTObject(data), this.pem, this.ALGORITHM); }; /** * {@inheritDoc} */ RS256Algorithm.prototype.decode = function (token, complete) { var decodedToken = null; try { decodedToken = this.jwt.decode(token, this.cert); if (!complete) { decodedToken = decodedToken.data; } } catch (error) { console.warn("Could not decode token! " + error); decodedToken = false; } return decodedToken; }; module.exports = RS256Algorithm;