UNPKG

@breautek/storm

Version:

Object-Oriented REST API framework

80 lines (77 loc) 2.81 kB
"use strict"; /* Copyright 2017-2021 Norman Breau 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. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.TokenManager = void 0; const tslib_1 = require("tslib"); const jwt = tslib_1.__importStar(require("jsonwebtoken")); const Token_1 = require("./Token"); const JWTVerifyOptionsParser_1 = require("./JWTVerifyOptionsParser"); const crypto_1 = require("crypto"); // const TAG: string = 'TokenManager'; class TokenManager { constructor(secret) { this.$secret = secret; } sign(payload, expiresIn) { return new Promise((resolve, reject) => { (0, crypto_1.randomBytes)(64, (err, buffer) => { if (err) { reject(err); return; } payload.__bt__salt = buffer.toString('hex'); jwt.sign(payload, this.$secret, { expiresIn: expiresIn }, (error, token) => { if (error) { return reject(error); } return resolve(new Token_1.Token(token)); }); }); }); } verify(token, options) { return new Promise((resolve, reject) => { // placed inside the promise in the event that a reject would be required. if (!options) { options = { enableExpiration: true }; } else if (options.enableExpiration === undefined) { options.enableExpiration = true; } jwt.verify(token.getSignature(), this.$secret, JWTVerifyOptionsParser_1.JWTVerifyOptionsParser.parse(options), (error, decoded) => { if (error) { return reject(error); } return resolve(decoded); }); }); } decode(token) { return new Promise((resolve, reject) => { try { let decoded = jwt.decode(token.getSignature()); resolve(decoded); } catch (ex) { reject(ex); } }); } } exports.TokenManager = TokenManager; //# sourceMappingURL=TokenManager.js.map