Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const logger = require('./logger')('RsaJwt');
- const NodeRSA = require('node-rsa');
- const jwt = require('jsonwebtoken');
- const fs = require('fs');
- const generateAndSaveKeyPair = (keyPath) => {
- logger.debug('Generating private and public key for JWT sessions...');
- const keyPair = new NodeRSA({b: 2048});
- const privateKey = keyPair.exportKey('private');
- const publicKey = keyPair.exportKey('public');
- if(keyPath) fs.writeFileSync(keyPath, privateKey, 'utf-8');
- logger.success('Done');
- return [privateKey, publicKey];
- };
- const loadKeyPair = (keyPath) => {
- const privateKey = fs.readFileSync(keyPath, 'utf-8');
- logger.debug('Loading private and public key for JWT sessions...');
- const keyPair = new NodeRSA();
- keyPair.importKey(privateKey, 'private');
- const publicKey = keyPair.exportKey('public');
- logger.success('Done');
- return [privateKey, publicKey];
- };
- const rsaJwt = (keyPath) => {
- let invalidationCounterByUserUUID,
- invalidBefore;
- let publicKey,
- privateKey;
- const generateNewKeyPair = async () => {
- [privateKey, publicKey] = generateAndSaveKeyPair(keyPath);
- invalidationCounterByUserUUID = {};
- invalidBefore = Math.floor(new Date().getTime()/1000);
- };
- const sign = (payload) => {
- payload.invalidationCounter = invalidationCounterByUserUUID[payload.userUuid] || 0;
- return jwt.sign(payload, privateKey, {algorithm:'RS256'});
- };
- const verify = (token) => {
- try {
- const payload = jwt.verify(token, publicKey, {algorithm:['RS256']});
- const notInvalidated = !invalidationCounterByUserUUID[payload.userUuid] || payload.invalidationCounter === invalidationCounterByUserUUID[payload.userUuid];
- const hasValidIat = payload.iat >= invalidBefore;
- return (notInvalidated && hasValidIat) ? payload : false;
- }
- catch(error) {
- logger.warning(error);
- return false;
- }
- };
- const invalidateUserTokens = (userUuid) => {
- invalidationCounterByUserUUID[userUuid] = invalidationCounterByUserUUID[userUuid]+1 || 1;
- };
- // INIT
- if(keyPath) {
- try {
- [privateKey, publicKey] = loadKeyPair(keyPath);
- }
- catch(error) {
- if(error.code !== 'ENOENT') {
- logger.fatal(error);
- }
- }
- }
- if(!privateKey) generateNewKeyPair();
- // !INIT
- return {
- generateNewKeyPair,
- sign,
- verify,
- invalidateUserTokens
- };
- };
- module.exports = rsaJwt;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement