diff --git a/index.d.ts b/index.d.ts new file mode 100644 index 00000000..56bb8d1d --- /dev/null +++ b/index.d.ts @@ -0,0 +1,142 @@ +import csrf from 'csrf'; + +declare class AuthResponse { + constructor(params: AuthResponse.AuthResponseParams); + processResponse(response: Object): void; + getToken(): Token; + text(): string; + status(): number; + headers(): Object; + valid(): boolean; + getJson(): Object; + get_intuit_tid(): string; + isContentType(): boolean; + getContentType(): string; + isJson(): boolean; + +} + +declare namespace AuthResponse { + export interface AuthResponseParams { + token?: Token; + response?: Response; + body?: string; + json?: Object; + intuit_tid?: string; + } +} + +declare class Token implements Token.TokenData { + latency: number; + realmId: string; + token_type: string; + access_token: string; + refresh_token: string; + expires_in: number; + x_refresh_token_expires_in: number; + id_token: string; + createdAt: string; + accessToken(): string; + refreshToken(): string; + tokenType(): string; + getToken(): Token.TokenData; + setToken(tokenData: Token.TokenData): Token; + clearToken(): Token; + isAccessTokenValid(): boolean; + isRefreshTokenValid(): boolean; +} + +declare namespace Token { + export interface TokenData { + realmId?: string; + token_type?: string; + access_token?: string; + refresh_token?: string; + expires_in: number; + x_refresh_token_expires_in: number; + id_token?: string; + latency: number; + createdAt: string; + } +} + +declare class OAuthClient { + constructor(config: OAuthClient.OAuthClientConfig); + authHeader(): string; + authorizeUri(params: OAuthClient.AuthorizeParams): string; + createError(e: Error, authResponse?: AuthResponse): OAuthClient.OAuthClientError; + createToken(uri: string): Promise; + getKeyFromJWKsURI(id_token: string, kid: string, request: Request): Promise; + getTokenRequest(request: Request): Promise; + getUserInfo(params?: OAuthClient.GetUserInfoParams): Promise; + isAccessTokenValid(): boolean; + loadResponse(request: Request): Promise; + loadResponseFromJWKsURI(request: Request): Promise; + log(level: string, message: string, messageData: any): void; + makeApiCall(params?: OAuthClient.MakeApiCallParams): Promise; + refresh(): Promise; + refreshUsingToken(refresh_token: string): Promise; + revoke(params?: OAuthClient.RevokeParams): Promise; + setToken(params: Token.TokenData): Token; + validateIdToken(params?: OAuthClient.ValidateIdTokenParams): Promise; + validateToken(): void; +} + +declare namespace OAuthClient { + export interface OAuthClientConfig { + clientId: string; + clientSecret: string; + redirectUri?: string; + environment?: string; + token: Token; + logging: boolean; + } + + export enum environment { + sandbox = 'https://sandbox-quickbooks.api.intuit.com/', + production = 'https://quickbooks.api.intuit.com/' + } + + export enum scopes { + Accounting = 'com.intuit.quickbooks.accounting', + Payment = 'com.intuit.quickbooks.payment', + Payroll = 'com.intuit.quickbooks.payroll', + TimeTracking = 'com.intuit.quickbooks.payroll.timetracking', + Benefits = 'com.intuit.quickbooks.payroll.benefits', + Profile = 'profile', + Email = 'email', + Phone = 'phone', + Address = 'address', + OpenId = 'openid', + Intuit_name = 'intuit_name' + } + + export interface AuthorizeParams { + scope: scopes | scopes[] | string; + state?: csrf | string; + } + + export interface RevokeParams { + access_token?: string; + refresh_token?: string; + } + + export interface GetUserInfoParams { } + + export interface MakeApiCallParams { + url: string; + } + + export interface ValidateIdTokenParams { + id_token?: string; + } + + export interface OAuthClientError extends Error { + intuit_tid: string; + authResponse: AuthResponse; + originalMessage: string; + error_description: string; + } +} + +export = OAuthClient; diff --git a/package.json b/package.json index 239c74a4..b2c46172 100644 --- a/package.json +++ b/package.json @@ -3,10 +3,11 @@ "version": "3.0.2", "description": "Intuit Node.js client for OAuth2.0 and OpenIDConnect", "main": "./src/OAuthClient.js", + "types": "./index.d.ts", "scripts": { "start": "node index.js", "karma": "karma start karma.conf.js", - "test": "nyc mocha", + "test": "nyc mocha && npm run test-ts", "snyk": "snyk test", "lint": "eslint .", "fix": "eslint . --fix", @@ -15,8 +16,9 @@ "test-debug": "mocha --inspect-brk --watch test", "show-coverage": "npm test; open -a 'Google Chrome' coverage/index.html", "clean-install": "rm -rf node_modules && npm install", - "snyk-protect": "snyk protect", - "prepublish": "npm run snyk-protect" + "snyk-protect": "snyk-protect", + "prepublish": "npm run snyk-protect", + "test-ts": "mocha -r ts-node/register test/**/*.test.ts" }, "keywords": [ "intuit-oauth", @@ -69,13 +71,19 @@ "dependencies": { "atob": "2.1.2", "csrf": "^3.0.4", - "jsonwebtoken": "^8.3.0", - "popsicle": "10.0.1", + "express": "^4.17.1", + "jsonwebtoken": "^9.0.2", + "n": "^10.1.0", + "popsicle": "^12.1.2", "query-string": "^6.12.1", "rsa-pem-from-mod-exp": "^0.8.4", "winston": "^3.1.0" }, "devDependencies": { + "@snyk/protect": "^1.657.0", + "@types/chai": "^4.2.14", + "@types/express": "^4.17.1", + "@types/mocha": "^8.0.3", "btoa": "^1.2.1", "chai": "^4.1.2", "chai-as-promised": "^7.1.1", @@ -83,12 +91,13 @@ "eslint-config-airbnb-base": "^14.1.0", "eslint-config-prettier": "^6.11.0", "eslint-plugin-import": "^2.20.2", - "mocha": "^7.1.2", + "mocha": "^11.1.0", "nock": "^9.2.3", "nyc": "^15.0.1", "prettier": "^2.0.5", "sinon": "^9.0.2", - "snyk": "^1.316.1" + "ts-node": "^9.0.0", + "typescript": "^4.9.5" }, "snyk": true } diff --git a/sample/.env.example b/sample/javascript/.env.example similarity index 100% rename from sample/.env.example rename to sample/javascript/.env.example diff --git a/sample/README.md b/sample/javascript/README.md similarity index 100% rename from sample/README.md rename to sample/javascript/README.md diff --git a/sample/app.js b/sample/javascript/app.js similarity index 100% rename from sample/app.js rename to sample/javascript/app.js diff --git a/sample/package.json b/sample/javascript/package.json similarity index 100% rename from sample/package.json rename to sample/javascript/package.json diff --git a/sample/typescript/.env.example b/sample/typescript/.env.example new file mode 100644 index 00000000..10396306 --- /dev/null +++ b/sample/typescript/.env.example @@ -0,0 +1,5 @@ +# Environment Variables. + + +PORT= +NGROK_ENABLED= true diff --git a/sample/typescript/README.md b/sample/typescript/README.md new file mode 100644 index 00000000..c88c602b --- /dev/null +++ b/sample/typescript/README.md @@ -0,0 +1,96 @@ + +[![Sample Banner](./public/images/Sample.png)][ss1] + +Intuit OAuth2.0 Sample - NodeJS +========================================================== + +## Overview + +This is a `sample` app built using Node.js and Express Framework to showcase how to Authorize and Authenticate using Intuit's OAuth2.0 Client library. + +## Installation + +### Requirements + +* [Node.js](http://nodejs.org) >= 6.0.0 +* [Intuit Developer](https://developer.intuit.com) Account + +### Via Github Repo (Recommended) + +```bash +$ cd sample +$ npm install +``` + +## Configuration + +Copy the contents from `.env.example` to `.env` within the sample directory: +```bash +$ cp .env.example .env +``` +Edit the `.env` file to add your: + + +* **PORT:(optional)** Optional port number for the app to be served +* **NGROK_ENABLED:(optional)** By default it is set to `false`. If you want to serve the Sample App over HTTPS ( which is mandatory if you want to test this app using Production Credentials), set the variable to `true` + + + +### TLS / SSL (**optional**) + +If you want your enpoint to be exposed over the internet. The easiest way to do that while you are still developing your code locally is to use [ngrok](https://ngrok.com/). + +You dont have to worry about installing ngrok. The sample application does that for you. +1. Just set `NGROK_ENABLED` = `true` in `.env` + + +## Usage + +```bash +$ npm start +``` + +### Without ngrok (if you are using localhost i.e `NGROK_ENABLED`=`false` in `.env`) +You will see an URL as below: +```bash +💳 Step 1 : Paste this URL in your browser : http://localhost:8000 +💳 Step 2 : Copy and Paste the clientId and clientSecret from : https://developer.intuit.com +💳 Step 3 : Copy Paste this callback URL into `redirectURI` : http://localhost:8000/callback +💻 Step 4 : Make Sure this redirect URI is also listed under the Redirect URIs on your app in : https://developer.intuit.com +``` + +### With ngrok (if you are using ngrok i.e `NGROK_ENABLED`=`true` in `.env`) + +Your will see an URL as below : +```bash +💳 Step 1 : Paste this URL in your browser : https://9b4ee833.ngrok.io +💳 Step 2 : Copy and Paste the clientId and clientSecret from : https://developer.intuit.com +💳 Step 3 : Copy Paste this callback URL into `redirectURI` : https://9b4ee833.ngrok.io/callback +💻 Step 4 : Make Sure this redirect URI is also listed under the Redirect URIs on your app in : https://developer.intuit.com +``` + +Click on the URL and follow through the instructions given in the sample app. + + +## Links + +Project Repo + +* https://github.com/intuit/oauth-jsclient + +Intuit OAuth2.0 API Reference + +* https://developer.intuit.com/app/developer/qbo/docs/develop/authentication-and-authorization/oauth-2.0 + +Intuit OAuth2.0 Playground + +* https://developer.intuit.com/app/developer/playground + +## Contributions + +Any reports of problems, comments or suggestions are most welcome. + +Please report these on [Issue Tracker in Github](https://github.com/intuit/oauth-jsclient/issues). + + +[ss1]: https://help.developer.intuit.com/s/samplefeedback?cid=9010&repoName=Intuit-OAuth2.0-Sample-NodeJS diff --git a/sample/typescript/dist/app.js b/sample/typescript/dist/app.js new file mode 100644 index 00000000..8c8f765d --- /dev/null +++ b/sample/typescript/dist/app.js @@ -0,0 +1,140 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var dotenv_1 = __importDefault(require("dotenv")); +var express_1 = __importDefault(require("express")); +var path_1 = __importDefault(require("path")); +var intuit_oauth_1 = __importDefault(require("intuit-oauth")); +var body_parser_1 = __importDefault(require("body-parser")); +dotenv_1.default.config(); +var app = express_1.default(); +var ngrok = (process.env.NGROK_ENABLED === "true") ? require('ngrok') : null; +/** + * Configure View and Handlebars + */ +app.use(body_parser_1.default.urlencoded({ extended: true })); +app.use(express_1.default.static(path_1.default.join(__dirname, '../../public'))); +app.engine('html', require('ejs').renderFile); +app.set('view engine', 'html'); +app.use(body_parser_1.default.json()); +var urlencodedParser = body_parser_1.default.urlencoded({ extended: false }); +/** + * App Variables + * @type {null} + */ +var oauth2_token_json = null, redirectUri = ''; +/** + * Instantiate new Client + * @type {OAuthClient} + */ +var oauthClient = null; +/** + * Home Route + */ +app.get('/', function (req, res) { + res.render('index'); +}); +/** + * Get the AuthorizeUri + */ +app.get('/authUri', urlencodedParser, function (req, res) { + oauthClient = new intuit_oauth_1.default({ + clientId: req.query.json.clientId, + clientSecret: req.query.json.clientSecret, + environment: req.query.json.environment, + redirectUri: req.query.json.redirectUri + }); + var authUri = oauthClient.authorizeUri({ scope: [intuit_oauth_1.default.scopes.Accounting], state: 'intuit-test' }); + res.send(authUri); +}); +/** + * Handle the callback to extract the `Auth Code` and exchange them for `Bearer-Tokens` + */ +app.get('/callback', function (req, res) { + oauthClient.createToken(req.url) + .then(function (authResponse) { + oauth2_token_json = JSON.stringify(authResponse.getJson(), null, 2); + }) + .catch(function (e) { + console.error(e); + }); + res.send(''); +}); +/** + * Display the token : CAUTION : JUST for sample purposes + */ +app.get('/retrieveToken', function (req, res) { + res.send(oauth2_token_json); +}); +/** + * Refresh the access-token + */ +app.get('/refreshAccessToken', function (req, res) { + oauthClient.refresh() + .then(function (authResponse) { + console.log('The Refresh Token is ' + JSON.stringify(authResponse.getJson())); + oauth2_token_json = JSON.stringify(authResponse.getJson(), null, 2); + res.send(oauth2_token_json); + }) + .catch(function (e) { + console.error(e); + }); +}); +/** + * getCompanyInfo () + */ +app.get('/getCompanyInfo', function (req, res) { + var companyID = oauthClient.getToken().realmId; + var url = oauthClient.environment == 'sandbox' ? intuit_oauth_1.default.environment.sandbox : intuit_oauth_1.default.environment.production; + oauthClient.makeApiCall({ url: url + 'v3/company/' + companyID + '/companyinfo/' + companyID }) + .then(function (authResponse) { + console.log("authResponse: ", authResponse); + console.log("The response for API call is :" + JSON.stringify(authResponse.json)); + res.send(authResponse.json); + }) + .catch(function (e) { + console.error(e); + }); +}); +/** + * disconnect () + */ +app.get('/disconnect', function (req, res) { + console.log('The disconnect called '); + var authUri = oauthClient.authorizeUri({ scope: [intuit_oauth_1.default.scopes.OpenId, intuit_oauth_1.default.scopes.Email], state: 'intuit-test' }); + res.redirect(authUri); +}); +/** + * Start server on HTTP (will use ngrok for HTTPS forwarding) + */ +var server = app.listen(process.env.PORT || 8000, function () { + var address = server.address(); + console.log("\uD83D\uDCBB Server listening on port " + address.port); + if (!ngrok) { + redirectUri = "" + address.port + '/callback'; + console.log("\uD83D\uDCB3 Step 1 : Paste this URL in your browser : " + 'http://localhost:' + ("" + address.port)); + console.log('💳 Step 2 : Copy and Paste the clientId and clientSecret from : https://developer.intuit.com'); + console.log("\uD83D\uDCB3 Step 3 : Copy Paste this callback URL into redirectURI :" + 'http://localhost:' + ("" + address.port) + '/callback'); + console.log("\uD83D\uDCBB Step 4 : Make Sure this redirect URI is also listed under the Redirect URIs on your app in : https://developer.intuit.com"); + } +}); +/** + * Optional : If NGROK is enabled + */ +if (ngrok) { + console.log("NGROK Enabled"); + ngrok.connect({ addr: process.env.PORT || 8000 }, function (err, url) { + if (err) { + process.exit(1); + } + else { + redirectUri = url + '/callback'; + console.log("\uD83D\uDCB3 Step 1 : Paste this URL in your browser : " + url); + console.log('💳 Step 2 : Copy and Paste the clientId and clientSecret from : https://developer.intuit.com'); + console.log("\uD83D\uDCB3 Step 3 : Copy Paste this callback URL into redirectURI : " + redirectUri); + console.log("\uD83D\uDCBB Step 4 : Make Sure this redirect URI is also listed under the Redirect URIs on your app in : https://developer.intuit.com"); + } + }); +} diff --git a/sample/typescript/package.json b/sample/typescript/package.json new file mode 100644 index 00000000..c9d74b93 --- /dev/null +++ b/sample/typescript/package.json @@ -0,0 +1,27 @@ +{ + "name": "intuit-nodejsclient", + "version": "1.0.0", + "description": "A sample NodeJs typescript application to demonstrate the use of the client OAuth library", + "scripts": { + "start": "tsc && node dist/app", + "test": "./node_modules/mocha/bin/mocha test/**/*-test.js --reporter spec" + }, + "author": "anil_kumar3@intuit.com", + "license": "APACHE", + "homepage": "https://github.intuit.com/abisalehalliprasan/oauth-jsclient", + "dependencies": { + "body-parser": "latest", + "dotenv": "^8.2.0", + "ejs": "^3.1.10", + "express": "^4.14.0", + "express-session": "^1.14.2", + "intuit-oauth": "^4.2.0", + "ngrok": "^5.0.0-beta.2", + "path": "^0.12.7" + }, + "devDependencies": { + "@types/body-parser": "^1.17.1", + "@types/express": "^4.17.1", + "typescript": "^3.6.4" + } +} diff --git a/sample/typescript/src/app.ts b/sample/typescript/src/app.ts new file mode 100644 index 00000000..acdff3b5 --- /dev/null +++ b/sample/typescript/src/app.ts @@ -0,0 +1,178 @@ +import dotenv from 'dotenv'; +import express from 'express'; +import path from 'path'; +import OAuthClient from 'intuit-oauth'; +import bodyParser from 'body-parser'; +import { AddressInfo } from 'net'; + +dotenv.config(); +const app = express(); +const ngrok = (process.env.NGROK_ENABLED==="true") ? require('ngrok'):null; + + +/** + * Configure View and Handlebars + */ +app.use(bodyParser.urlencoded({extended: true})); +app.use(express.static(path.join(__dirname, '../../public'))); +app.engine('html', require('ejs').renderFile); +app.set('view engine', 'html'); +app.use(bodyParser.json()) + +const urlencodedParser = bodyParser.urlencoded({ extended: false }); + +/** + * App Variables + * @type {null} + */ +let oauth2_token_json = null, + redirectUri = ''; + + +/** + * Instantiate new Client + * @type {OAuthClient} + */ + +let oauthClient = null; + + +/** + * Home Route + */ +app.get('/', function(req, res) { + + res.render('index'); +}); + +/** + * Get the AuthorizeUri + */ +app.get('/authUri', urlencodedParser, function(req,res) { + + oauthClient = new OAuthClient({ + clientId: req.query.json.clientId, + clientSecret: req.query.json.clientSecret, + environment: req.query.json.environment, + redirectUri: req.query.json.redirectUri + }); + + const authUri = oauthClient.authorizeUri({scope:[OAuthClient.scopes.Accounting],state:'intuit-test'}); + res.send(authUri); +}); + + +/** + * Handle the callback to extract the `Auth Code` and exchange them for `Bearer-Tokens` + */ +app.get('/callback', function(req, res) { + + oauthClient.createToken(req.url) + .then(function(authResponse) { + oauth2_token_json = JSON.stringify(authResponse.getJson(), null,2); + }) + .catch(function(e) { + console.error(e); + }); + + res.send(''); + +}); + +/** + * Display the token : CAUTION : JUST for sample purposes + */ +app.get('/retrieveToken', function(req, res) { + res.send(oauth2_token_json); +}); + + +/** + * Refresh the access-token + */ +app.get('/refreshAccessToken', function(req,res){ + + oauthClient.refresh() + .then(function(authResponse){ + console.log('The Refresh Token is '+ JSON.stringify(authResponse.getJson())); + oauth2_token_json = JSON.stringify(authResponse.getJson(), null,2); + res.send(oauth2_token_json); + }) + .catch(function(e) { + console.error(e); + }); + + +}); + +/** + * getCompanyInfo () + */ +app.get('/getCompanyInfo', function(req,res){ + + + const companyID = oauthClient.getToken().realmId; + + const url = oauthClient.environment == 'sandbox' ? OAuthClient.environment.sandbox : OAuthClient.environment.production ; + + oauthClient.makeApiCall({url: url + 'v3/company/' + companyID +'/companyinfo/' + companyID}) + .then(function(authResponse){ + console.log("The response for API call is :"+JSON.stringify(authResponse)); + res.send(JSON.parse(authResponse.text())); + }) + .catch(function(e) { + console.error(e); + }); +}); + +/** + * disconnect () + */ +app.get('/disconnect', function(req,res){ + + console.log('The disconnect called '); + const authUri = oauthClient.authorizeUri({scope:[OAuthClient.scopes.OpenId,OAuthClient.scopes.Email],state:'intuit-test'}); + res.redirect(authUri); + +}); + + + +/** + * Start server on HTTP (will use ngrok for HTTPS forwarding) + */ +const server = app.listen(process.env.PORT || 8000, () => { + const address = server.address() as AddressInfo; + console.log(`💻 Server listening on port ${address.port}`); +if(!ngrok){ + redirectUri = `${address.port}` + '/callback'; + console.log(`💳 Step 1 : Paste this URL in your browser : ` + 'http://localhost:' + `${address.port}`); + console.log('💳 Step 2 : Copy and Paste the clientId and clientSecret from : https://developer.intuit.com') + console.log(`💳 Step 3 : Copy Paste this callback URL into redirectURI :` + 'http://localhost:' + `${address.port}` + '/callback'); + console.log(`💻 Step 4 : Make Sure this redirect URI is also listed under the Redirect URIs on your app in : https://developer.intuit.com`); +} + +}); + +/** + * Optional : If NGROK is enabled + */ +if (ngrok) { + + console.log("NGROK Enabled"); + ngrok.connect({addr: process.env.PORT || 8000}, (err, url) => { + if (err) { + process.exit(1); + } + else { + redirectUri = url + '/callback'; + console.log(`💳 Step 1 : Paste this URL in your browser : ${url}`); + console.log('💳 Step 2 : Copy and Paste the clientId and clientSecret from : https://developer.intuit.com') + console.log(`💳 Step 3 : Copy Paste this callback URL into redirectURI : ${redirectUri}`); + console.log(`💻 Step 4 : Make Sure this redirect URI is also listed under the Redirect URIs on your app in : https://developer.intuit.com`); + + } + } + ); +} + diff --git a/sample/typescript/tsconfig.json b/sample/typescript/tsconfig.json new file mode 100644 index 00000000..e77f3714 --- /dev/null +++ b/sample/typescript/tsconfig.json @@ -0,0 +1,65 @@ +{ + "compilerOptions": { + /* Basic Options */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + // "lib": [], /* Specify library files to be included in the compilation. */ + "allowJs": true, /* Allow javascript files to be compiled. */ + "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + // "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + // "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "dist/", /* Redirect output structure to the directory. */ + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "incremental": true, /* Enable incremental compilation */ + // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */ + "strictNullChecks": false, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + }, + "include": [ + "src/" + ] +} diff --git a/src/OAuthClient.js b/src/OAuthClient.js index 011c251b..b7db8823 100644 --- a/src/OAuthClient.js +++ b/src/OAuthClient.js @@ -40,9 +40,10 @@ const Token = require('./access-token/Token'); /** * @constructor * @param {string} config.environment - * @param {string} config.appSecret - * @param {string} config.appKey - * @param {string} [config.cachePrefix] + * @param {string} config.clientId + * @param {string} config.clientSecret + * @param {string} [config.redirectUri] + * @param {bool} [config.logging] */ function OAuthClient(config) { this.environment = config.environment; diff --git a/test/OAuthClientTest.js b/test/OAuthClientTest.js index fec50f38..0696a8ec 100644 --- a/test/OAuthClientTest.js +++ b/test/OAuthClientTest.js @@ -322,6 +322,26 @@ describe('Tests for OAuthClient', () => { ); }); }); + it('Make API Call in Sandbox Environment with headers as parameters', () => { + 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', + headers: { + Accept: 'application/json', + }, + }) + .then((authResponse) => { + expect(JSON.stringify(authResponse.getJson())).to.be.equal( + JSON.stringify(expectedMakeAPICall), + ); + }); + }); it('loadResponseFromJWKsURI', () => { const request = { url: 'https://sandbox-quickbooks.api.intuit.com/v3/company/12345/companyinfo/12345', diff --git a/test/types.test.ts b/test/types.test.ts new file mode 100644 index 00000000..0710e5d3 --- /dev/null +++ b/test/types.test.ts @@ -0,0 +1,92 @@ +'use strict'; +import { expect } from 'chai'; +import * as OAuthClient from '../src/OAuthClient'; + +const AuthResponse = require('../src/response/AuthResponse'); + +describe('OAuthClient type validation tests', () => { + let oAuthClientConfig; + + beforeEach(() => { + oAuthClientConfig = { + clientId: 'clientId', + clientSecret: 'clientSecret', + environment: 'sandbox', + redirectUri: 'http://localhost:8000/callback' + }; + }); + + it('environment should have appropriate fields and types', () => { + const result = OAuthClient.environment; + expect(typeof result).to.equal('object'); + expect(result.sandbox).to.equal('https://sandbox-quickbooks.api.intuit.com/'); + expect(result.xyz).to.be.undefined; + }); + + it('scopes should have appropriate fields and types', () => { + const result = OAuthClient.scopes; + expect(typeof result).to.equal('object'); + expect(result.Accounting).to.equal('com.intuit.quickbooks.accounting'); + expect(typeof result.Accounting).to.equal('string'); + expect(result.accounting).to.be.undefined; + }); + + it('OAuthClientConfig should have appropriate fields and types', () => { + expect(typeof oAuthClientConfig.clientId).to.equal('string'); + expect(typeof oAuthClientConfig.clientSecret).to.equal('string'); + expect(typeof oAuthClientConfig.environment).to.equal('string'); + expect(typeof oAuthClientConfig.redirectUri).to.equal('string'); + }); + + it('Should create OAuthClient with appropriate fields and types for valid OAuthClientConfig', () => { + const oAuthClient = new OAuthClient({ + oAuthClientConfig + }); + expect(typeof oAuthClient).to.equal('object'); + expect(typeof oAuthClient.token).to.equal('object'); + expect(typeof oAuthClient.logging).to.equal('boolean'); + expect(typeof oAuthClient.logger).to.equal('object'); + expect(typeof oAuthClient.state).to.equal('object'); + }); + + it('should create new access token instance with appropriate fields and types for valid OAuthClient', () => { + const oAuthClient = new OAuthClient({ + oAuthClientConfig + }); + const accessToken = oAuthClient.getToken(); + expect(typeof accessToken).to.equal('object'); + expect(typeof accessToken.realmId).to.equal('string'); + expect(typeof accessToken.token_type).to.equal('string'); + expect(typeof accessToken.refresh_token).to.equal('string'); + expect(typeof accessToken.expires_in).to.equal('number'); + expect(typeof accessToken.x_refresh_token_expires_in).to.equal('number'); + expect(typeof accessToken.id_token).to.equal('string'); + expect(typeof accessToken.latency).to.equal('number'); + expect(typeof accessToken.createdAt).to.equal('number'); + }); + + it('should create new auth response instance with appropriate fields and types for valid accessToken', () => { + const oAuthClient = new OAuthClient({ + oAuthClientConfig + }); + const accessToken = oAuthClient.getToken(); + const authResponse = new AuthResponse({ token: accessToken }); + expect(typeof authResponse.token).to.equal('object'); + expect(typeof authResponse.response).to.equal('string'); + expect(typeof authResponse.body).to.equal('string'); + expect(typeof authResponse.json).to.equal('object'); + expect(typeof authResponse.intuit_tid).to.equal('string'); + }); + + it('Should create OAuthClientError with appropriate fields and types for empty authResponse', () => { + const oAuthClient = new OAuthClient({ + oAuthClientConfig + }); + const oAuthClientError = oAuthClient.createError(new Error(), null); + expect(typeof oAuthClientError.error).to.equal('string'); + expect(typeof oAuthClientError.authResponse).to.equal('string'); + expect(typeof oAuthClientError.intuit_tid).to.equal('string'); + expect(typeof oAuthClientError.originalMessage).to.equal('string'); + expect(typeof oAuthClientError.error_description).to.equal('string'); + }); +});