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