1
0
mirror of https://github.com/sasjs/adapter.git synced 2026-01-03 18:50:05 +00:00

Compare commits

...

26 Commits

Author SHA1 Message Date
Yury Shkoda
76bbb8acf2 chore(sasjsTests): debugging 2023-05-29 18:11:25 +03:00
Yury Shkoda
1ead483921 chore(sasjsTests): debugging 2023-05-29 18:00:57 +03:00
Yury Shkoda
e2cb787f89 chore(sasjs-tests): trying to run only sendArrTests 2023-05-29 17:40:40 +03:00
Yury Shkoda
828aef1873 chore(sasjs-tests): debugging 2023-05-29 17:33:01 +03:00
Yury Shkoda
f6ee1111c5 chore(cypress): debugging 2023-05-29 17:19:08 +03:00
Yury Shkoda
5f8750a8b6 chore(cypress): debugging 2023-05-29 16:54:21 +03:00
Yury Shkoda
d027acacb6 chore(cypress): debugging 2023-05-29 16:45:32 +03:00
Yury Shkoda
3660b9127a chore(sasjsTests): debugging 2023-05-29 16:39:31 +03:00
Yury Shkoda
5ac0f12435 chore(sasjsTests): debugging 2023-05-29 16:28:59 +03:00
Yury Shkoda
ee0c4b007b chore(sasjsTests): decreased defaultCommandTimeout for cypress 2023-05-29 15:41:15 +03:00
Yury Shkoda
db4a4e6d57 chore(sasjsTests): trying @sasjs/adapter@4.3.5 2023-05-29 15:23:38 +03:00
Yury Shkoda
eba30432dd chore(sasjsTests): debugging 2023-05-29 15:07:35 +03:00
Yury Shkoda
6b9cb3af5f chore(sasjsTests): added sleep step 2023-05-29 14:52:06 +03:00
Yury Shkoda
afe612925e chore(sasjsTests): debugging 2023-05-29 14:40:26 +03:00
Yury Shkoda
1f9bed0625 chore(sasjsTest): debugging 2023-05-29 14:27:49 +03:00
Yury Shkoda
51fdea46fc chore(sasjs-tests): debugging 2023-05-29 14:07:28 +03:00
Yury Shkoda
007b00565c chore(sasjsTests): removed pm2 log 2023-05-29 13:54:28 +03:00
Yury Shkoda
38eef00216 chore(sasjsTests): using different user 2023-05-29 13:46:53 +03:00
Yury Shkoda
f1c67432bf chore(sasjs-tests): debugging 2023-05-26 12:21:27 +03:00
Yury Shkoda
3041a0f4b1 chore(sasjs-tests): debugging 2023-05-26 12:07:42 +03:00
Yury Shkoda
6a5529f3f0 chore: debugging 2023-05-26 11:07:31 +03:00
Yury Shkoda
7758b78a88 chore: debugging sasjs 2023-05-26 10:11:02 +03:00
Yury Shkoda
09c1038cbd chore: debugging sasjs 2023-05-26 10:02:07 +03:00
Yury Shkoda
87e2449b6f chore: debugging sasjs 2023-05-26 09:52:37 +03:00
Yury Shkoda
c6b927c525 test: updated unit tests related to tokens operations 2023-05-25 10:35:10 +03:00
Yury Shkoda
4b6445d524 feat: improved error message for requests related to tokens operations 2023-05-25 10:27:54 +03:00
20 changed files with 394 additions and 107 deletions

View File

