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 rsaJwt = (keyPath) => {
- let invalidationCounterByUserUuid;
- let invalidBefore;
- let privateKey;
- let publicKey;
- // INIT
- if(keyPath && fs.existsSync(keyPath)) {
- logger.debug('Loading private and public key for JWT sessions...');
- const keyPair = new NodeRSA();
- privateKey = fs.readFileSync(keyPath, 'utf-8');
- keyPair.importKey(privateKey, 'private');
- publicKey = keyPair.exportKey('public');
- logger.success('Done');
- resetInvalidation();
- }
- else generateNewKeyPair();
- // !INIT
- function resetInvalidation() {
- invalidationCounterByUserUuid = {};
- invalidBefore = Math.floor(new Date().getTime()/1000);
- }
- function generateNewKeyPair() {
- logger.debug('Generating private and public key for JWT sessions...');
- const keyPair = new NodeRSA({ b: 2048 });
- privateKey = keyPair.exportKey('private');
- publicKey = keyPair.exportKey('public');
- if(keyPath) fs.writeFileSync(keyPath, privateKey, 'utf-8');
- logger.success('Done');
- resetInvalidation();
- }
- function sign(payload) {
- payload.invalidationCounter = invalidationCounterByUserUuid[payload.userUuid] || 0;
- return jwt.sign(payload, privateKey, { algorithm:'RS256' });
- }
- function 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;
- }
- }
- function invalidateUserTokens (userUuid) {
- invalidationCounterByUserUuid[userUuid] = ++invalidationCounterByUserUuid[userUuid] || 1;
- }
- return { generateNewKeyPair, sign, verify, invalidateUserTokens };
- }
- module.exports = rsaJwt;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement