Guest User

Untitled

a guest
Jul 7th, 2019
99
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. class rsaJwt {
  9.   constructor(keyPath) {
  10.     this.keyPath = keyPath;
  11.  
  12.     if(this.keyPath && fs.existsSync(this.keyPath)) {
  13.       logger.debug('Loading private and public key for JWT sessions...');
  14.       const keyPair = new NodeRSA();
  15.       this.privateKey = fs.readFileSync(keyPath, 'utf-8');
  16.       keyPair.importKey(privateKey, 'private');
  17.       this.publicKey = keyPair.exportKey('public');
  18.       logger.success('Done');
  19.  
  20.       this.resetInvalidation();
  21.     }
  22.     else this.generateNewKeyPair();
  23.   }
  24.  
  25.   resetInvalidation() {
  26.       this.invalidationCounterByUserUuid = {};
  27.       this.invalidBefore = Math.floor(new Date().getTime()/1000);
  28.   }
  29.  
  30.   generateNewKeyPair() {
  31.     logger.debug('Generating private and public key for JWT sessions...');
  32.     const keyPair = new NodeRSA({ b: 2048 });
  33.     this.privateKey = keyPair.exportKey('private');
  34.     this.publicKey = keyPair.exportKey('public');
  35.     if(this.keyPath) fs.writeFileSync(this.keyPath, this.privateKey, 'utf-8');
  36.     logger.success('Done');
  37.  
  38.     this.resetInvalidation();
  39.   }
  40.  
  41.   sign(payload) {
  42.     payload.invalidationCounter = this.invalidationCounterByUserUuid[payload.userUuid] || 0;
  43.     return jwt.sign(payload, this.privateKey, { algorithm:'RS256' });
  44.   }
  45.  
  46.   verify(token) {
  47.     try {
  48.       const payload = jwt.verify(token, this.publicKey, { algorithm: ['RS256'] });
  49.       const notInvalidated = !this.invalidationCounterByUserUuid[payload.userUuid] || payload.invalidationCounter === this.invalidationCounterByUserUuid[payload.userUuid];
  50.       const hasValidIat = payload.iat >= this.invalidBefore;
  51.       return (notInvalidated && hasValidIat) ? payload : false;
  52.     }
  53.     catch(error) {
  54.       logger.warning(error);
  55.       return false;
  56.     }
  57.   }
  58.  
  59.   invalidateUserTokens(userUuid) {
  60.     this.invalidationCounterByUserUuid[userUuid] = ++this.invalidationCounterByUserUuid[userUuid] || 1;
  61.   }
  62. }
  63.  
  64. module.exports = rsaJwt;
RAW Paste Data