@@ -22,17 +22,17 @@ jobs:
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
cache: npm cache: npm
- name: Check npm audit # - name: Check npm audit
run: npm audit --production --audit-level=low # run: npm audit --production --audit-level=low
- name: Install Dependencies - name: Install Dependencies
run: npm ci run: npm ci
- name: Check code style # - name: Check code style
run: npm run lint # run: npm run lint
- name: Run unit tests # - name: Run unit tests
run: npm test # run: npm test
- name: Build Package - name: Build Package
run: npm run package:lib run: npm run package:lib
@@ -72,19 +72,27 @@ jobs:
npm install -g replace-in-files-cli npm install -g replace-in-files-cli
cd sasjs-tests cd sasjs-tests
replace-in-files --regex='"@sasjs/adapter".*' --replacement='"@sasjs/adapter":"latest",' ./package.json replace-in-files --regex='"@sasjs/adapter".*' --replacement='"@sasjs/adapter":"latest",' ./package.json
npm i npm i --legacy-peer-deps
replace-in-files --regex='"serverUrl".*' --replacement='"serverUrl":"${{ secrets.SASJS_SERVER_URL }}",' ./public/config.json replace-in-files --regex='"serverUrl".*' --replacement='"serverUrl":"${{ secrets.SASJS_SERVER_URL }}",' ./public/config.json
replace-in-files --regex='"userName".*' --replacement='"userName":"${{ secrets.SASJS_USERNAME }}",' ./public/config.json replace-in-files --regex='"userName".*' --replacement='"userName":"${{ secrets.SASJS_USERNAME_DEV }}",' ./public/config.json
replace-in-files --regex='"password".*' --replacement='"password":"${{ secrets.SASJS_PASSWORD }}",' ./public/config.json replace-in-files --regex='"password".*' --replacement='"password":"${{ secrets.SASJS_PASSWORD_DEV }}",' ./public/config.json
replace-in-files --regex='"serverType".*' --replacement='"serverType":"SASJS",' ./public/config.json replace-in-files --regex='"serverType".*' --replacement='"serverType":"SASJS",' ./public/config.json
npm run update:adapter # npm run update:adapter
pm2 start --name sasjs-test npm -- start pm2 start --name sasjs-test npm -- start
cat ./public/config.json
cat ../cypress.json
- name: Sleep for 10 seconds
uses: jakejarvis/wait-action@master
with:
time: '10s'
- name: Run cypress on sasjs - name: Run cypress on sasjs
run: | run: |
ss -lntu
replace-in-files --regex='"sasjsTestsUrl".*' --replacement='"sasjsTestsUrl":"http://localhost:3000",' ./cypress.json replace-in-files --regex='"sasjsTestsUrl".*' --replacement='"sasjsTestsUrl":"http://localhost:3000",' ./cypress.json
replace-in-files --regex='"username".*' --replacement='"username":"${{ secrets.SASJS_USERNAME }}",' ./cypress.json replace-in-files --regex='"username".*' --replacement='"username":"${{ secrets.SASJS_USERNAME_DEV }}",' ./cypress.json
replace-in-files --regex='"password".*' --replacement='"password":"${{ secrets.SASJS_PASSWORD }}",' ./cypress.json replace-in-files --regex='"password".*' --replacement='"password":"${{ secrets.SASJS_PASSWORD_DEV }}",' ./cypress.json
sh ./sasjs-tests/sasjs-cypress-run.sh ${{ secrets.MATRIX_TOKEN }} https://github.com/${{github.repository}}/actions/runs/${{github.run_id}} sh ./sasjs-tests/sasjs-cypress-run.sh ${{ secrets.MATRIX_TOKEN }} https://github.com/${{github.repository}}/actions/runs/${{github.run_id}}
# For some reason if coverage report action is run before other commands, those commands can't access the directories and files on which they depend on # For some reason if coverage report action is run before other commands, those commands can't access the directories and files on which they depend on

View File

