From dffe2cb30ebd1b4f42aff8a60cdeb2cd87612f3b Mon Sep 17 00:00:00 2001 From: abisalehalliprasan Date: Fri, 19 Jul 2019 16:33:07 -0700 Subject: [PATCH] Clear Token Object on Revoke Functionality : Fixed --- README.md | 6 +- package.json | 2 +- src/OAuthClient.js | 620 +++++++++++++++++----------------- src/access-token/Token.js | 88 +++-- test/OAuthClientTest.js | 694 +++++++++++++++++++------------------- 5 files changed, 711 insertions(+), 699 deletions(-) diff --git a/README.md b/README.md index df7bca2c..c48594b5 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,6 @@ The OAuth2 Nodejs Client library is meant to work with Intuit's [OAuth2.0](https - [Is Access Token valid](#is-accesstoken-valid) - [Refresh Access_Token](#refresh-access_token) - [Refresh Access_Token by passing the refresh_token explicitly](#refresh-access_token_explicitly) - - [Auto Refresh](#auto-refresh) - [Revoke Access Token](#revoke-access_token) - [Getter / Setter for Token](#getter-/-setter-for-token ) - [Auth Response](#auth-response) @@ -493,7 +492,4 @@ You can refer to our [FAQ](https://github.com/intuit/oauth-jsclient/wiki/FAQ) if Intuit `oauth-jsclient` is licensed under the [Apache License, Version 2.0](https://github.com/intuit/oauth-jsclient/blob/master/LICENSE) -[ss1]: https://help.developer.intuit.com/s/SDKFeedback?cid=1120 - - - +[ss1]: https://help.developer.intuit.com/s/SDKFeedback?cid=1120 \ No newline at end of file diff --git a/package.json b/package.json index 694c3504..a120418e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "intuit-oauth", - "version": "1.3.0", + "version": "1.4.0", "description": "Intuit Node.js client for OAuth2.0 and OpenID", "main": "./src/OAuthClient.js", "scripts": { diff --git a/src/OAuthClient.js b/src/OAuthClient.js index 96027ced..16c61268 100644 --- a/src/OAuthClient.js +++ b/src/OAuthClient.js @@ -46,31 +46,31 @@ var jwt = require('jsonwebtoken') */ function OAuthClient(config) { - this.environment = config.environment; - this.clientId = config.clientId; - this.clientSecret = config.clientSecret; - this.redirectUri = config.redirectUri; - this.token = new Token(config.token); - this.logging = config.hasOwnProperty('logging') && config.logging == true ? true : false; - this.logger = null; - - if(this.logging) { - - var dir = './logs'; - if (!fs.existsSync(dir)){ - fs.mkdirSync(dir); - } - this.logger = winston.createLogger({ - level: 'info', - format: winston.format.combine( - winston.format.timestamp(), - winston.format.printf(info => { - return `${info.timestamp} ${info.level}: ${info.message}`; - }) - ), - transports: [new winston.transports.File({filename: path.join(dir , 'oAuthClient-log.log')})] - }); + this.environment = config.environment; + this.clientId = config.clientId; + this.clientSecret = config.clientSecret; + this.redirectUri = config.redirectUri; + this.token = new Token(config.token); + this.logging = config.hasOwnProperty('logging') && config.logging == true ? true : false; + this.logger = null; + + if(this.logging) { + + var dir = './logs'; + if (!fs.existsSync(dir)){ + fs.mkdirSync(dir); } + this.logger = winston.createLogger({ + level: 'info', + format: winston.format.combine( + winston.format.timestamp(), + winston.format.printf(info => { + return `${info.timestamp} ${info.level}: ${info.message}`; + }) + ), + transports: [new winston.transports.File({filename: path.join(dir , 'oAuthClient-log.log')})] + }); + } } @@ -107,21 +107,21 @@ OAuthClient.user_agent = 'Intuit-OAuthClient-JS'+ '_' + package.version + '_' + */ OAuthClient.prototype.authorizeUri = function(params) { - params = params || {}; + params = params || {}; - // check if the scopes is provided - if(!params.scope) throw new Error('Provide the scopes'); + // check if the scopes is provided + if(!params.scope) throw new Error('Provide the scopes'); - var authorizeUri = OAuthClient.authorizeEndpoint + '?' + queryString.stringify({ - 'response_type': 'code', - 'redirect_uri': this.redirectUri , - 'client_id': this.clientId, - 'scope': (Array.isArray(params.scope)) ? params.scope.join(' ') : params.scope, - 'state': params.state || csrf.create(csrf.secretSync()) - }); + var authorizeUri = OAuthClient.authorizeEndpoint + '?' + queryString.stringify({ + 'response_type': 'code', + 'redirect_uri': this.redirectUri , + 'client_id': this.clientId, + 'scope': (Array.isArray(params.scope)) ? params.scope.join(' ') : params.scope, + 'state': params.state || csrf.create(csrf.secretSync()) + }); - this.log('info','The Authorize Uri is :',authorizeUri); - return authorizeUri; + this.log('info','The Authorize Uri is :',authorizeUri); + return authorizeUri; }; @@ -133,48 +133,48 @@ OAuthClient.prototype.authorizeUri = function(params) { */ OAuthClient.prototype.createToken = function(uri) { - return (new Promise(function(resolve) { + return (new Promise(function(resolve) { - if(!uri) throw new Error('Provide the Uri'); - var params = queryString.parse(uri.split('?').reverse()[0]); - this.getToken().realmId = (params['realmId'] ? params['realmId'] : ''); + if(!uri) throw new Error('Provide the Uri'); + var params = queryString.parse(uri.split('?').reverse()[0]); + this.getToken().realmId = (params['realmId'] ? params['realmId'] : ''); - var body = {}; - if (params.code) { + var body = {}; + if (params.code) { - body.grant_type = 'authorization_code'; - body.code = params.code; - body.redirect_uri = params.redirectUri || this.redirectUri; - } + body.grant_type = 'authorization_code'; + body.code = params.code; + body.redirect_uri = params.redirectUri || this.redirectUri; + } - var request = { - url: OAuthClient.tokenEndpoint, - body: body, - method: 'POST', - headers: { - 'Authorization': 'Basic ' + this.authHeader(), - 'Content-Type': AuthResponse._urlencodedContentType, - 'Accept': AuthResponse._jsonContentType, - 'User-Agent': OAuthClient.user_agent - } - }; + var request = { + url: OAuthClient.tokenEndpoint, + body: body, + method: 'POST', + headers: { + 'Authorization': 'Basic ' + this.authHeader(), + 'Content-Type': AuthResponse._urlencodedContentType, + 'Accept': AuthResponse._jsonContentType, + 'User-Agent': OAuthClient.user_agent + } + }; - resolve(this.getTokenRequest(request)); + resolve(this.getTokenRequest(request)); - }.bind(this))).then(function(res) { + }.bind(this))).then(function(res) { - var authResponse = res.json ? res : null; - var json = authResponse && authResponse.getJson() || res; - this.token.setToken(json); - this.log('info','Create Token response is : ',JSON.stringify(authResponse, null, 2)); - return authResponse; + var authResponse = res.json ? res : null; + var json = authResponse && authResponse.getJson() || res; + this.token.setToken(json); + this.log('info','Create Token response is : ',JSON.stringify(authResponse, null, 2)); + return authResponse; - }.bind(this)).catch(function(e) { + }.bind(this)).catch(function(e) { - this.log('error','Create Token () threw an exception : ',JSON.stringify(e, null, 2)); - throw e; + this.log('error','Create Token () threw an exception : ',JSON.stringify(e, null, 2)); + throw e; - }.bind(this)); + }.bind(this)); }; @@ -186,53 +186,53 @@ OAuthClient.prototype.createToken = function(uri) { */ OAuthClient.prototype.refresh = function() { - return (new Promise(function(resolve) { + return (new Promise(function(resolve) { - /** - * Check if the tokens exist and are valid - */ - this.validateToken(); + /** + * Check if the tokens exist and are valid + */ + this.validateToken(); - var body = {}; + var body = {}; - body.grant_type = 'refresh_token'; - body.refresh_token = this.getToken().refresh_token; + body.grant_type = 'refresh_token'; + body.refresh_token = this.getToken().refresh_token; - var request = { - url: OAuthClient.tokenEndpoint, - body: body, - method: 'POST', - headers: { - 'Authorization': 'Basic ' + this.authHeader(), - 'Content-Type': AuthResponse._urlencodedContentType, - 'Accept': AuthResponse._jsonContentType, - 'User-Agent': OAuthClient.user_agent - } - }; + var request = { + url: OAuthClient.tokenEndpoint, + body: body, + method: 'POST', + headers: { + 'Authorization': 'Basic ' + this.authHeader(), + 'Content-Type': AuthResponse._urlencodedContentType, + 'Accept': AuthResponse._jsonContentType, + 'User-Agent': OAuthClient.user_agent + } + }; - resolve(this.getTokenRequest(request)); + resolve(this.getTokenRequest(request)); - }.bind(this))).then(function(res) { + }.bind(this))).then(function(res) { - var authResponse = res.json ? res : null; - var json = authResponse && authResponse.getJson() || res; - this.token.setToken(json); - this.log('info','Refresh Token () response is : ',JSON.stringify(authResponse, null, 2)); - return authResponse; + var authResponse = res.json ? res : null; + var json = authResponse && authResponse.getJson() || res; + this.token.setToken(json); + this.log('info','Refresh Token () response is : ',JSON.stringify(authResponse, null, 2)); + return authResponse; - }.bind(this)).catch(function(e) { + }.bind(this)).catch(function(e) { - this.log('error','Refresh Token () threw an exception : ',JSON.stringify(e, null, 2)); - throw e; + this.log('error','Refresh Token () threw an exception : ',JSON.stringify(e, null, 2)); + throw e; - }.bind(this)); + }.bind(this)); }; /** * Refresh Tokens by passing refresh_token parameter explicitly { Refresh access_token by passing refresh_token } - * @param {Object} params.refresh_token (optional) + * @param {Object} params.refresh_token (refresh_token) * @returns {Promise} */ OAuthClient.prototype.refreshUsingToken = function(refresh_token) { @@ -291,40 +291,40 @@ OAuthClient.prototype.refreshUsingToken = function(refresh_token) { */ OAuthClient.prototype.revoke = function(params) { - return (new Promise(function(resolve) { - - params = params || {}; + return (new Promise(function(resolve) { - var body = {}; + params = params || {}; - body.token = params.access_token || params.refresh_token || (this.getToken().isAccessTokenValid() ? this.getToken().access_token : this.getToken().refresh_token); + var body = {}; - var request = { - url: OAuthClient.revokeEndpoint, - body: body, - method: 'POST', - headers: { - 'Authorization': 'Basic ' + this.authHeader(), - 'Accept': AuthResponse._jsonContentType, - 'Content-Type': AuthResponse._jsonContentType, - 'User-Agent': OAuthClient.user_agent - } - }; + body.token = params.access_token || params.refresh_token || (this.getToken().isAccessTokenValid() ? this.getToken().access_token : this.getToken().refresh_token); - resolve(this.getTokenRequest(request)); + var request = { + url: OAuthClient.revokeEndpoint, + body: body, + method: 'POST', + headers: { + 'Authorization': 'Basic ' + this.authHeader(), + 'Accept': AuthResponse._jsonContentType, + 'Content-Type': AuthResponse._jsonContentType, + 'User-Agent': OAuthClient.user_agent + } + }; + resolve(this.getTokenRequest(request)); - }.bind(this))).then(function(authResponse) { + }.bind(this))).then(function(authResponse) { - this.log('info','Revoke Token () response is : ',JSON.stringify(authResponse, null, 2)); - return authResponse; + this.token.clearToken(); + this.log('info','Revoke Token () response is : ',JSON.stringify(authResponse, null, 2)); + return authResponse; - }.bind(this)).catch(function(e) { + }.bind(this)).catch(function(e) { - this.log('error','Revoke Token () threw an exception : ',JSON.stringify(e, null, 2)); - throw e; + this.log('error','Revoke Token () threw an exception : ',JSON.stringify(e, null, 2)); + throw e; - }.bind(this)); + }.bind(this)); }; @@ -335,34 +335,34 @@ OAuthClient.prototype.revoke = function(params) { */ OAuthClient.prototype.getUserInfo = function(params) { - return (new Promise(function(resolve) { + return (new Promise(function(resolve) { - params = params || {}; + params = params || {}; - var request = { - url: this.environment == 'sandbox' ? OAuthClient.userinfo_endpoint_sandbox : OAuthClient.userinfo_endpoint_production, - method: 'GET', - headers: { - 'Authorization': 'Bearer ' + this.token.access_token, - 'Accept': AuthResponse._jsonContentType, - 'User-Agent': OAuthClient.user_agent - } - }; + var request = { + url: this.environment == 'sandbox' ? OAuthClient.userinfo_endpoint_sandbox : OAuthClient.userinfo_endpoint_production, + method: 'GET', + headers: { + 'Authorization': 'Bearer ' + this.token.access_token, + 'Accept': AuthResponse._jsonContentType, + 'User-Agent': OAuthClient.user_agent + } + }; - resolve(this.getTokenRequest(request)); + resolve(this.getTokenRequest(request)); - }.bind(this))).then(function(res) { + }.bind(this))).then(function(res) { - var authResponse = res.json ? res : null; - this.log('info','The Get User Info () response is : ',JSON.stringify(authResponse, null, 2)); - return authResponse; + var authResponse = res.json ? res : null; + this.log('info','The Get User Info () response is : ',JSON.stringify(authResponse, null, 2)); + return authResponse; - }.bind(this)).catch(function(e) { + }.bind(this)).catch(function(e) { - this.log('error','Get User Info () threw an exception : ',JSON.stringify(e, null, 2)); - throw e; + this.log('error','Get User Info () threw an exception : ',JSON.stringify(e, null, 2)); + throw e; - }.bind(this)); + }.bind(this)); }; @@ -373,33 +373,33 @@ OAuthClient.prototype.getUserInfo = function(params) { */ OAuthClient.prototype.makeApiCall = function(params) { - return (new Promise(function(resolve) { + return (new Promise(function(resolve) { - params = params || {}; + params = params || {}; - var request = { - url: params.url, - method: 'GET', - headers: { - 'Authorization': 'Bearer ' + this.getToken().access_token, - 'Accept': AuthResponse._jsonContentType, - 'User-Agent': OAuthClient.user_agent - } - }; + var request = { + url: params.url, + method: 'GET', + headers: { + 'Authorization': 'Bearer ' + this.getToken().access_token, + 'Accept': AuthResponse._jsonContentType, + 'User-Agent': OAuthClient.user_agent + } + }; - resolve(this.getTokenRequest(request)); + resolve(this.getTokenRequest(request)); - }.bind(this))).then(function(authResponse) { + }.bind(this))).then(function(authResponse) { - this.log('info','The makeAPICall () response is : ',JSON.stringify(authResponse, null, 2)); - return authResponse; + this.log('info','The makeAPICall () response is : ',JSON.stringify(authResponse, null, 2)); + return authResponse; - }.bind(this)).catch(function(e) { + }.bind(this)).catch(function(e) { - this.log('error','Get makeAPICall () threw an exception : ',JSON.stringify(e, null, 2)); - throw e; + this.log('error','Get makeAPICall () threw an exception : ',JSON.stringify(e, null, 2)); + throw e; - }.bind(this)); + }.bind(this)); }; @@ -410,48 +410,48 @@ OAuthClient.prototype.makeApiCall = function(params) { */ OAuthClient.prototype.migrate = function(params) { - return (new Promise(function(resolve) { + return (new Promise(function(resolve) { - params = params || {}; + params = params || {}; - var uri = this.environment.toLowerCase() == 'sandbox' ? OAuthClient.migrate_sandbox : OAuthClient.migrate_production; + var uri = this.environment.toLowerCase() == 'sandbox' ? OAuthClient.migrate_sandbox : OAuthClient.migrate_production; - var authHeader = this.generateOauth1Sign(objectAssign({}, {method: 'POST', uri: uri}, params)); + var authHeader = this.generateOauth1Sign(objectAssign({}, {method: 'POST', uri: uri}, params)); - var body = { - 'scope':(Array.isArray(params.scope)) ? params.scope.join(' ') : params.scope, - 'redirect_uri':this.redirectUri, - 'client_id': this.clientId, - 'client_secret': this.clientSecret - }; + var body = { + 'scope':(Array.isArray(params.scope)) ? params.scope.join(' ') : params.scope, + 'redirect_uri':this.redirectUri, + 'client_id': this.clientId, + 'client_secret': this.clientSecret + }; - var request = { - url: uri, - method: 'POST', - body: body, - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'OAuth ' + authHeader, - 'Accept': AuthResponse._jsonContentType, - 'User-Agent': OAuthClient.user_agent - } - }; + var request = { + url: uri, + method: 'POST', + body: body, + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'OAuth ' + authHeader, + 'Accept': AuthResponse._jsonContentType, + 'User-Agent': OAuthClient.user_agent + } + }; - resolve(this.getTokenRequest(request)); + resolve(this.getTokenRequest(request)); - }.bind(this))).then(function(res) { + }.bind(this))).then(function(res) { - var authResponse = res.json ? res : null; - var json = authResponse && authResponse.getJson() || res; - this.token.setToken(json); - this.log('info','The migrate () response is : ',JSON.stringify(authResponse, null, 2)); - return authResponse; - }.bind(this)).catch(function(e) { + var authResponse = res.json ? res : null; + var json = authResponse && authResponse.getJson() || res; + this.token.setToken(json); + this.log('info','The migrate () response is : ',JSON.stringify(authResponse, null, 2)); + return authResponse; + }.bind(this)).catch(function(e) { - this.log('error','The migrate () threw an exception : ',JSON.stringify(e, null, 2)); - throw e; + this.log('error','The migrate () threw an exception : ',JSON.stringify(e, null, 2)); + throw e; - }.bind(this)); + }.bind(this)); }; @@ -464,38 +464,38 @@ OAuthClient.prototype.migrate = function(params) { OAuthClient.prototype.generateOauth1Sign = function(params) { - var timestamp = Math.round(new Date().getTime()/1000); + var timestamp = Math.round(new Date().getTime()/1000); - var parameters = { - oauth_consumer_key : params.oauth_consumer_key, - oauth_token : params.access_token, - oauth_signature_method : 'HMAC-SHA1', - oauth_timestamp : timestamp, - oauth_nonce : 'nonce', - oauth_version : '1.0' - }; + var parameters = { + oauth_consumer_key : params.oauth_consumer_key, + oauth_token : params.access_token, + oauth_signature_method : 'HMAC-SHA1', + oauth_timestamp : timestamp, + oauth_nonce : 'nonce', + oauth_version : '1.0' + }; - var encodedSignature = oauthSignature.generate (params.method, params.uri, parameters, params.oauth_consumer_secret, params.access_secret); + var encodedSignature = oauthSignature.generate (params.method, params.uri, parameters, params.oauth_consumer_secret, params.access_secret); - parameters ['oauth_signature'] = encodedSignature; - var keys = Object.keys(parameters); - var authHeader = ''; + parameters ['oauth_signature'] = encodedSignature; + var keys = Object.keys(parameters); + var authHeader = ''; - for (key in parameters) { + for (key in parameters) { - // Add this for Accounting API minorversion url query parameter - if (key === 'minorversion') { - continue; - } - if (key === keys[keys.length-1]) { - authHeader += key + '=' + '"'+parameters[key]+'"'; - } - else { - authHeader += key + '=' + '"'+parameters[key]+'",'; - } + // Add this for Accounting API minorversion url query parameter + if (key === 'minorversion') { + continue; + } + if (key === keys[keys.length-1]) { + authHeader += key + '=' + '"'+parameters[key]+'"'; } + else { + authHeader += key + '=' + '"'+parameters[key]+'",'; + } + } - return authHeader; + return authHeader; }; @@ -506,53 +506,53 @@ OAuthClient.prototype.generateOauth1Sign = function(params) { */ OAuthClient.prototype.validateIdToken = function(params) { - return (new Promise(function(resolve) { + return (new Promise(function(resolve) { - if(!this.getToken().id_token) throw new Error('The bearer token does not have id_token'); + if(!this.getToken().id_token) throw new Error('The bearer token does not have id_token'); - var id_token = this.getToken().id_token || params.id_token; + var id_token = this.getToken().id_token || params.id_token; - params = params || {}; + params = params || {}; - // Decode ID Token - var token_parts = id_token.split('.') - var id_token_header = JSON.parse(atob(token_parts[0])); - var id_token_payload = JSON.parse(atob(token_parts[1])); + // Decode ID Token + var token_parts = id_token.split('.') + var id_token_header = JSON.parse(atob(token_parts[0])); + var id_token_payload = JSON.parse(atob(token_parts[1])); - var id_token_signature = atob(token_parts[2]); - // - // 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; + var id_token_signature = atob(token_parts[2]); + // + // 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; - // Step 2 : check if the aud field in idToken is same as application's clientId - if(id_token_payload.aud != this.clientId) return false; + // Step 2 : check if the aud field in idToken is same as application's clientId + 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; + // Step 3 : ensure the timestamp has not elapsed + if(id_token_payload.exp < Date.now() / 1000) return false; - var request = { - url: OAuthClient.jwks_uri, - method: 'GET', - headers: { - 'Accept': AuthResponse._jsonContentType, - 'User-Agent': OAuthClient.user_agent - } - }; + var request = { + url: OAuthClient.jwks_uri, + method: 'GET', + headers: { + 'Accept': AuthResponse._jsonContentType, + 'User-Agent': OAuthClient.user_agent + } + }; - resolve(this.getKeyFromJWKsURI(id_token, id_token_header.kid, request)); + resolve(this.getKeyFromJWKsURI(id_token, id_token_header.kid, request)); - }.bind(this))).then(function(res) { + }.bind(this))).then(function(res) { - this.log('info','The validateIdToken () response is : ',JSON.stringify(res, null, 2)); - if(res) return true; + this.log('info','The validateIdToken () response is : ',JSON.stringify(res, null, 2)); + if(res) return true; - }.bind(this)).catch(function(e) { + }.bind(this)).catch(function(e) { - this.log('error','The validateIdToken () threw an exception : ',JSON.stringify(e, null, 2)); - throw e; + this.log('error','The validateIdToken () threw an exception : ',JSON.stringify(e, null, 2)); + throw e; - }.bind(this)); + }.bind(this)); } /** @@ -564,28 +564,28 @@ OAuthClient.prototype.validateIdToken = function(params) { */ OAuthClient.prototype.getKeyFromJWKsURI = function(id_token, kid, request) { - return (new Promise(function(resolve) { + return (new Promise(function(resolve) { - resolve(this.loadResponse(request)); + resolve(this.loadResponse(request)); - }.bind(this))).then(function(response) { + }.bind(this))).then(function(response) { - if(response.status != "200") throw new Error('Could not reach JWK endpoint'); + if(response.status != "200") throw new Error('Could not reach JWK endpoint'); - // Find the key by KID - var responseBody = JSON.parse(response.body); - var key = responseBody.keys.find(el => (el.kid == kid)) - var cert = this.getPublicKey(key.n, key.e) + // Find the key by KID + var responseBody = JSON.parse(response.body); + var key = responseBody.keys.find(el => (el.kid == kid)) + var cert = this.getPublicKey(key.n, key.e) - return jwt.verify(id_token, cert); + return jwt.verify(id_token, cert); - }.bind(this)).catch(function(e) { + }.bind(this)).catch(function(e) { - e = this.createError(e); - this.log('error','The getKeyFromJWKsURI () threw an exception : ',JSON.stringify(e, null, 2)); - throw e; + e = this.createError(e); + this.log('error','The getKeyFromJWKsURI () threw an exception : ',JSON.stringify(e, null, 2)); + throw e; - }.bind(this)); + }.bind(this)); } @@ -595,9 +595,9 @@ OAuthClient.prototype.getKeyFromJWKsURI = function(id_token, kid, request) { * @param exponent */ OAuthClient.prototype.getPublicKey = function(modulus, exponent) { - var getPem = require('rsa-pem-from-mod-exp'); - var pem = getPem(modulus, exponent); - return pem + var getPem = require('rsa-pem-from-mod-exp'); + var pem = getPem(modulus, exponent); + return pem }; /** @@ -607,26 +607,26 @@ OAuthClient.prototype.getPublicKey = function(modulus, exponent) { */ OAuthClient.prototype.getTokenRequest = function(request) { - var authResponse = new AuthResponse({token:this.token}); + var authResponse = new AuthResponse({token:this.token}); - return (new Promise(function(resolve) { + return (new Promise(function(resolve) { - resolve(this.loadResponse(request)); + resolve(this.loadResponse(request)); - }.bind(this))).then(function(response) { + }.bind(this))).then(function(response) { - authResponse.processResponse(response); + authResponse.processResponse(response); - if (!authResponse.valid()) throw new Error('Response has an Error'); + if (!authResponse.valid()) throw new Error('Response has an Error'); - return authResponse; + return authResponse; - }.bind(this)).catch(function(e) { + }.bind(this)).catch(function(e) { - if (!e.authResponse) e = this.createError(e, authResponse); - throw e; + if (!e.authResponse) e = this.createError(e, authResponse); + throw e; - }.bind(this)); + }.bind(this)); }; @@ -635,8 +635,8 @@ OAuthClient.prototype.getTokenRequest = function(request) { */ OAuthClient.prototype.validateToken = function() { - if(!this.token.refreshToken()) throw new Error('The Refresh token is missing'); - if(!this.token.isRefreshTokenValid()) throw new Error('The Refresh token is invalid, please Authorize again.'); + if(!this.token.refreshToken()) throw new Error('The Refresh token is missing'); + if(!this.token.isRefreshTokenValid()) throw new Error('The Refresh token is invalid, please Authorize again.'); }; @@ -647,9 +647,9 @@ OAuthClient.prototype.validateToken = function() { */ OAuthClient.prototype.loadResponse = function (request) { - return popsicle.get(request).then(function (response) { - return response; - }); + return popsicle.get(request).then(function (response) { + return response; + }); }; /** @@ -659,9 +659,9 @@ OAuthClient.prototype.loadResponse = function (request) { */ OAuthClient.prototype.loadResponseFromJWKsURI = function (request) { - return popsicle.get(request).then(function (response) { - return response; - }); + return popsicle.get(request).then(function (response) { + return response; + }); }; /** @@ -672,24 +672,24 @@ OAuthClient.prototype.loadResponseFromJWKsURI = function (request) { */ OAuthClient.prototype.createError = function(e, authResponse) { - if(!authResponse || authResponse.body == ""){ + if(!authResponse || authResponse.body == ""){ - e.error = e.originalMessage || ''; - e.authResponse = authResponse || '' - e.intuit_tid = authResponse.headers()['intuit_tid'] || ''; - e.originalMessage = authResponse.response.statusText || ''; - e.error = authResponse.response.statusText || ''; - e.error_description = authResponse.response.statusText || ''; - return e; - } + e.error = e.originalMessage || ''; + e.authResponse = authResponse || '' + e.intuit_tid = authResponse.headers()['intuit_tid'] || ''; + e.originalMessage = authResponse.response.statusText || ''; + e.error = authResponse.response.statusText || ''; + e.error_description = authResponse.response.statusText || ''; + return e; + } - e.authResponse = authResponse ? authResponse : null; - e.originalMessage = e.message; - e.error = ('error' in authResponse.getJson() ? authResponse.getJson().error : ''); - e.error_description = ('error_description' in authResponse.getJson() ? authResponse.getJson().error_description : ''); - e.intuit_tid = authResponse.headers()['intuit_tid']; + e.authResponse = authResponse ? authResponse : null; + e.originalMessage = e.message; + e.error = ('error' in authResponse.getJson() ? authResponse.getJson().error : ''); + e.error_description = ('error_description' in authResponse.getJson() ? authResponse.getJson().error_description : ''); + e.intuit_tid = authResponse.headers()['intuit_tid']; - return e; + return e; }; @@ -699,7 +699,7 @@ OAuthClient.prototype.createError = function(e, authResponse) { * @private */ OAuthClient.prototype.isAccessTokenValid = function() { - return this.token.isAccessTokenValid(); + return this.token.isAccessTokenValid(); }; /** @@ -707,7 +707,7 @@ OAuthClient.prototype.isAccessTokenValid = function() { * @returns {Token} */ OAuthClient.prototype.getToken = function() { - return this.token; + return this.token; }; @@ -728,14 +728,14 @@ OAuthClient.prototype.setToken = function(params) { * @returns {string} authHeader */ OAuthClient.prototype.authHeader = function() { - var apiKey = this.clientId + ':' + this.clientSecret; - return (typeof btoa == 'function') ? btoa(apiKey) : new Buffer(apiKey).toString('base64'); + var apiKey = this.clientId + ':' + this.clientSecret; + return (typeof btoa == 'function') ? btoa(apiKey) : new Buffer(apiKey).toString('base64'); }; OAuthClient.prototype.log = function(level,message,messageData) { - if (this.logging) { - this.logger.log(level,message + messageData); - } + if (this.logging) { + this.logger.log(level,message + messageData); + } }; -module.exports = OAuthClient; +module.exports = OAuthClient; \ No newline at end of file diff --git a/src/access-token/Token.js b/src/access-token/Token.js index 736c9b4f..a6554040 100644 --- a/src/access-token/Token.js +++ b/src/access-token/Token.js @@ -30,17 +30,17 @@ */ function Token(params) { - params = params || {}; - - this.realmId = params.realmId || ''; - this.token_type = params.token_type || ''; - this.access_token = params.access_token || ''; - this.refresh_token = params.refresh_token || ''; - this.expires_in = params.expires_in || 0; - this.x_refresh_token_expires_in = params.x_refresh_token_expires_in || 0; - this.id_token = params.id_token || ''; - this.latency = params.latency || 60 * 1000; - this.createdAt = params.createdAt || Date.now(); + params = params || {}; + + this.realmId = params.realmId || ''; + this.token_type = params.token_type || ''; + this.access_token = params.access_token || ''; + this.refresh_token = params.refresh_token || ''; + this.expires_in = params.expires_in || 0; + this.x_refresh_token_expires_in = params.x_refresh_token_expires_in || 0; + this.id_token = params.id_token || ''; + this.latency = params.latency || 60 * 1000; + this.createdAt = params.createdAt || Date.now(); } /** @@ -48,7 +48,7 @@ function Token(params) { * @returns {string} access_token */ Token.prototype.accessToken = function() { - return this.getToken().access_token; + return this.getToken().access_token; }; /** @@ -56,7 +56,7 @@ Token.prototype.accessToken = function() { * @returns {string} refresh_token */ Token.prototype.refreshToken = function() { - return this.getToken().refresh_token; + return this.getToken().refresh_token; }; /** @@ -64,7 +64,7 @@ Token.prototype.refreshToken = function() { * @returns {string} token_type */ Token.prototype.tokenType = function() { - return this.getToken().token_type; + return this.getToken().token_type; }; @@ -74,16 +74,16 @@ Token.prototype.tokenType = function() { */ Token.prototype.getToken = function() { - return { - token_type: this.token_type, - access_token: this.access_token, - expires_in: this.expires_in, - refresh_token: this.refresh_token, - x_refresh_token_expires_in: this.x_refresh_token_expires_in, - realmId: this.realmId, - id_token: this.id_token, - createdAt: this.createdAt - }; + return { + token_type: this.token_type, + access_token: this.access_token, + expires_in: this.expires_in, + refresh_token: this.refresh_token, + x_refresh_token_expires_in: this.x_refresh_token_expires_in, + realmId: this.realmId, + id_token: this.id_token, + createdAt: this.createdAt + }; }; @@ -94,25 +94,41 @@ Token.prototype.getToken = function() { */ Token.prototype.setToken = function(tokenData) { - this.access_token = tokenData.access_token; - this.refresh_token = tokenData.refresh_token; - this.token_type = tokenData.token_type ; - this.expires_in = tokenData.expires_in; - this.x_refresh_token_expires_in = tokenData.x_refresh_token_expires_in; - this.id_token = tokenData.id_token || ''; - this.createdAt = tokenData.createdAt || Date.now(); - return this; + this.access_token = tokenData.access_token; + this.refresh_token = tokenData.refresh_token; + this.token_type = tokenData.token_type ; + this.expires_in = tokenData.expires_in; + this.x_refresh_token_expires_in = tokenData.x_refresh_token_expires_in; + this.id_token = tokenData.id_token || ''; + this.createdAt = tokenData.createdAt || Date.now(); + return this; }; +/** + * Helper Method to clear accessToken { clear Token Object } + * @param + * @returns {Token} + */ +Token.prototype.clearToken = function() { + this.access_token = ''; + this.refresh_token = ''; + this.token_type = ''; + this.expires_in = 0; + this.x_refresh_token_expires_in = 0; + this.id_token = ''; + this.createdAt = 0; + return this; +} + /** * Helper Method to check token expiry { set Token Object } * @param seconds * @returns {boolean} */ Token.prototype._checkExpiry = function(seconds) { - var expiry = this.createdAt + (seconds * 1000); - return (expiry - this.latency > Date.now()); + var expiry = this.createdAt + (seconds * 1000); + return (expiry - this.latency > Date.now()); } /** @@ -120,7 +136,7 @@ Token.prototype._checkExpiry = function(seconds) { * @returns {boolean} */ Token.prototype.isAccessTokenValid = function() { - return this._checkExpiry(this.expires_in); + return this._checkExpiry(this.expires_in); }; /** @@ -128,7 +144,7 @@ Token.prototype.isAccessTokenValid = function() { * @return {boolean} */ Token.prototype.isRefreshTokenValid = function() { - return this._checkExpiry(this.x_refresh_token_expires_in); + return this._checkExpiry(this.x_refresh_token_expires_in); }; module.exports = Token; \ No newline at end of file diff --git a/test/OAuthClientTest.js b/test/OAuthClientTest.js index f177a826..f14e22b1 100644 --- a/test/OAuthClientTest.js +++ b/test/OAuthClientTest.js @@ -18,404 +18,404 @@ var expectedMigrationResponse = require('./mocks/authResponse.json'); var oauthClient = new OAuthClientTest({ - clientId: 'clientID', - clientSecret: 'clientSecret', - environment: 'sandbox', - redirectUri: 'http://localhost:8000/callback' + clientId: 'clientID', + clientSecret: 'clientSecret', + environment: 'sandbox', + redirectUri: 'http://localhost:8000/callback' }); describe('Tests for OAuthClient', function() { - var scope; - - it('Creates a new access token instance', function() { - var accessToken = oauthClient.getToken(); - expect(accessToken).to.have.property('realmId'); - expect(accessToken).to.have.property('token_type'); - expect(accessToken).to.have.property('refresh_token'); - expect(accessToken).to.have.property('expires_in'); - expect(accessToken).to.have.property('x_refresh_token_expires_in'); - expect(accessToken).to.have.property('id_token'); - expect(accessToken).to.have.property('latency'); + var scope; + + it('Creates a new access token instance', function() { + var accessToken = oauthClient.getToken(); + expect(accessToken).to.have.property('realmId'); + expect(accessToken).to.have.property('token_type'); + expect(accessToken).to.have.property('refresh_token'); + expect(accessToken).to.have.property('expires_in'); + expect(accessToken).to.have.property('x_refresh_token_expires_in'); + expect(accessToken).to.have.property('id_token'); + expect(accessToken).to.have.property('latency'); + }); + + + describe('Get the authorizationURI', function() { + it('When Scope is passed', function() { + var actualAuthUri = oauthClient.authorizeUri({scope:'testScope',state:'testState'}); + var expectedAuthUri = 'https://appcenter.intuit.com/connect/oauth2?client_id=clientID&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&response_type=code&scope=testScope&state=testState'; + expect(actualAuthUri).to.be.equal(expectedAuthUri); }); + it('When NO Scope is passed', function() { + try { + oauthClient.authorizeUri(); - describe('Get the authorizationURI', function() { - it('When Scope is passed', function() { - var actualAuthUri = oauthClient.authorizeUri({scope:'testScope',state:'testState'}); - var expectedAuthUri = 'https://appcenter.intuit.com/connect/oauth2?client_id=clientID&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&response_type=code&scope=testScope&state=testState'; - expect(actualAuthUri).to.be.equal(expectedAuthUri); - }); - - it('When NO Scope is passed', function() { - try { - oauthClient.authorizeUri(); - - } catch (e) { - expect(e.message).to.equal('Provide the scopes'); - } - }); - it('When Scope is passed as an array', function() { - var actualAuthUri = oauthClient.authorizeUri({scope:[OAuthClientTest.scopes.Accounting,OAuthClientTest.scopes.Payment,OAuthClientTest.scopes.OpenId],state:'testState'}); - var expectedAuthUri = 'https://appcenter.intuit.com/connect/oauth2?client_id=clientID&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&response_type=code&scope=com.intuit.quickbooks.accounting%20com.intuit.quickbooks.payment%20openid&state=testState'; - expect(actualAuthUri).to.be.equal(expectedAuthUri); - }); + } catch (e) { + expect(e.message).to.equal('Provide the scopes'); + } }); - - // Create bearer tokens - describe('Create Bearer Token', function() { - - before(function() { - - scope = nock('https://oauth.platform.intuit.com').persist() - .post('/oauth2/v1/tokens/bearer') - .reply(200, expectedTokenResponse, { - "content-type":"application/json", - "content-length":"1636", - "connection":"close", - "server":"nginx", - "intuit_tid":"12345-123-1234-12345", - "cache-control":"no-cache, no-store", - "pragma":"no-cache" - }); - }); - - it('Provide the uri to get the tokens', function() { - var parseRedirect = 'http://localhost:8000/callback?state=testState&code=Q011535008931rqveFweqmueq0GlOHhLPAFMp3NI2KJm5gbMMx'; - return oauthClient.createToken(parseRedirect) - .then(function(authResponse) { - expect(authResponse.getToken().access_token).to.be.equal(expectedAccessToken.access_token); - }); + it('When Scope is passed as an array', function() { + var actualAuthUri = oauthClient.authorizeUri({scope:[OAuthClientTest.scopes.Accounting,OAuthClientTest.scopes.Payment,OAuthClientTest.scopes.OpenId],state:'testState'}); + var expectedAuthUri = 'https://appcenter.intuit.com/connect/oauth2?client_id=clientID&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&response_type=code&scope=com.intuit.quickbooks.accounting%20com.intuit.quickbooks.payment%20openid&state=testState'; + expect(actualAuthUri).to.be.equal(expectedAuthUri); + }); + }); + + // Create bearer tokens + describe('Create Bearer Token', function() { + + before(function() { + + scope = nock('https://oauth.platform.intuit.com').persist() + .post('/oauth2/v1/tokens/bearer') + .reply(200, expectedTokenResponse, { + "content-type":"application/json", + "content-length":"1636", + "connection":"close", + "server":"nginx", + "intuit_tid":"12345-123-1234-12345", + "cache-control":"no-cache, no-store", + "pragma":"no-cache" }); + }); - it('When NO uri is provided', function() { - return oauthClient.createToken() - .then(function(authResponse) { - expect(authResponse.getToken().access_token).to.be.equal(expectedAccessToken.access_token); - }) - .catch(function(e) { - expect(e.message).to.equal('Provide the Uri'); - }); + it('Provide the uri to get the tokens', function() { + var parseRedirect = 'http://localhost:8000/callback?state=testState&code=Q011535008931rqveFweqmueq0GlOHhLPAFMp3NI2KJm5gbMMx'; + return oauthClient.createToken(parseRedirect) + .then(function(authResponse) { + expect(authResponse.getToken().access_token).to.be.equal(expectedAccessToken.access_token); }); }); - // Refresh bearer tokens - describe('Refresh Bearer Token', function() { - before(function() { - var refreshAccessToken = require("./mocks/refreshResponse.json"); - scope = nock('https://oauth.platform.intuit.com').persist() - .post('/oauth2/v1/tokens/bearer') - .reply(200,refreshAccessToken , { - "content-type":"application/json", - "content-length":"1636", - "connection":"close", - "server":"nginx", - "intuit_tid":"12345-123-1234-12345", - "cache-control":"no-cache, no-store", - "pragma":"no-cache" - }); + it('When NO uri is provided', function() { + return oauthClient.createToken() + .then(function(authResponse) { + expect(authResponse.getToken().access_token).to.be.equal(expectedAccessToken.access_token); + }) + .catch(function(e) { + expect(e.message).to.equal('Provide the Uri'); }); - - it('Refresh the existing tokens', function() { - return oauthClient.refresh() - .then(function(authResponse) { - expect(authResponse.getToken().refresh_token).to.be.equal(expectedAccessToken.refresh_token); - }); + }); + }); + + // Refresh bearer tokens + describe('Refresh Bearer Token', function() { + before(function() { + var refreshAccessToken = require("./mocks/refreshResponse.json"); + scope = nock('https://oauth.platform.intuit.com').persist() + .post('/oauth2/v1/tokens/bearer') + .reply(200,refreshAccessToken , { + "content-type":"application/json", + "content-length":"1636", + "connection":"close", + "server":"nginx", + "intuit_tid":"12345-123-1234-12345", + "cache-control":"no-cache, no-store", + "pragma":"no-cache" }); + }); - it('Refresh : refresh token is missing', function(){ - oauthClient.getToken().refresh_token = null; - return oauthClient.refresh() - .catch(function(e) { - expect(e.message).to.equal('The Refresh token is missing'); - }); + it('Refresh the existing tokens', function() { + return oauthClient.refresh() + .then(function(authResponse) { + expect(authResponse.getToken().refresh_token).to.be.equal(expectedAccessToken.refresh_token); }); + }); - it('Refresh : refresh token is invalid', function(){ - oauthClient.getToken().refresh_token = 'sample_refresh_token'; - oauthClient.getToken().x_refresh_token_expires_in = '300'; - return oauthClient.refresh() - .catch(function(e) { - expect(e.message).to.equal('The Refresh token is invalid, please Authorize again.'); - }); + it('Refresh : refresh token is missing', function(){ + oauthClient.getToken().refresh_token = null; + return oauthClient.refresh() + .catch(function(e) { + expect(e.message).to.equal('The Refresh token is missing'); }); }); - // Revoke bearer tokens - describe('Revoke Bearer Token', function(){ - before(function() { - scope = nock('https://developer.api.intuit.com').persist() - .post('/v2/oauth2/tokens/revoke') - .reply(200, '' , { - "content-type":"application/json", - "content-length":"1636", - "connection":"close", - "server":"nginx", - "intuit_tid":"12345-123-1234-12345", - "cache-control":"no-cache, no-store", - "pragma":"no-cache" - }); + it('Refresh : refresh token is invalid', function(){ + oauthClient.getToken().refresh_token = 'sample_refresh_token'; + oauthClient.getToken().x_refresh_token_expires_in = '300'; + return oauthClient.refresh() + .catch(function(e) { + expect(e.message).to.equal('The Refresh token is invalid, please Authorize again.'); }); - - it('Revoke the existing tokens', function() { - oauthClient.getToken().x_refresh_token_expires_in = '4535995551112'; - return oauthClient.revoke() - .then(function(authResponse) { - expect(authResponse.getToken().refresh_token).to.be.equal(expectedAccessToken.refresh_token); - }); + }); + }); + + // Revoke bearer tokens + describe('Revoke Bearer Token', function(){ + before(function() { + scope = nock('https://developer.api.intuit.com').persist() + .post('/v2/oauth2/tokens/revoke') + .reply(200, '' , { + "content-type":"application/json", + "content-length":"1636", + "connection":"close", + "server":"nginx", + "intuit_tid":"12345-123-1234-12345", + "cache-control":"no-cache, no-store", + "pragma":"no-cache" }); + }); - it('Revoke : refresh token is missing', function() { - oauthClient.getToken().refresh_token = null; - return oauthClient.revoke() - .catch(function(e) { - expect(e.message).to.equal('The Refresh token is missing'); - }); + it('Revoke the existing tokens', function() { + oauthClient.getToken().x_refresh_token_expires_in = '4535995551112'; + return oauthClient.revoke() + .then(function(authResponse) { + expect(authResponse.getToken().refresh_token).to.be.equal(''); }); + }); - it('Revoke : refresh token is invalid', function() { - oauthClient.getToken().refresh_token = 'sample_refresh_token'; - oauthClient.getToken().x_refresh_token_expires_in = '300'; - return oauthClient.revoke() - .catch(function(e) { - expect(e.message).to.equal('The Refresh token is invalid, please Authorize again.'); - }); + it('Revoke : refresh token is missing', function() { + oauthClient.getToken().refresh_token = null; + return oauthClient.revoke() + .catch(function(e) { + expect(e.message).to.equal('The Refresh token is missing'); }); }); - // Get User Info ( OpenID ) - describe('Get User Info ( OpenID )', function() { - describe('', function () { - before(function () { - scope = nock('https://sandbox-accounts.platform.intuit.com').persist() - .get('/v1/openid_connect/userinfo') - .reply(200, expectedUserInfo, { - "content-type": "application/json", - "content-length": "1636", - "connection": "close", - "server": "nginx", - "intuit_tid": "12345-123-1234-12345", - "cache-control": "no-cache, no-store", - "pragma": "no-cache" - }); + it('Revoke : refresh token is invalid', function() { + oauthClient.getToken().refresh_token = 'sample_refresh_token'; + oauthClient.getToken().x_refresh_token_expires_in = '300'; + return oauthClient.revoke() + .catch(function(e) { + expect(e.message).to.equal('The Refresh token is invalid, please Authorize again.'); }); + }); + }); + + // Get User Info ( OpenID ) + describe('Get User Info ( OpenID )', function() { + describe('', function () { + before(function () { + scope = nock('https://sandbox-accounts.platform.intuit.com').persist() + .get('/v1/openid_connect/userinfo') + .reply(200, expectedUserInfo, { + "content-type": "application/json", + "content-length": "1636", + "connection": "close", + "server": "nginx", + "intuit_tid": "12345-123-1234-12345", + "cache-control": "no-cache, no-store", + "pragma": "no-cache" + }); + }); - it('Get User Info in Sandbox', function () { - return oauthClient.getUserInfo() - .then(function (authResponse) { - expect(JSON.stringify(authResponse.getJson())).to.be.equal(JSON.stringify(expectedUserInfo)); - }); - }); + it('Get User Info in Sandbox', function () { + return oauthClient.getUserInfo() + .then(function (authResponse) { + expect(JSON.stringify(authResponse.getJson())).to.be.equal(JSON.stringify(expectedUserInfo)); + }); }); + }); - describe('', function () { - before(function () { - scope = nock('https://accounts.platform.intuit.com').persist() - .get('/v1/openid_connect/userinfo') - .reply(200, expectedUserInfo, { - "content-type": "application/json", - "content-length": "1636", - "connection": "close", - "server": "nginx", - "intuit_tid": "12345-123-1234-12345", - "cache-control": "no-cache, no-store", - "pragma": "no-cache" - }); - }); + describe('', function () { + before(function () { + scope = nock('https://accounts.platform.intuit.com').persist() + .get('/v1/openid_connect/userinfo') + .reply(200, expectedUserInfo, { + "content-type": "application/json", + "content-length": "1636", + "connection": "close", + "server": "nginx", + "intuit_tid": "12345-123-1234-12345", + "cache-control": "no-cache, no-store", + "pragma": "no-cache" + }); + }); - it('Get User Info in Production', function () { - oauthClient.environment = 'production'; - return oauthClient.getUserInfo() - .then(function (authResponse) { - expect(JSON.stringify(authResponse.getJson())).to.be.equal(JSON.stringify(expectedUserInfo)); - }); - }); + it('Get User Info in Production', function () { + oauthClient.environment = 'production'; + return oauthClient.getUserInfo() + .then(function (authResponse) { + expect(JSON.stringify(authResponse.getJson())).to.be.equal(JSON.stringify(expectedUserInfo)); + }); + }); + }); + }); + + // make API Call + describe('Make API Call ', function() { + describe('', function() { + before(function() { + scope = nock('https://sandbox-quickbooks.api.intuit.com').persist() + .get('/v3/company/12345/companyinfo/12345') + .reply(200, expectedMakeAPICall , { + "content-type":"application/json", + "content-length":"1636", + "connection":"close", + "server":"nginx", + "intuit_tid":"12345-123-1234-12345", + "cache-control":"no-cache, no-store", + "pragma":"no-cache" + }); + }); + it('Make API Call in Sandbox Environment', function() { + oauthClient.getToken().realmId = '12345'; + return oauthClient.makeApiCall({url:'https://sandbox-quickbooks.api.intuit.com/v3/company/'+'12345'+'/companyinfo/'+'12345'}) + .then(function(authResponse) { + expect(JSON.stringify(authResponse.getJson())).to.be.equal(JSON.stringify(expectedMakeAPICall)); + }); }); }); - // make API Call - describe('Make API Call ', function() { - describe('', function() { - before(function() { - scope = nock('https://sandbox-quickbooks.api.intuit.com').persist() - .get('/v3/company/12345/companyinfo/12345') - .reply(200, expectedMakeAPICall , { - "content-type":"application/json", - "content-length":"1636", - "connection":"close", - "server":"nginx", - "intuit_tid":"12345-123-1234-12345", - "cache-control":"no-cache, no-store", - "pragma":"no-cache" - }); - }); - it('Make API Call in Sandbox Environment', function() { - oauthClient.getToken().realmId = '12345'; - return oauthClient.makeApiCall({url:'https://sandbox-quickbooks.api.intuit.com/v3/company/'+'12345'+'/companyinfo/'+'12345'}) - .then(function(authResponse) { - expect(JSON.stringify(authResponse.getJson())).to.be.equal(JSON.stringify(expectedMakeAPICall)); - }); - }); - }); - - describe('', function() { - before(function() { - scope = nock('https://quickbooks.api.intuit.com').persist() - .get('/v3/company/12345/companyinfo/12345') - .reply(200, expectedMakeAPICall , { - "content-type":"application/json", - "content-length":"1636", - "connection":"close", - "server":"nginx", - "intuit_tid":"12345-123-1234-12345", - "cache-control":"no-cache, no-store", - "pragma":"no-cache" - }); - }); - it('Make API Call in Production Environment', function() { - oauthClient.environment = 'production'; - oauthClient.getToken().realmId = '12345'; - return oauthClient.makeApiCall({url:'https://quickbooks.api.intuit.com/v3/company/'+'12345'+'/companyinfo/'+'12345'}) - .then(function(authResponse) { - expect(JSON.stringify(authResponse.getJson())).to.be.equal(JSON.stringify(expectedMakeAPICall)); - }); - }); - }); + describe('', function() { + before(function() { + scope = nock('https://quickbooks.api.intuit.com').persist() + .get('/v3/company/12345/companyinfo/12345') + .reply(200, expectedMakeAPICall , { + "content-type":"application/json", + "content-length":"1636", + "connection":"close", + "server":"nginx", + "intuit_tid":"12345-123-1234-12345", + "cache-control":"no-cache, no-store", + "pragma":"no-cache" + }); + }); + it('Make API Call in Production Environment', function() { + oauthClient.environment = 'production'; + oauthClient.getToken().realmId = '12345'; + return oauthClient.makeApiCall({url:'https://quickbooks.api.intuit.com/v3/company/'+'12345'+'/companyinfo/'+'12345'}) + .then(function(authResponse) { + expect(JSON.stringify(authResponse.getJson())).to.be.equal(JSON.stringify(expectedMakeAPICall)); + }); + }); }); + }); + + // make API Call + describe('Validate Id Token ', function() { + describe('', function() { + before(function() { + scope = nock('https://oauth.platform.intuit.com').persist() + .get('/op/v1/jwks') + .reply(200, expectedjwkResponseCall , { + "content-type":"application/json;charset=UTF-8", + "content-length":"264", + "connection":"close", + "server":"nginx", + "strict-transport-security":"max-age=15552000", + "intuit_tid":"1234-1234-1234-123", + "cache-control":"no-cache, no-store", + "pragma":"no-cache" + }); + }); - // make API Call - describe('Validate Id Token ', function() { - describe('', function() { - before(function() { - scope = nock('https://oauth.platform.intuit.com').persist() - .get('/op/v1/jwks') - .reply(200, expectedjwkResponseCall , { - "content-type":"application/json;charset=UTF-8", - "content-length":"264", - "connection":"close", - "server":"nginx", - "strict-transport-security":"max-age=15552000", - "intuit_tid":"1234-1234-1234-123", - "cache-control":"no-cache, no-store", - "pragma":"no-cache" - }); - }); - - it('Validate Id Token', function() { - oauthClient.getToken().setToken(expectedOpenIDToken); - oauthClient.validateIdToken() - .then(function(response) { - expect(response).to.be.equal(expectedvalidateIdToken); - }); - }); + it('Validate Id Token', function() { + oauthClient.getToken().setToken(expectedOpenIDToken); + oauthClient.validateIdToken() + .then(function(response) { + expect(response).to.be.equal(expectedvalidateIdToken); + }); + }); - }); }); + }); - // Check Access Token Validity - describe('Check Access-Token Validity', function() { - it('access-token is valid', function() { - var validity = oauthClient.isAccessTokenValid(); - expect(validity).to.be.true; - }); - it('access-token is not valid', function() { - oauthClient.getToken().expires_in = null; - var validity = oauthClient.isAccessTokenValid(); - expect(validity).to.be.false; - }); + // Check Access Token Validity + describe('Check Access-Token Validity', function() { + it('access-token is valid', function() { + var validity = oauthClient.isAccessTokenValid(); + expect(validity).to.be.true; }); - - // Get Token - describe('Get Token', function() { - it('get token instance', function() { - var token = oauthClient.getToken(); - expect(token).to.be.a('Object'); - }); - it('accesstoken is not valid', function() { - oauthClient.getToken().expires_in = null; - var validity = oauthClient.isAccessTokenValid(); - expect(validity).to.be.false; - }); + it('access-token is not valid', function() { + oauthClient.getToken().expires_in = null; + var validity = oauthClient.isAccessTokenValid(); + expect(validity).to.be.false; }); + }); - // Get Auth Header - describe('Get Auth Header', function() { - it('Auth Header is valid', function() { - var authHeader = oauthClient.authHeader(); - expect(authHeader).to.be.equal('Y2xpZW50SUQ6Y2xpZW50U2VjcmV0'); - }); - it('accesstoken is not valid', function() { - oauthClient.getToken().expires_in = null; - var validity = oauthClient.isAccessTokenValid(); - expect(validity).to.be.false; - }); + // Get Token + describe('Get Token', function() { + it('get token instance', function() { + var token = oauthClient.getToken(); + expect(token).to.be.a('Object'); }); - - // Generate OAuth1Sign - - describe('Generate OAuth1Sign', function() { - it('Generate OAuth1Sign String', function() { - var params = { - method: 'POST', - uri: 'uri', - oauth_consumer_key : 'qyprdFsHNQtdRupMKmYnDt6MOjWBW9', - oauth_consumer_secret : 'TOI5I5dK94dkqDy9SlRD7s08uQUvtow6CK53SpJ1', - oauth_signature_method : 'HMAC-SHA1', - oauth_timestamp : 'timestamp', - oauth_nonce : 'nonce', - oauth_version : '1.0', - access_token : 'qyprdlGm45UFPPhwAM59Awaq4BAd6hNFwp1SSkZDn54Zrgv9', - access_secret : 'xPZ44ZvT17H56pkAAqhfyjuZlF5zZb2k9ej3ohko' - } - - var oauth1Sign = oauthClient.generateOauth1Sign(params); - expect(oauth1Sign).to.be.a('String'); - }); + it('accesstoken is not valid', function() { + oauthClient.getToken().expires_in = null; + var validity = oauthClient.isAccessTokenValid(); + expect(validity).to.be.false; }); + }); - // Migrate Tokens - describe('Migrate OAuth Tokens', function() { - describe('Sandbox', function() { - before(function() { - scope = nock('https://developer.api.intuit.com').persist() - .post('/v2/oauth2/tokens/migrate') - .reply(200, expectedMigrationResponse , { - "content-type":"application/json;charset=UTF-8", - "content-length":"264", - "connection":"close", - "server":"nginx", - "strict-transport-security":"max-age=15552000", - "intuit_tid":"1234-1234-1234-123", - "cache-control":"no-cache, no-store", - "pragma":"no-cache" - }); - }); - - it('Migrate OAuth Tokens - Sandbox', function() { - - var timestamp = Math.round(new Date().getTime()/1000); - - var params = { - oauth_consumer_key : 'oauth_consumer_key', - oauth_consumer_secret : 'oauth_consumer_secret', - oauth_signature_method : 'HMAC-SHA1', - oauth_timestamp : timestamp, - oauth_nonce : 'nonce', - oauth_version : '1.0', - access_token : 'sample_access_token', - access_secret : 'sample_access_secret', - scope : ['com.intuit.quickbooks.accounting'] - } - oauthClient.migrate(params) - .then(function(response){ - expect(response).to.be.equal(expectedMigrationResponse); - }); - }); + // Get Auth Header + describe('Get Auth Header', function() { + it('Auth Header is valid', function() { + var authHeader = oauthClient.authHeader(); + expect(authHeader).to.be.equal('Y2xpZW50SUQ6Y2xpZW50U2VjcmV0'); + }); + it('accesstoken is not valid', function() { + oauthClient.getToken().expires_in = null; + var validity = oauthClient.isAccessTokenValid(); + expect(validity).to.be.false; + }); + }); + + // Generate OAuth1Sign + + describe('Generate OAuth1Sign', function() { + it('Generate OAuth1Sign String', function() { + var params = { + method: 'POST', + uri: 'uri', + oauth_consumer_key : 'qyprdFsHNQtdRupMKmYnDt6MOjWBW9', + oauth_consumer_secret : 'TOI5I5dK94dkqDy9SlRD7s08uQUvtow6CK53SpJ1', + oauth_signature_method : 'HMAC-SHA1', + oauth_timestamp : 'timestamp', + oauth_nonce : 'nonce', + oauth_version : '1.0', + access_token : 'qyprdlGm45UFPPhwAM59Awaq4BAd6hNFwp1SSkZDn54Zrgv9', + access_secret : 'xPZ44ZvT17H56pkAAqhfyjuZlF5zZb2k9ej3ohko' + } + + var oauth1Sign = oauthClient.generateOauth1Sign(params); + expect(oauth1Sign).to.be.a('String'); + }); + }); + + // Migrate Tokens + describe('Migrate OAuth Tokens', function() { + describe('Sandbox', function() { + before(function() { + scope = nock('https://developer.api.intuit.com').persist() + .post('/v2/oauth2/tokens/migrate') + .reply(200, expectedMigrationResponse , { + "content-type":"application/json;charset=UTF-8", + "content-length":"264", + "connection":"close", + "server":"nginx", + "strict-transport-security":"max-age=15552000", + "intuit_tid":"1234-1234-1234-123", + "cache-control":"no-cache, no-store", + "pragma":"no-cache" + }); + }); - }); + it('Migrate OAuth Tokens - Sandbox', function() { + + var timestamp = Math.round(new Date().getTime()/1000); + + var params = { + oauth_consumer_key : 'oauth_consumer_key', + oauth_consumer_secret : 'oauth_consumer_secret', + oauth_signature_method : 'HMAC-SHA1', + oauth_timestamp : timestamp, + oauth_nonce : 'nonce', + oauth_version : '1.0', + access_token : 'sample_access_token', + access_secret : 'sample_access_secret', + scope : ['com.intuit.quickbooks.accounting'] + } + oauthClient.migrate(params) + .then(function(response){ + expect(response).to.be.equal(expectedMigrationResponse); + }); + }); }); + }); -}); + +}); \ No newline at end of file