All files / src verifier.js

14.81% Statements 4/27
0% Branches 0/6
0% Functions 0/3
14.81% Lines 4/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 699x 9x 9x                                                                                                                           9x        
const fetch = require('node-fetch');
const hash = require('hash.js');
const ecc = require('eosjs-ecc');
 
// hash the parameter values to be sent to the verifier
function hashParams(params) {
  const hashedParams = {};
  Object.keys(params).map((key) => {
    hashedParams[key] = hash.sha256().update(params[key]).digest('hex');
  });
  return hashedParams;
}
 
// Call the Verifier to verify the client request and return an ore-access-token to access a particular right
async function getAccessTokenFromVerifier(verifierEndpoint, instrument, right, hashedParams) {
  let errorTitle;
  let errorMessage;
  let result;
  const signature = await this.sign(instrument.id);
 
  const options = {
    method: 'POST',
    body: JSON.stringify({
      requestParams: hashedParams,
      rightName: right.right_name,
      signature,
      voucherId: instrument.id
    }),
    headers: {
      'Content-Type': 'application/json'
    }
  };
 
  // Call the Verifier to approve the request
  try {
    result = await fetch(`${verifierEndpoint}/verify`, options);
 
    if (!result.ok) {
      const error = await result.json();
      throw new Error(error.message);
    }
  } catch (error) {
    errorTitle = 'Orejs Verifier Fetch Error';
    throw new Error(`${errorTitle}: ${error.message}`);
  }
 
  const { endpoint, oreAccessToken, method, additionalParameters, accessTokenTimeout } = await result.json();
 
 
  if (!oreAccessToken) {
    errorTitle = 'Orejs Access Token Verification Error';
    errorMessage = 'Verifier is unable to return an ORE access token. Make sure a valid instrument is passed to the verifier.';
    throw new Error(`${errorTitle}: ${errorMessage}`);
  }
 
  if (!endpoint) {
    errorTitle = 'Orejs Access Right Verification Error';
    errorMessage = 'Verifier is unable to find an endpoint for the right name passed in. Make sure to pass in the correct right name you want to access.';
    throw new Error(`${errorTitle}: ${errorMessage}`);
  }
 
  return { endpoint, oreAccessToken, method, additionalParameters, accessTokenTimeout };
}
 
module.exports = {
  getAccessTokenFromVerifier,
  hashParams
};