@@ -5,6 +5,9 @@ const testingFinishTimeout = Cypress.env('testingFinishTimeout')
context('sasjs-tests', function () { context('sasjs-tests', function () {
this.beforeAll(() => { this.beforeAll(() => {
cy.task('log', 'beforeAll')
cy.task('log', `sasjsTestsUrl: ${sasjsTestsUrl}`)
cy.visit(sasjsTestsUrl) cy.visit(sasjsTestsUrl)
}) })
@@ -13,35 +16,66 @@ context('sasjs-tests', function () {
}) })
it('Should have all tests successfull', (done) => { it('Should have all tests successfull', (done) => {
cy.task('log', `Should have all tests successfull`)
cy.get('body').then(($body) => { cy.get('body').then(($body) => {
cy.task('log', `22`)
cy.wait(1000).then(() => { cy.wait(1000).then(() => {
const startButton = $body.find( const startButton = $body.find(
'.ui.massive.icon.primary.left.labeled.button' '.ui.massive.icon.primary.left.labeled.button'
)[0] )[0]
// ui massive icon primary left labeled button
cy.task('log', `startButton: ${startButton}`)
if ( if (
!startButton || !startButton ||
(startButton && !Cypress.dom.isVisible(startButton)) (startButton && !Cypress.dom.isVisible(startButton))
) { ) {
cy.task('log', `34`)
cy.task('log', `username: ${username}`)
cy.task('log', `password: ${password}`)
const userNameInput = cy.get('input[placeholder="User Name"]')
const passwordInput = cy.get('input[placeholder="Password"]')
cy.task('log', `userNameInput: ${userNameInput}`)
cy.task('log', `passwordInput: ${passwordInput}`)
cy.get('input[placeholder="User Name"]').type(username) cy.get('input[placeholder="User Name"]').type(username)
cy.get('input[placeholder="Password"]').type(password) cy.get('input[placeholder="Password"]').type(password)
const submitBtn = cy.get('.submit-button')
cy.task('log', `submitBtn: ${submitBtn}`)
cy.get('.submit-button').click() cy.get('.submit-button').click()
} }
cy.get('input[placeholder="User Name"]', { timeout: 40000 }) cy.get('input[placeholder="User Name"]', { timeout: 40000 })
.should('not.exist') .should('not.exist')
.then(() => { .then(() => {
cy.task('log', `46`)
cy.get('.ui.massive.icon.primary.left.labeled.button') cy.get('.ui.massive.icon.primary.left.labeled.button')
.click() .click()
.then(() => { .then(() => {
cy.task('log', `50`)
const loadingButton = $body.find(
'.ui.massive.loading.primary.button'
)[0]
cy.task('log', `loadingButton: ${loadingButton}`)
cy.get('.ui.massive.loading.primary.button', { cy.get('.ui.massive.loading.primary.button', {
timeout: testingFinishTimeout timeout: testingFinishTimeout
}) })
.should('not.exist') .should('not.exist')
.then(() => { .then(() => {
cy.task('log', `56`)
cy.get('span.icon.failed') cy.get('span.icon.failed')
.should('not.exist') .should('not.exist')
.then(() => { .then(() => {
cy.task('log', `60`)
done() done()
}) })
}) })
@@ -51,46 +85,46 @@ context('sasjs-tests', function () {
}) })
}) })
it('Should have all tests successfull with debug on', (done) => { // it('Should have all tests successfull with debug on', (done) => {
cy.get('body').then(($body) => { // cy.get('body').then(($body) => {
cy.wait(1000).then(() => { // cy.wait(1000).then(() => {
const startButton = $body.find( // const startButton = $body.find(
'.ui.massive.icon.primary.left.labeled.button' // '.ui.massive.icon.primary.left.labeled.button'
)[0] // )[0]
if ( // if (
!startButton || // !startButton ||
(startButton && !Cypress.dom.isVisible(startButton)) // (startButton && !Cypress.dom.isVisible(startButton))
) { // ) {
cy.get('input[placeholder="User Name"]').type(username) // cy.get('input[placeholder="User Name"]').type(username)
cy.get('input[placeholder="Password"]').type(password) // cy.get('input[placeholder="Password"]').type(password)
cy.get('.submit-button').click() // cy.get('.submit-button').click()
} // }
cy.get('.ui.fitted.toggle.checkbox label') // cy.get('.ui.fitted.toggle.checkbox label')
.click() // .click()
.then(() => { // .then(() => {
cy.get('input[placeholder="User Name"]', { timeout: 40000 }) // cy.get('input[placeholder="User Name"]', { timeout: 40000 })
.should('not.exist') // .should('not.exist')
.then(() => { // .then(() => {
cy.get('.ui.massive.icon.primary.left.labeled.button') // cy.get('.ui.massive.icon.primary.left.labeled.button')
.click() // .click()
.then(() => { // .then(() => {
cy.get('.ui.massive.loading.primary.button', { // cy.get('.ui.massive.loading.primary.button', {
timeout: testingFinishTimeout // timeout: testingFinishTimeout
}) // })
.should('not.exist') // .should('not.exist')
.then(() => { // .then(() => {
cy.get('span.icon.failed') // cy.get('span.icon.failed')
.should('not.exist') // .should('not.exist')
.then(() => { // .then(() => {
done() // done()
}) // })
}) // })
}) // })
}) // })
}) // })
}) // })
}) // })
}) // })
}) })

View File

@@ -39,4 +39,11 @@ module.exports = (on, config) => {
return launchOptions return launchOptions
} }
}) })
on('task', {
log(message) {
console.log(message)
return null
}
})
} }

View File

@@ -8,7 +8,7 @@
"name": "@sasjs/tests", "name": "@sasjs/tests",
"version": "1.0.0", "version": "1.0.0",
"dependencies": { "dependencies": {
"@sasjs/adapter": "file:../build/sasjs-adapter-5.0.0.tgz", "@sasjs/adapter": "4.3.5",
"@sasjs/test-framework": "1.5.7", "@sasjs/test-framework": "1.5.7",
"@types/jest": "^26.0.20", "@types/jest": "^26.0.20",
"@types/node": "^14.14.41", "@types/node": "^14.14.41",
@@ -3113,11 +3113,10 @@
"integrity": "sha512-WiBSI6JBIhC6LRIsB2Kwh8DsGTlbBU+mLRxJmAe3LjHTdkDpwIbEOZgoXBbZilk/vlfjK8i6nKRAvIRn1XaIMw==" "integrity": "sha512-WiBSI6JBIhC6LRIsB2Kwh8DsGTlbBU+mLRxJmAe3LjHTdkDpwIbEOZgoXBbZilk/vlfjK8i6nKRAvIRn1XaIMw=="
}, },
"node_modules/@sasjs/adapter": { "node_modules/@sasjs/adapter": {
"version": "5.0.0", "version": "4.3.5",
"resolved": "file:../build/sasjs-adapter-5.0.0.tgz", "resolved": "https://registry.npmjs.org/@sasjs/adapter/-/adapter-4.3.5.tgz",
"integrity": "sha512-BK+ZrvPeOqjCmHVLm3VtiQ/ATOTqjp+TibQixuG4DbljonBxZS/DnRZ0a1hOQUpCUZVKDRVtCNQ3ROtKUqxxrA==", "integrity": "sha512-ihVcmGQYPIZ3WTZOQd8xe/RDvtqK9lQmLx7hujmKeaN0RM/LsenYWIpM0nXKdw/2KruoghxMBNFLzpJUxJT4OA==",
"hasInstallScript": true, "hasInstallScript": true,
"license": "ISC",
"dependencies": { "dependencies": {
"@sasjs/utils": "2.52.0", "@sasjs/utils": "2.52.0",
"axios": "0.27.2", "axios": "0.27.2",
@@ -20165,8 +20164,9 @@
"integrity": "sha512-WiBSI6JBIhC6LRIsB2Kwh8DsGTlbBU+mLRxJmAe3LjHTdkDpwIbEOZgoXBbZilk/vlfjK8i6nKRAvIRn1XaIMw==" "integrity": "sha512-WiBSI6JBIhC6LRIsB2Kwh8DsGTlbBU+mLRxJmAe3LjHTdkDpwIbEOZgoXBbZilk/vlfjK8i6nKRAvIRn1XaIMw=="
}, },
"@sasjs/adapter": { "@sasjs/adapter": {
"version": "file:../build/sasjs-adapter-5.0.0.tgz", "version": "4.3.5",
"integrity": "sha512-BK+ZrvPeOqjCmHVLm3VtiQ/ATOTqjp+TibQixuG4DbljonBxZS/DnRZ0a1hOQUpCUZVKDRVtCNQ3ROtKUqxxrA==", "resolved": "https://registry.npmjs.org/@sasjs/adapter/-/adapter-4.3.5.tgz",
"integrity": "sha512-ihVcmGQYPIZ3WTZOQd8xe/RDvtqK9lQmLx7hujmKeaN0RM/LsenYWIpM0nXKdw/2KruoghxMBNFLzpJUxJT4OA==",
"requires": { "requires": {
"@sasjs/utils": "2.52.0", "@sasjs/utils": "2.52.0",
"axios": "0.27.2", "axios": "0.27.2",

View File

@@ -4,7 +4,7 @@
"homepage": ".", "homepage": ".",
"private": true, "private": true,
"dependencies": { "dependencies": {
"@sasjs/adapter": "file:../build/sasjs-adapter-5.0.0.tgz", "@sasjs/adapter": "4.3.5",
"@sasjs/test-framework": "1.5.7", "@sasjs/test-framework": "1.5.7",
"@types/jest": "^26.0.20", "@types/jest": "^26.0.20",
"@types/node": "^14.14.41", "@types/node": "^14.14.41",
@@ -45,4 +45,4 @@
"devDependencies": { "devDependencies": {
"node-sass": "7.0.3" "node-sass": "7.0.3"
} }
} }

View File

@@ -2,7 +2,7 @@
"userName": "", "userName": "",
"password": "", "password": "",
"sasJsConfig": { "sasJsConfig": {
"serverUrl": "", "serverUrl": "https://sas9.4gl.io",
"appLoc": "/Public/app/adapter-tests/services", "appLoc": "/Public/app/adapter-tests/services",
"serverType": "SASJS", "serverType": "SASJS",
"debug": false, "debug": false,

View File

@@ -1,7 +1,9 @@
{ {
"$schema": "https://cli.sasjs.io/sasjsconfig-schema.json", "$schema": "https://cli.sasjs.io/sasjsconfig-schema.json",
"serviceConfig": { "serviceConfig": {
"serviceFolders": ["sasjs/common"] "serviceFolders": [
"sasjs/common"
]
}, },
"defaultTarget": "4gl", "defaultTarget": "4gl",
"targets": [ "targets": [
@@ -26,4 +28,4 @@
} }
} }
] ]
} }

View File

@@ -11,7 +11,7 @@ const Login = (): ReactElement<{}> => {
const handleSubmit = useCallback( const handleSubmit = useCallback(
(e: any) => { (e: any) => {
e.preventDefault() e.preventDefault()
appContext.adapter.logIn(username, password).then((res) => { appContext.adapter.logIn(username, password).then((res: any) => {
appContext.setIsLoggedIn(res.isLoggedIn) appContext.setIsLoggedIn(res.isLoggedIn)
}) })
}, },

View File

@@ -1,5 +1,7 @@
import { prefixMessage } from '@sasjs/utils/error' import { prefixMessage } from '@sasjs/utils/error'
import { RequestClient } from '../request/RequestClient' import { RequestClient } from '../request/RequestClient'
import { getTokenRequestErrorPrefix } from './getTokenRequestErrorPrefix'
import { ServerType } from '@sasjs/utils'
/** /**
* Exchanges the auth code for an access token for the given client. * Exchanges the auth code for an access token for the given client.
@@ -31,6 +33,16 @@ export async function getAccessTokenForSasjs(
} }
}) })
.catch((err) => { .catch((err) => {
throw prefixMessage(err, 'Error while getting access token. ') throw prefixMessage(
err,
getTokenRequestErrorPrefix(
'fetching access token',
'getAccessTokenForSasjs',
ServerType.Sasjs,
url,
data,
clientId
)
)
}) })
} }

View File

@@ -1,11 +1,13 @@
import { SasAuthResponse } from '@sasjs/utils/types' import { SasAuthResponse, ServerType } from '@sasjs/utils/types'
import { prefixMessage } from '@sasjs/utils/error' import { prefixMessage } from '@sasjs/utils/error'
import { RequestClient } from '../request/RequestClient' import { RequestClient } from '../request/RequestClient'
import { CertificateError } from '../types/errors' import { CertificateError } from '../types/errors'
import { getTokenRequestErrorPrefix } from './getTokenRequestErrorPrefix'
// TODO: update func docs
/** /**
* Exchanges the auth code for an access token for the given client. * Exchange the auth code for access / refresh tokens for the given client / secret pair.
* @param requestClient - the pre-configured HTTP request client * @param requestClient - the pre-configured HTTP request client.
* @param clientId - the client ID to authenticate with. * @param clientId - the client ID to authenticate with.
* @param clientSecret - the client secret to authenticate with. * @param clientSecret - the client secret to authenticate with.
* @param authCode - the auth code received from the server. * @param authCode - the auth code received from the server.
@@ -16,29 +18,43 @@ export async function getAccessTokenForViya(
clientSecret: string, clientSecret: string,
authCode: string authCode: string
): Promise<SasAuthResponse> { ): Promise<SasAuthResponse> {
const url = '/SASLogon/oauth/token'
let token let token
if (typeof Buffer === 'undefined') { if (typeof Buffer === 'undefined') {
token = btoa(clientId + ':' + clientSecret) token = btoa(clientId + ':' + clientSecret)
} else { } else {
token = Buffer.from(clientId + ':' + clientSecret).toString('base64') token = Buffer.from(clientId + ':' + clientSecret).toString('base64')
} }
const url = '/SASLogon/oauth/token'
const headers = { const headers = {
Authorization: 'Basic ' + token, Authorization: 'Basic ' + token,
Accept: 'application/json' Accept: 'application/json'
} }
const dataJson = {
const data = new URLSearchParams({
grant_type: 'authorization_code', grant_type: 'authorization_code',
code: authCode code: authCode
}) }
const data = new URLSearchParams(dataJson)
const authResponse = await requestClient const authResponse = await requestClient
.post(url, data, undefined, 'application/x-www-form-urlencoded', headers) .post(url, data, undefined, 'application/x-www-form-urlencoded', headers)
.then((res) => res.result as SasAuthResponse) .then((res) => res.result as SasAuthResponse)
.catch((err) => { .catch((err) => {
if (err instanceof CertificateError) throw err if (err instanceof CertificateError) throw err
throw prefixMessage(err, 'Error while getting access token. ') throw prefixMessage(
err,
getTokenRequestErrorPrefix(
'fetching access token',
'getAccessTokenForViya',
ServerType.SasViya,
url,
dataJson,
headers,
clientId,
clientSecret
)
)
}) })
return authResponse return authResponse

View File

@@ -0,0 +1,88 @@
import { ServerType } from '@sasjs/utils/types'
type Server = ServerType.SasViya | ServerType.Sasjs
type Operation = 'fetching access token' | 'refreshing tokens'
const getServerName = (server: Server) =>
server === ServerType.SasViya ? 'Viya' : 'Sasjs'
const getResponseTitle = (server: Server) =>
`Response from ${getServerName(server)} is below.`
/**
* Forms error prefix for requests related to token operations.
* @param operation - string describing operation ('fetching access token' or 'refreshing tokens').
* @param funcName - name of the function sent the request.
* @param server - server type (SASVIYA or SASJS).
* @param url - endpoint used to send the request.
* @param data - request payload.
* @param headers - request headers.
* @param clientId - client ID to authenticate with.
* @param clientSecret - client secret to authenticate with.
* @returns - string containing request information. Example:
* Error while fetching access token from /SASLogon/oauth/token
* Thrown by the @sasjs/adapter getAccessTokenForViya function.
* Payload:
* {
* "grant_type": "authorization_code",
* "code": "example_code"
* }
* Headers:
* {
* "Authorization": "Basic NEdMQXBwOjRHTEFwcDE=",
* "Accept": "application/json"
* }
* ClientId: exampleClientId
* ClientSecret: exampleClientSecret
*
* Response from Viya is below.
* Auth error: {
* "error": "invalid_token",
* "error_description": "No scopes were granted"
* }
*/
export const getTokenRequestErrorPrefix = (
operation: Operation,
funcName: string,
server: Server,
url: string,
data?: {},
headers?: {},
clientId?: string,
clientSecret?: string
) => {
const stringify = (obj: {}) => JSON.stringify(obj, null, 2)
const lines = [
`Error while ${operation} from ${url}`,
`Thrown by the @sasjs/adapter ${funcName} function.`
]
if (data) {
lines.push('Payload:')
lines.push(stringify(data))
}
if (headers) {
lines.push('Headers:')
lines.push(stringify(headers))
}
if (clientId) lines.push(`ClientId: ${clientId}`)
if (clientSecret) lines.push(`ClientSecret: ${clientSecret}`)
lines.push('')
lines.push(`${getResponseTitle(server)}`)
lines.push('')
return lines.join(`\n`)
}
/**
* Parse error prefix to get response payload.
* @param prefix - error prefix generated by getTokenRequestErrorPrefix function.
* @param server - server type (SASVIYA or SASJS).
* @returns - response payload.
*/
export const getTokenRequestErrorPrefixResponse = (
prefix: string,
server: ServerType.SasViya | ServerType.Sasjs
) => prefix.split(`${getResponseTitle(server)}\n`).pop() as string

View File

@@ -22,6 +22,7 @@ export async function getTokens(
): Promise<AuthConfig> { ): Promise<AuthConfig> {
const logger = process.logger || console const logger = process.logger || console
let { access_token, refresh_token, client, secret } = authConfig let { access_token, refresh_token, client, secret } = authConfig
if ( if (
isAccessTokenExpiring(access_token) || isAccessTokenExpiring(access_token) ||
isRefreshTokenExpiring(refresh_token) isRefreshTokenExpiring(refresh_token)
@@ -29,6 +30,7 @@ export async function getTokens(
if (hasTokenExpired(refresh_token)) { if (hasTokenExpired(refresh_token)) {
const error = const error =
'Unable to obtain new access token. Your refresh token has expired.' 'Unable to obtain new access token. Your refresh token has expired.'
logger.error(error) logger.error(error)
throw new Error(error) throw new Error(error)
@@ -47,5 +49,6 @@ export async function getTokens(
: await refreshTokensForSasjs(requestClient, refresh_token) : await refreshTokensForSasjs(requestClient, refresh_token)
;({ access_token, refresh_token } = tokens) ;({ access_token, refresh_token } = tokens)
} }
return { access_token, refresh_token, client, secret } return { access_token, refresh_token, client, secret }
} }

View File

@@ -1,5 +1,7 @@
import { prefixMessage } from '@sasjs/utils/error' import { prefixMessage } from '@sasjs/utils/error'
import { RequestClient } from '../request/RequestClient' import { RequestClient } from '../request/RequestClient'
import { getTokenRequestErrorPrefix } from './getTokenRequestErrorPrefix'
import { ServerType } from '@sasjs/utils'
/** /**
* Exchanges the refresh token for an access token for the given client. * Exchanges the refresh token for an access token for the given client.
@@ -28,7 +30,15 @@ export async function refreshTokensForSasjs(
} }
}) })
.catch((err) => { .catch((err) => {
throw prefixMessage(err, 'Error while refreshing tokens: ') throw prefixMessage(
err,
getTokenRequestErrorPrefix(
'refreshing tokens',
'refreshTokensForSasjs',
ServerType.Sasjs,
url
)
)
}) })
return authResponse return authResponse

View File

@@ -1,8 +1,9 @@
import { SasAuthResponse } from '@sasjs/utils/types' import { SasAuthResponse, ServerType } from '@sasjs/utils/types'
import { prefixMessage } from '@sasjs/utils/error' import { prefixMessage } from '@sasjs/utils/error'
import * as NodeFormData from 'form-data' import * as NodeFormData from 'form-data'
import { RequestClient } from '../request/RequestClient' import { RequestClient } from '../request/RequestClient'
import { isNode } from '../utils' import { isNode } from '../utils'
import { getTokenRequestErrorPrefix } from './getTokenRequestErrorPrefix'
/** /**
* Exchanges the refresh token for an access token for the given client. * Exchanges the refresh token for an access token for the given client.
@@ -46,7 +47,19 @@ export async function refreshTokensForViya(
) )
.then((res) => res.result) .then((res) => res.result)
.catch((err) => { .catch((err) => {
throw prefixMessage(err, 'Error while refreshing tokens: ') throw prefixMessage(
err,
getTokenRequestErrorPrefix(
'refreshing tokens',
'refreshTokensForViya',
ServerType.SasViya,
url,
formData,
headers,
clientId,
clientSecret
)
)
}) })
return authResponse return authResponse

View File

@@ -55,7 +55,7 @@ describe('getAccessTokenForSasjs', () => {
authConfig.refresh_token authConfig.refresh_token
).catch((e: any) => e) ).catch((e: any) => e)
expect(error).toContain('Error while getting access token') expect(error).toContain('Error while fetching access token')
}) })
}) })

View File

@@ -66,7 +66,7 @@ describe('getAccessTokenForViya', () => {
authConfig.refresh_token authConfig.refresh_token
).catch((e: any) => e) ).catch((e: any) => e)
expect(error).toContain('Error while getting access token') expect(error).toContain('Error while fetching access token')
}) })
}) })

View File

@@ -0,0 +1,81 @@
import { ServerType } from '@sasjs/utils/types'
import { getTokenRequestErrorPrefix } from '../getTokenRequestErrorPrefix'
describe('getTokenRequestErrorPrefix', () => {
it('should return error prefix', () => {
// INFO: Viya with only required attributes
let operation: 'fetching access token' = 'fetching access token'
const funcName = 'testFunc'
const url = '/SASjsApi/auth/token'
let expectedPrefix = `Error while ${operation} from ${url}
Thrown by the @sasjs/adapter ${funcName} function.
Response from Viya is below.
`
expect(
getTokenRequestErrorPrefix(operation, funcName, ServerType.SasViya, url)
).toEqual(expectedPrefix)
// INFO: Sasjs with data and headers
const data = {
grant_type: 'authorization_code',
code: 'testCode'
}
const headers = {
Authorization: 'Basic test=',
Accept: 'application/json'
}
expectedPrefix = `Error while ${operation} from ${url}
Thrown by the @sasjs/adapter ${funcName} function.
Payload:
${JSON.stringify(data, null, 2)}
Headers:
${JSON.stringify(headers, null, 2)}
Response from Sasjs is below.
`
expect(
getTokenRequestErrorPrefix(
operation,
funcName,
ServerType.Sasjs,
url,
data,
headers
)
).toEqual(expectedPrefix)
// INFO: Viya with all attributes
const clientId = 'testId'
const clientSecret = 'testSecret'
expectedPrefix = `Error while ${operation} from ${url}
Thrown by the @sasjs/adapter ${funcName} function.
Payload:
${JSON.stringify(data, null, 2)}
Headers:
${JSON.stringify(headers, null, 2)}
ClientId: ${clientId}
ClientSecret: ${clientSecret}
Response from Viya is below.
`
expect(
getTokenRequestErrorPrefix(
operation,
funcName,
ServerType.SasViya,
url,
data,
headers,
clientId,
clientSecret
)
).toEqual(expectedPrefix)
})
})

View File

@@ -1,6 +1,8 @@
import { ServerType } from '@sasjs/utils'
import { generateToken, mockAuthResponse } from './mockResponses' import { generateToken, mockAuthResponse } from './mockResponses'
import { RequestClient } from '../../request/RequestClient' import { RequestClient } from '../../request/RequestClient'
import { refreshTokensForSasjs } from '../refreshTokensForSasjs' import { refreshTokensForSasjs } from '../refreshTokensForSasjs'
import { getTokenRequestErrorPrefixResponse } from '../getTokenRequestErrorPrefix'
const requestClient = new (<jest.Mock<RequestClient>>RequestClient)() const requestClient = new (<jest.Mock<RequestClient>>RequestClient)()
@@ -38,9 +40,9 @@ describe('refreshTokensForSasjs', () => {
const error = await refreshTokensForSasjs( const error = await refreshTokensForSasjs(
requestClient, requestClient,
refresh_token refresh_token
).catch((e: any) => e) ).catch((e: any) => getTokenRequestErrorPrefixResponse(e, ServerType.Sasjs))
expect(error).toEqual(`Error while refreshing tokens: ${tokenError}`) expect(error).toEqual(tokenError)
}) })
}) })

View File

@@ -1,9 +1,10 @@
import { AuthConfig } from '@sasjs/utils' import { AuthConfig, ServerType } from '@sasjs/utils'
import * as NodeFormData from 'form-data' import * as NodeFormData from 'form-data'
import { generateToken, mockAuthResponse } from './mockResponses' import { generateToken, mockAuthResponse } from './mockResponses'
import { RequestClient } from '../../request/RequestClient' import { RequestClient } from '../../request/RequestClient'
import { refreshTokensForViya } from '../refreshTokensForViya' import { refreshTokensForViya } from '../refreshTokensForViya'
import * as IsNodeModule from '../../utils/isNode' import * as IsNodeModule from '../../utils/isNode'
import { getTokenRequestErrorPrefixResponse } from '../getTokenRequestErrorPrefix'
const requestClient = new (<jest.Mock<RequestClient>>RequestClient)() const requestClient = new (<jest.Mock<RequestClient>>RequestClient)()
@@ -67,9 +68,11 @@ describe('refreshTokensForViya', () => {
authConfig.client, authConfig.client,
authConfig.secret, authConfig.secret,
authConfig.refresh_token authConfig.refresh_token
).catch((e: any) => e) ).catch((e: any) =>
getTokenRequestErrorPrefixResponse(e, ServerType.SasViya)
)
expect(error).toEqual(`Error while refreshing tokens: ${tokenError}`) expect(error).toEqual(tokenError)
}) })
it('should throw an error if environment is not Node', async () => { it('should throw an error if environment is not Node', async () => {

View File

@@ -11,8 +11,8 @@ import {
NotFoundError, NotFoundError,
InternalServerError InternalServerError
} from '../types/errors' } from '../types/errors'
import { prefixMessage } from '@sasjs/utils/error'
import { RequestClient } from '../request/RequestClient' import { RequestClient } from '../request/RequestClient'
import { getTokenRequestErrorPrefixResponse } from '../auth/getTokenRequestErrorPrefix'
const axiosActual = jest.requireActual('axios') const axiosActual = jest.requireActual('axios')
@@ -66,14 +66,18 @@ describe('RequestClient', () => {
}) })
it('should response the POST method with Unauthorized', async () => { it('should response the POST method with Unauthorized', async () => {
await expect( const expectedError = new LoginRequiredError({
adapter.getAccessToken('clientId', 'clientSecret', 'incorrect') error: 'unauthorized',
).rejects.toEqual( error_description: 'Bad credentials'
prefixMessage( })
new LoginRequiredError(incorrectAuthCodeErr),
'Error while getting access token. ' const rejectionErrorMessage = await adapter
.getAccessToken('clientId', 'clientSecret', 'incorrect')
.catch((err) =>
getTokenRequestErrorPrefixResponse(err.message, ServerType.SasViya)
) )
)
expect(rejectionErrorMessage).toEqual(expectedError.message)
}) })
describe('handleError', () => { describe('handleError', () => {
@@ -209,15 +213,15 @@ describe('RequestClient - Self Signed Server', () => {
serverType: ServerType.SasViya serverType: ServerType.SasViya
}) })
await expect( const expectedError = 'self signed certificate'
adapterWithoutCertificate.getAccessToken(
'clientId', const rejectionErrorMessage = await adapterWithoutCertificate
'clientSecret', .getAccessToken('clientId', 'clientSecret', 'authCode')
'authCode' .catch((err) =>
getTokenRequestErrorPrefixResponse(err.message, ServerType.SasViya)
) )
).rejects.toThrow(
`Error while getting access token. ${ERROR_MESSAGES.selfSigned}` expect(rejectionErrorMessage).toEqual(expectedError)
)
}) })
it('should response the POST method using insecure flag', async () => { it('should response the POST method using insecure flag', async () => {
@@ -247,14 +251,18 @@ describe('RequestClient - Self Signed Server', () => {
}) })
it('should response the POST method with Unauthorized', async () => { it('should response the POST method with Unauthorized', async () => {
await expect( const expectedError = new LoginRequiredError({
adapter.getAccessToken('clientId', 'clientSecret', 'incorrect') error: 'unauthorized',
).rejects.toEqual( error_description: 'Bad credentials'
prefixMessage( })
new LoginRequiredError(incorrectAuthCodeErr),
'Error while getting access token. ' const rejectionErrorMessage = await adapter
.getAccessToken('clientId', 'clientSecret', 'incorrect')
.catch((err) =>
getTokenRequestErrorPrefixResponse(err.message, ServerType.SasViya)
) )
)
expect(rejectionErrorMessage).toEqual(expectedError.message)
}) })
}) })