all files / cloudsim-grant/ token.js

96% Statements 24/25
75% Branches 6/8
100% Functions 4/4
96% Lines 24/25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                                                                                                   
'use strict'
 
//const pub = require('./.publickey.js').publicKey
const jwt = require('jsonwebtoken')
const dotenv = require('dotenv')
const NodeRSA = require('node-rsa')
 
 
let  publicKey = "not a key"
let  privateKey = "not a key"
let  authUrl = "not a url"
 
// this function sets the keys. It is called automatically with
// the values found in the .env file. Only the test needs to
// call it directly.
exports.initKeys = function(publicK, privateK, _authUrl) {
 
  Eif (publicK)
    publicKey = publicK.replace(/\\n/g, "\n");
  if (privateK)
    privateKey = privateK.replace(/\\n/g, "\n");
 
  authUrl = _authUrl
}
 
// generates keys that can be used with jsonwebtoken
exports.generateKeys = function() {
  var key = new NodeRSA({b: 512, e: 5});
 
  key.setOptions({
    encryptionScheme: {
      scheme: 'pkcs1',
      label: 'Optimization-Service'
    },
    signingScheme: {
      saltLength: 25
    }
  });
 
  return {
    "private" : key.exportKey('pkcs1-private-pem'),
    "public"  : key.exportKey('pkcs8-public-pem')
  };
}
 
 
// sign a token. This is done by the server
// the private key is necessary
// the private key should only be on the auth server
exports.signToken = function (data, cb) {
  const options = {
    algorithm: 'RS256',
    expiresIn: 60 * 60 * 24 * 180,
  }
  jwt.sign(data, privateKey, options, cb)
}
 
// verify a token... requires the public key of the server in the .env file
exports.verifyToken = function(token, cb) {
  jwt.verify(token, publicKey,  {algorithms: ['RS256']}, cb)
}
 
// read the environment variables. They contain the keys(s)
dotenv.config()
 
exports.initKeys(process.env.CLOUDSIM_AUTH_PUB_KEY,
                 process.env.CLOUDSIM_AUTH_PRIV_KEY,
                 process.env.CLOUDSIM_AUTH_URL)
 
Iif (!process.env.CLOUDSIM_AUTH_PUB_KEY || process.env.CLOUDSIM_AUTH_PUB_KEY === "") {
  console.warn('warning: CLOUDSIM_AUTH_PUB_KEY is empty!')
}