Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix linting errors
  • Loading branch information
Neha Patwardhan committed Oct 17, 2019
commit 4b26c8fbde9b8e7b546ed11e3292b56c40e86ddc
49 changes: 32 additions & 17 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,36 @@
"strict": ["error", "safe"],
"prefer-object-spread": "off",
"no-param-reassign": "off",
"comma-dangle": ["error", {
"arrays": "always-multiline",
"objects": "always-multiline",
"imports": "always-multiline",
"exports": "always-multiline",
"functions": "never"
}],
"no-underscore-dangle": ["error", {
"allow": [
"_checkExpiry",
"_urlencodedContentType",
"_jsonContentType",
"_contentType"
]
}],
"camelcase": ["error", { "properties": "never" }]
"comma-dangle": [
"error",
{
"arrays": "always-multiline",
"objects": "always-multiline",
"imports": "always-multiline",
"exports": "always-multiline",
"functions": "never"
}
],
"no-underscore-dangle": "off",
"no-unused-expressions": "off",
"func-names": "off",
"no-mixed-operators": "off",
"eqeqeq": "off",
"function-paren-newline": "off",
"consistent-return": "off",
"no-prototype-builtins": "off"
},
"globals": {
"sinon": true,
"describe": true,
"it": true,
"expect": true,
"test": true,
"require": true
},
"env": {
"es6": true,
"node": true,
"mocha": true
}
}
}
45 changes: 22 additions & 23 deletions src/OAuthClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
const atob = require('atob');
const oauthSignature = require('oauth-signature');
const objectAssign = require('object-assign');
const csrf = require('csrf');
const Csrf = require('csrf');
const queryString = require('query-string');
const popsicle = require('popsicle');
const os = require('os');
Expand All @@ -39,7 +39,7 @@ const jwt = require('jsonwebtoken');
const AuthResponse = require('./response/AuthResponse');
const version = require('../package.json');
const Token = require('./access-token/Token');

const getPem = require('rsa-pem-from-mod-exp');

