Advertisement
Guest User

Untitled

a guest
Jul 7th, 2019
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. const logger = require('./logger')('RsaJwt');
  4. const NodeRSA = require('node-rsa');
  5. const jwt = require('jsonwebtoken');
  6. const fs = require('fs');
  7.  
  8. const rsaJwt = (keyPath) => {
  9.   let invalidationCounterByUserUuid;
  10.   let invalidBefore;
  11.  
  12.   let privateKey;
  13.   let publicKey;
  14.  
  15.   // INIT
  16.   if(keyPath && fs.existsSync(keyPath)) {
  17.     logger.debug('Loading private and public key for JWT sessions...');
  18.     const keyPair = new NodeRSA();
  19.     privateKey = fs.readFileSync(keyPath, 'utf-8');
  20.     keyPair.importKey(privateKey, 'private');
  21.     publicKey = keyPair.exportKey('public');
  22.     logger.success('Done');
  23.  
  24.     resetInvalidation();
  25.   }
  26.   else generateNewKeyPair();
  27.   // !INIT
  28.  
  29.   function resetInvalidation() {
  30.       invalidationCounterByUserUuid = {};
  31.       invalidBefore = Math.floor(new Date().getTime()/1000);
  32.   }
  33.  
  34.   function generateNewKeyPair() {
  35.     logger.debug('Generating private and public key for JWT sessions...');
  36.     const keyPair = new NodeRSA({ b: 2048 });
  37.     privateKey = keyPair.exportKey('private');
  38.     publicKey = keyPair.exportKey('public');
  39.     if(keyPath) fs.writeFileSync(keyPath, privateKey, 'utf-8');
  40.     logger.success('Done');
  41.  
  42.     resetInvalidation();
  43.   }
  44.  
  45.   function sign(payload) {
  46.     payload.invalidationCounter = invalidationCounterByUserUuid[payload.userUuid] || 0;
  47.     return jwt.sign(payload, privateKey, { algorithm:'RS256' });
  48.   }
  49.  
  50.   function verify(token) {
  51.     try {
  52.       const payload = jwt.verify(token, publicKey, { algorithm: ['RS256'] });
  53.       const notInvalidated = !invalidationCounterByUserUuid[payload.userUuid] || payload.invalidationCounter === invalidationCounterByUserUuid[payload.userUuid];
  54.       const hasValidIat = payload.iat >= invalidBefore;
  55.       return (notInvalidated && hasValidIat) ? payload : false;
  56.     }
  57.     catch(error) {
  58.       logger.warning(error);
  59.       return false;
  60.     }
  61.   }
  62.  
  63.   function invalidateUserTokens (userUuid) {
  64.     invalidationCounterByUserUuid[userUuid] = ++invalidationCounterByUserUuid[userUuid] || 1;
  65.   }
  66.  
  67.   return { generateNewKeyPair, sign, verify, invalidateUserTokens };
  68. }
  69.  
  70. module.exports = rsaJwt;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement