diff --git a/packages/ember-simple-auth/src/authenticators/oauth2-password-grant.ts b/packages/ember-simple-auth/src/authenticators/oauth2-password-grant.ts index 5edb787b9..1a67bb2b5 100644 --- a/packages/ember-simple-auth/src/authenticators/oauth2-password-grant.ts +++ b/packages/ember-simple-auth/src/authenticators/oauth2-password-grant.ts @@ -374,7 +374,7 @@ export default class OAuth2PasswordGrantAuthenticator extends BaseAuthenticator @protected */ @waitFor - makeRequest( + async makeRequest( url: string, data: MakeRequestData, headers: Record = {} @@ -405,26 +405,21 @@ export default class OAuth2PasswordGrantAuthenticator extends BaseAuthenticator method: 'POST', }; - return new Promise((resolve, reject) => { - fetch(url, options) - .then(response => { - response.text().then(text => { - try { - let json = JSON.parse(text); - if (!response.ok) { - (response as OAuth2Response).responseJSON = json; - reject(response); - } else { - resolve(json); - } - } catch (SyntaxError) { - (response as OAuth2Response).responseText = text; - reject(response); - } - }); - }) - .catch(reject); - }); + const response = await fetch(url, options); + const text = await response.text(); + const cloned = response.clone() as OAuth2Response; + try { + const json = JSON.parse(text); + if (response.ok) { + return json; + } else { + cloned.responseJSON = json; + throw cloned; + } + } catch (SyntaxError) { + cloned.responseText = text; + throw cloned; + } } _scheduleAccessTokenRefresh( diff --git a/packages/test-esa/tests/unit/authenticators/oauth2-password-grant-test.js b/packages/test-esa/tests/unit/authenticators/oauth2-password-grant-test.js index 924f67ef1..8853ccd45 100644 --- a/packages/test-esa/tests/unit/authenticators/oauth2-password-grant-test.js +++ b/packages/test-esa/tests/unit/authenticators/oauth2-password-grant-test.js @@ -318,6 +318,17 @@ module('OAuth2PasswordGrantAuthenticator', function (hooks) { } }); + test('rejects with original/cloned response', async function (assert) { + assert.expect(1); + try { + await authenticator.authenticate('username', 'password'); + assert.ok(false, "Mustn't reach here. Test failed."); + } catch (response) { + const json = await response.json(); + assert.deepEqual(json, { error: 'invalid_grant' }); + } + }); + test('provides access to custom headers', async function (assert) { assert.expect(1); try { @@ -348,6 +359,16 @@ module('OAuth2PasswordGrantAuthenticator', function (hooks) { assert.equal(error.responseText, 'The server has failed completely.'); } }); + test('rejects with response object containing responseText', async function (assert) { + assert.expect(1); + try { + await authenticator.authenticate('username', 'password'); + assert.ok(false, "Test failed. Mustn't reach here."); + } catch (response) { + const text = await response.text(); + assert.equal(text, 'The server has failed completely.'); + } + }); test('provides access to custom headers', async function (assert) { assert.expect(1);