/**
* @constructor
Expand All @@ -56,7 +56,7 @@ function OAuthClient(config) {
this.token = new Token(config.token);
this.logging = !!(Object.prototype.hasOwnProperty.call(config, 'logging') && config.logging === true);
this.logger = null;
this.state = new csrf(); // eslint-disable-line new-cap
this.state = new Csrf();

if (this.logging) {
const dir = './logs';
Expand Down Expand Up @@ -98,8 +98,8 @@ OAuthClient.scopes = {
OpenId: 'openid',
Intuit_name: 'intuit_name',
};
OAuthClient.user_agent = `Intuit-OAuthClient-JS_${version}_${os.type()}_${os.release()}_${os.platform()}`;

OAuthClient.user_agent = `Intuit-OAuthClient-JS_${version}_${os.type()}_${os.release()}_${os.platform()}`;

/**
* Redirect User to Authorization Page
Expand Down Expand Up @@ -218,18 +218,18 @@ OAuthClient.prototype.refresh = function refresh() {
* @param {Object} params.refresh_token (refresh_token)
* @returns {Promise<AuthResponse>}
*/
OAuthClient.prototype.refreshUsingToken = function refreshUsingToken(refresh_token) {
OAuthClient.prototype.refreshUsingToken = function (refreshToken) {
return (new Promise(((resolve) => {
/**
* Check if the tokens exist
*/

if (!refresh_token) throw new Error('The Refresh token is missing');
if (!refreshToken) throw new Error('The Refresh token is missing');

const body = {};

body.grant_type = 'refresh_token';
body.refresh_token = refresh_token;
body.refresh_token = refreshToken;

const request = {
url: OAuthClient.tokenEndpoint,
Expand Down Expand Up @@ -270,10 +270,10 @@ OAuthClient.prototype.revoke = function revoke(params) {

const body = {};

body.token = params.access_token || params.refresh_token ||
(this.getToken().isAccessTokenValid()
? this.getToken().access_token
: this.getToken().refresh_token);
body.token = params.access_token || params.refresh_token
|| (this.getToken().isAccessTokenValid() ?
this.getToken().access_token :
this.getToken().refresh_token);

const request = {
url: OAuthClient.revokeEndpoint,
Expand Down Expand Up @@ -442,6 +442,7 @@ OAuthClient.prototype.generateOauth1Sign = function generateOauth1Sign(params) {
if (key === 'minorversion') {
return header;
}

if (idx === array.length - 1) {
return `${header}${key}="${val}"`;
}
Expand All @@ -460,12 +461,12 @@ OAuthClient.prototype.validateIdToken = function validateIdToken(params = {}) {
return (new Promise(((resolve) => {
if (!this.getToken().id_token) throw new Error('The bearer token does not have id_token');

const id_token = this.getToken().id_token || params.id_token;
const idToken = this.getToken().id_token || params.id_token;

// Decode ID Token
const token_parts = id_token.split('.');
const id_token_header = JSON.parse(atob(token_parts[0]));
const id_token_payload = JSON.parse(atob(token_parts[1]));
const tokenParts = idToken.split('.');
const idTokenHeader = JSON.parse(atob(tokenParts[0]));
const idTokenPayload = JSON.parse(atob(tokenParts[1]));

// Step 1 : First check if the issuer is as mentioned in "issuer"
if (id_token_payload.iss !== 'https://oauth.platform.intuit.com/op/v1') return false;
Expand All @@ -474,7 +475,7 @@ OAuthClient.prototype.validateIdToken = function validateIdToken(params = {}) {
if (id_token_payload.aud !== this.clientId) return false;

// Step 3 : ensure the timestamp has not elapsed
if (id_token_payload.exp < Date.now() / 1000) return false;
if (idTokenPayload.exp < Date.now() / 1000) return false;

const request = {
url: OAuthClient.jwks_uri,
Expand All @@ -498,12 +499,12 @@ OAuthClient.prototype.validateIdToken = function validateIdToken(params = {}) {

/**
*
* @param id_token
* @param idToken
* @param kid
* @param request
* @returns {Promise<AuthResponse>}
*/
OAuthClient.prototype.getKeyFromJWKsURI = function getKeyFromJWKsURI(id_token, kid, request) {
OAuthClient.prototype.getKeyFromJWKsURI = function (idToken, kid, request) {
return (new Promise(((resolve) => {
resolve(this.loadResponse(request));
}))).then((response) => {
Expand All @@ -514,7 +515,7 @@ OAuthClient.prototype.getKeyFromJWKsURI = function getKeyFromJWKsURI(id_token, k
const key = responseBody.keys.find(el => (el.kid === kid));
const cert = this.getPublicKey(key.n, key.e);

return jwt.verify(id_token, cert);
return jwt.verify(idToken, cert);
}).catch((e) => {
e = this.createError(e);
this.log('error', 'The getKeyFromJWKsURI () threw an exception : ', JSON.stringify(e, null, 2));
Expand All @@ -527,9 +528,7 @@ OAuthClient.prototype.getKeyFromJWKsURI = function getKeyFromJWKsURI(id_token, k
* @param modulus
* @param exponent
*/
OAuthClient.prototype.getPublicKey = function getPublicKey(modulus, exponent) {
// eslint-disable-next-line global-require
const getPem = require('rsa-pem-from-mod-exp');
OAuthClient.prototype.getPublicKey = function (modulus, exponent) {
const pem = getPem(modulus, exponent);
return pem;
};
Expand Down Expand Up @@ -657,7 +656,7 @@ OAuthClient.prototype.setToken = function setToken(params) {
*/
OAuthClient.prototype.authHeader = function authHeader() {
const apiKey = `${this.clientId}:${this.clientSecret}`;
return (typeof btoa === 'function') ? btoa(apiKey) : Buffer.from(apiKey).toString('base64');
return (typeof btoa === 'function') ? btoa(apiKey) : new Buffer(apiKey).toString('base64');
};

OAuthClient.prototype.log = function log(level, message, messageData) {
Expand Down
1 change: 0 additions & 1 deletion test/AuthResponseTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,3 @@ describe('Tests for AuthResponse', () => {
expect(() => authResponse.processResponse(null)).to.not.throw();
});
});

15 changes: 7 additions & 8 deletions test/OAuthClientTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const expectedvalidateIdToken = require('./mocks/validateIdToken.json');
const expectedOpenIDToken = require('./mocks/openID-token.json');
// var expectedErrorResponse = require('./mocks/errorResponse.json');
const expectedMigrationResponse = require('./mocks/authResponse.json');
const refreshAccessToken = require('./mocks/refreshResponse.json');

const oauthClient = new OAuthClientTest({
clientId: 'clientID',
Expand Down Expand Up @@ -93,8 +94,8 @@ describe('Tests for OAuthClient', () => {
const parseRedirect = 'http://localhost:8000/callback?state=testState&code=Q011535008931rqveFweqmueq0GlOHhLPAFMp3NI2KJm5gbMMx';
return oauthClient.createToken(parseRedirect)
.then((authResponse) => {
expect(authResponse.getToken().access_token)
.to.be.equal(expectedAccessToken.access_token);
expect(authResponse.getToken().access_token).to.be
.equal(expectedAccessToken.access_token);
});
});

Expand Down Expand Up @@ -122,8 +123,6 @@ describe('Tests for OAuthClient', () => {
// Refresh bearer tokens
describe('Refresh Bearer Token', () => {
before(() => {
// eslint-disable-next-line global-require
const refreshAccessToken = require('./mocks/refreshResponse.json');
nock('https://oauth.platform.intuit.com').persist()
.post('/oauth2/v1/tokens/bearer')
.reply(200, refreshAccessToken, {
Expand All @@ -139,8 +138,8 @@ describe('Tests for OAuthClient', () => {

it('Refresh the existing tokens', () => oauthClient.refresh()
.then((authResponse) => {
expect(authResponse.getToken().refresh_token)
.to.be.equal(expectedAccessToken.refresh_token);
expect(authResponse.getToken().refresh_token).to.be
.equal(expectedAccessToken.refresh_token);
}));

it('Refresh : refresh token is missing', () => {
Expand Down Expand Up @@ -279,7 +278,7 @@ describe('Tests for OAuthClient', () => {
it('Make API Call in Sandbox Environment', () => {
oauthClient.getToken().realmId = '12345';
// eslint-disable-next-line no-useless-concat
return oauthClient.makeApiCall({ url: 'https://sandbox-quickbooks.api.intuit.com/v3/company/' + '12345' + '/companyinfo/' + '12345' })
return oauthClient.makeApiCall({ url: 'https://sandbox-quickbooks.api.intuit.com/v3/company/12345/companyinfo/12345' })
.then((authResponse) => {
expect(JSON.stringify(authResponse.getJson()))
.to.be.equal(JSON.stringify(expectedMakeAPICall));
Expand Down Expand Up @@ -314,7 +313,7 @@ describe('Tests for OAuthClient', () => {
oauthClient.environment = 'production';
oauthClient.getToken().realmId = '12345';
// eslint-disable-next-line no-useless-concat
return oauthClient.makeApiCall({ url: 'https://quickbooks.api.intuit.com/v3/company/' + '12345' + '/companyinfo/' + '12345' })
return oauthClient.makeApiCall({ url: 'https://quickbooks.api.intuit.com/v3/company/12345/companyinfo/12345' })
.then((authResponse) => {
expect(JSON.stringify(authResponse.getJson()))
.to.be.equal(JSON.stringify(expectedMakeAPICall));
Expand Down
19 changes: 9 additions & 10 deletions test/TokenTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const OAuthClientTest = require('../src/OAuthClient');
const expectedAccessToken = require('./mocks/bearer-token.json');


const oauthClient = new OAuthClientTest({
let oauthClient = new OAuthClientTest({
clientId: 'clientID',
clientSecret: 'clientSecret',
environment: 'sandbox',
Expand All @@ -30,14 +30,14 @@ describe('Tests for Token', () => {
});

it('Set Token using Constructor', () => {
const oauthClientWithToken = new OAuthClientTest({
oauthClient = new OAuthClientTest({
clientId: 'clientID',
clientSecret: 'clientSecret',
environment: 'sandbox',
redirectUri: 'http://localhost:8000/callback',
token: expectedAccessToken,
});
const token = oauthClientWithToken.getToken();
const token = oauthClient.getToken();

expect(token.access_token).to.equal(expectedAccessToken.access_token);
expect(token.refresh_token).to.equal(expectedAccessToken.refresh_token);
Expand All @@ -61,24 +61,24 @@ describe('Tests for Token', () => {

it('Get Access Token using Helper Method', () => {
oauthClient.token.setToken(expectedAccessToken);
const access_token = oauthClient.getToken().accessToken();
const accessToken = oauthClient.getToken().accessToken();

expect(access_token).to.deep.equal(expectedAccessToken.access_token);
expect(accessToken).to.deep.equal(expectedAccessToken.access_token);
});


it('Get Refresh Token using Helper Method', () => {
oauthClient.token.setToken(expectedAccessToken);
const refresh_token = oauthClient.getToken().refreshToken();
const refreshToken = oauthClient.getToken().refreshToken();

expect(refresh_token).to.deep.equal(expectedAccessToken.refresh_token);
expect(refreshToken).to.deep.equal(expectedAccessToken.refresh_token);
});

it('Get TokenType using Helper Method', () => {
oauthClient.token.setToken(expectedAccessToken);
const token_type = oauthClient.getToken().tokenType();
const tokenType = oauthClient.getToken().tokenType();

expect(token_type).to.deep.equal(expectedAccessToken.token_type);
expect(tokenType).to.deep.equal(expectedAccessToken.token_type);
});

it('Get Token using Helper Method', () => {
Expand All @@ -100,4 +100,3 @@ describe('Tests for Token', () => {
expect(token.x_refresh_token_expires_in).to.equal(0);
});
});