diff --git a/src/auth/base-auth-api.ts b/src/auth/base-auth-api.ts index 6aa8ed442..1b1efca17 100644 --- a/src/auth/base-auth-api.ts +++ b/src/auth/base-auth-api.ts @@ -33,6 +33,22 @@ export class AuthApiError extends Error { } } +function parseErrorBody(body: any): AuthApiErrorResponse { + const rawData = JSON.parse(body); + let data: AuthApiErrorResponse; + + if (rawData.error) { + data = rawData as AuthApiErrorResponse; + } else { + data = { + error: rawData.code, + error_description: rawData.description, + }; + } + + return data; +} + async function parseError(response: Response) { // Errors typically have a specific format: // { @@ -41,10 +57,10 @@ async function parseError(response: Response) { // } const body = await response.text(); - let data: AuthApiErrorResponse; try { - data = JSON.parse(body) as AuthApiErrorResponse; + const data = parseErrorBody(body); + return new AuthApiError( data.error, data.error_description, diff --git a/test/auth/database.test.ts b/test/auth/database.test.ts index 4ace37173..43e086382 100644 --- a/test/auth/database.test.ts +++ b/test/auth/database.test.ts @@ -1,10 +1,12 @@ import nock from 'nock'; import { beforeAll, afterAll } from '@jest/globals'; import { Database } from '../../src/auth/database'; +import { AuthApiError } from '../../src/auth/base-auth-api'; const { back: nockBack } = nock; const EMAIL = 'test-email@example.com'; +const DUPLICATE_EMAIL = 'test-email-duplicate@example.com'; const PASSWORD = 'test-password'; const opts = { @@ -48,6 +50,30 @@ describe('Database', () => { } as any) ).rejects.toThrow('Required parameter requestParameters.connection was null or undefined.'); }); + + it('should handle duplicate user error', async () => { + const database = new Database(opts); + const email = DUPLICATE_EMAIL; + let error: AuthApiError | null = null; + + try { + await database.signUp({ + email, + password: PASSWORD, + connection: 'Username-Password-Authentication', + }); + } catch (e) { + error = e as AuthApiError; + } + + expect(error).toBeDefined(); + expect(error).toEqual( + expect.objectContaining({ + error: 'invalid_signup', + error_description: 'Invalid sign up', + }) + ); + }); }); describe('#changePassword', () => { diff --git a/test/auth/fixtures/database.json b/test/auth/fixtures/database.json index 2aec9f201..c97c28b37 100644 --- a/test/auth/fixtures/database.json +++ b/test/auth/fixtures/database.json @@ -33,6 +33,23 @@ "email": "test-email@example.com" } }, + { + "scope": "https://test-domain.auth0.com", + "method": "POST", + "path": "/dbconnections/signup", + "body": { + "client_id": "test-client-id", + "email": "test-email-duplicate@example.com", + "password": "test-password", + "connection": "Username-Password-Authentication" + }, + "status": 400, + "response": { + "name": "BadRequestError", + "code": "invalid_signup", + "description": "Invalid sign up" + } + }, { "scope": "https://test-domain.auth0.com", "method": "POST",