Skip to content

Implement useAuthEmulator and remove auth.useEmulator. #4414

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Feb 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions common/api-review/auth-exp.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,11 @@ export function updatePhoneNumber(user: externs.User, credential: externs.PhoneA
// @public
export function updateProfile(user: externs.User, { displayName, photoURL: photoUrl }: Profile): Promise<void>;

// @public
export function useAuthEmulator(auth: externs.Auth, url: string, options?: {
disableWarnings: boolean;
}): void;

// @public
export function useDeviceLanguage(auth: externs.Auth): void;

Expand Down
2 changes: 1 addition & 1 deletion packages-exp/auth-compat-exp/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export class Auth
return this.auth.signOut();
}
useEmulator(url: string, options?: { disableWarnings: boolean }): void {
this.auth.useEmulator(url, options);
impl.useAuthEmulator(this.auth, url, options);
}
applyActionCode(code: string): Promise<void> {
return impl.applyActionCode(this.auth, code);
Expand Down
130 changes: 2 additions & 128 deletions packages-exp/auth-exp/src/core/auth/auth_impl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,15 @@ import * as sinonChai from 'sinon-chai';
import { FirebaseApp } from '@firebase/app-types-exp';
import { FirebaseError } from '@firebase/util';

import { endpointUrl, mockEndpoint } from '../../../test/helpers/api/helper';
import { testAuth, TestAuth, testUser } from '../../../test/helpers/mock_auth';
import * as fetch from '../../../test/helpers/mock_fetch';
import { Endpoint } from '../../api';
import { testAuth, testUser } from '../../../test/helpers/mock_auth';
import { Auth } from '../../model/auth';
import { User } from '../../model/user';
import { Persistence } from '../persistence';
import { inMemoryPersistence } from '../persistence/in_memory';
import { _getInstance } from '../util/instantiator';
import * as navigator from '../util/navigator';
import * as reload from '../user/reload';
import { _castAuth, AuthImpl, DefaultConfig } from './auth_impl';
import { AuthImpl, DefaultConfig } from './auth_impl';
import { _initializeAuthInstance } from './initialize';

use(sinonChai);
Expand Down Expand Up @@ -461,126 +458,3 @@ describe('core/auth/auth_impl', () => {
});
});
});

// These tests are separate because they are using a different auth with
// separate setup and config
describe('core/auth/auth_impl useEmulator', () => {
let auth: TestAuth;
let user: User;
let normalEndpoint: fetch.Route;
let emulatorEndpoint: fetch.Route;

beforeEach(async () => {
auth = await testAuth();
user = testUser(_castAuth(auth), 'uid', 'email', true);
fetch.setUp();
normalEndpoint = mockEndpoint(Endpoint.DELETE_ACCOUNT, {});
emulatorEndpoint = fetch.mock(
`http://localhost:2020/${endpointUrl(Endpoint.DELETE_ACCOUNT).replace(
/^.*:\/\//,
''
)}`,
{}
);
});

afterEach(() => {
fetch.tearDown();
sinon.restore();

// The DOM persists through tests; remove the banner if it is attached
const banner =
typeof document !== 'undefined'
? document.querySelector('.firebase-emulator-warning')
: null;
if (banner) {
banner.parentElement?.removeChild(banner);
}
});

context('useEmulator', () => {
it('fails if a network request has already been made', async () => {
await user.delete();
expect(() => auth.useEmulator('http://localhost:2020')).to.throw(
FirebaseError,
'auth/emulator-config-failed'
);
});

it('updates the endpoint appropriately', async () => {
auth.useEmulator('http://localhost:2020');
await user.delete();
expect(normalEndpoint.calls.length).to.eq(0);
expect(emulatorEndpoint.calls.length).to.eq(1);
});

it('checks the scheme properly', () => {
expect(() => auth.useEmulator('http://localhost:2020')).not.to.throw;
delete auth.config.emulator;
expect(() => auth.useEmulator('https://localhost:2020')).not.to.throw;
delete auth.config.emulator;
expect(() => auth.useEmulator('ssh://localhost:2020')).to.throw(
FirebaseError,
'auth/invalid-emulator-scheme'
);
delete auth.config.emulator;
expect(() => auth.useEmulator('localhost:2020')).to.throw(
FirebaseError,
'auth/invalid-emulator-scheme'
);
});

it('attaches a banner to the DOM', () => {
auth.useEmulator('http://localhost:2020');
if (typeof document !== 'undefined') {
const el = document.querySelector('.firebase-emulator-warning')!;
expect(el).not.to.be.null;
expect(el.textContent).to.eq(
'Running in emulator mode. ' +
'Do not use with production credentials.'
);
}
});

it('logs out a warning to the console', () => {
sinon.stub(console, 'info');
auth.useEmulator('http://localhost:2020');
expect(console.info).to.have.been.calledWith(
'WARNING: You are using the Auth Emulator,' +
' which is intended for local testing only. Do not use with' +
' production credentials.'
);
});

it('logs out the warning but has no banner if disableBanner true', () => {
sinon.stub(console, 'info');
auth.useEmulator('http://localhost:2020', { disableWarnings: true });
expect(console.info).to.have.been.calledWith(
'WARNING: You are using the Auth Emulator,' +
' which is intended for local testing only. Do not use with' +
' production credentials.'
);
if (typeof document !== 'undefined') {
expect(document.querySelector('.firebase-emulator-warning')).to.be.null;
}
});
});

context('toJSON', () => {
it('works when theres no current user', () => {
expect(JSON.stringify(auth)).to.eq(
'{"apiKey":"test-api-key","authDomain":"localhost","appName":"test-app"}'
);
});

it('also stringifies the current user', () => {
auth.currentUser = ({
toJSON: (): object => ({ foo: 'bar' })
} as unknown) as User;
expect(JSON.stringify(auth)).to.eq(
'{"apiKey":"test-api-key","authDomain":"localhost",' +
'"appName":"test-app","currentUser":{"foo":"bar"}}'
);
});
});
});
54 changes: 0 additions & 54 deletions packages-exp/auth-exp/src/core/auth/auth_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,20 +272,6 @@ export class AuthImpl implements Auth, _FirebaseService {
this.languageCode = _getUserLanguage();
}

useEmulator(url: string, options?: { disableWarnings: boolean }): void {
_assert(this._canInitEmulator, this, AuthErrorCode.EMULATOR_CONFIG_FAILED);

_assert(
/^https?:\/\//.test(url),
this,
AuthErrorCode.INVALID_EMULATOR_SCHEME
);

this.config.emulator = { url };
this.settings.appVerificationDisabledForTesting = true;
emitEmulatorWarning(!!options?.disableWarnings);
}

async _delete(): Promise<void> {
this._deleted = true;
}
Expand Down Expand Up @@ -570,43 +556,3 @@ class Subscription<T> {
return this.observer.next.bind(this.observer);
}
}

function emitEmulatorWarning(disableBanner: boolean): void {
function attachBanner(): void {
const el = document.createElement('p');
const sty = el.style;
el.innerText =
'Running in emulator mode. Do not use with production credentials.';
sty.position = 'fixed';
sty.width = '100%';
sty.backgroundColor = '#ffffff';
sty.border = '.1em solid #000000';
sty.color = '#ff0000';
sty.bottom = '0px';
sty.left = '0px';
sty.margin = '0px';
sty.zIndex = '10000';
sty.textAlign = 'center';
el.classList.add('firebase-emulator-warning');
document.body.appendChild(el);
}

if (typeof console !== 'undefined' && typeof console.info === 'function') {
console.info(
'WARNING: You are using the Auth Emulator,' +
' which is intended for local testing only. Do not use with' +
' production credentials.'
);
}
if (
typeof window !== 'undefined' &&
typeof document !== 'undefined' &&
!disableBanner
) {
if (document.readyState === 'loading') {
window.addEventListener('DOMContentLoaded', attachBanner);
} else {
attachBanner();
}
}
}
156 changes: 156 additions & 0 deletions packages-exp/auth-exp/src/core/auth/emulator.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { expect, use } from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as sinon from 'sinon';
import * as sinonChai from 'sinon-chai';

import { FirebaseError } from '@firebase/util';

import { endpointUrl, mockEndpoint } from '../../../test/helpers/api/helper';
import { testAuth, TestAuth, testUser } from '../../../test/helpers/mock_auth';
import * as fetch from '../../../test/helpers/mock_fetch';
import { Endpoint } from '../../api';
import { User } from '../../model/user';
import { _castAuth } from './auth_impl';
import { useAuthEmulator } from './emulator';

use(sinonChai);
use(chaiAsPromised);

describe('core/auth/emulator', () => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All tests moved from auth_impl.ts. No changes except API.

let auth: TestAuth;
let user: User;
let normalEndpoint: fetch.Route;
let emulatorEndpoint: fetch.Route;

beforeEach(async () => {
auth = await testAuth();
user = testUser(_castAuth(auth), 'uid', 'email', true);
fetch.setUp();
normalEndpoint = mockEndpoint(Endpoint.DELETE_ACCOUNT, {});
emulatorEndpoint = fetch.mock(
`http://localhost:2020/${endpointUrl(Endpoint.DELETE_ACCOUNT).replace(
/^.*:\/\//,
''
)}`,
{}
);
});

afterEach(() => {
fetch.tearDown();
sinon.restore();

// The DOM persists through tests; remove the banner if it is attached
const banner =
typeof document !== 'undefined'
? document.querySelector('.firebase-emulator-warning')
: null;
if (banner) {
banner.parentElement?.removeChild(banner);
}
});

context('useAuthEmulator', () => {
it('fails if a network request has already been made', async () => {
await user.delete();
expect(() => useAuthEmulator(auth, 'http://localhost:2020')).to.throw(
FirebaseError,
'auth/emulator-config-failed'
);
});

it('updates the endpoint appropriately', async () => {
useAuthEmulator(auth, 'http://localhost:2020');
await user.delete();
expect(normalEndpoint.calls.length).to.eq(0);
expect(emulatorEndpoint.calls.length).to.eq(1);
});

it('checks the scheme properly', () => {
expect(() => useAuthEmulator(auth, 'http://localhost:2020')).not.to.throw;
delete auth.config.emulator;
expect(() => useAuthEmulator(auth, 'https://localhost:2020')).not.to
.throw;
delete auth.config.emulator;
expect(() => useAuthEmulator(auth, 'ssh://localhost:2020')).to.throw(
FirebaseError,
'auth/invalid-emulator-scheme'
);
delete auth.config.emulator;
expect(() => useAuthEmulator(auth, 'localhost:2020')).to.throw(
FirebaseError,
'auth/invalid-emulator-scheme'
);
});

it('attaches a banner to the DOM', () => {
useAuthEmulator(auth, 'http://localhost:2020');
if (typeof document !== 'undefined') {
const el = document.querySelector('.firebase-emulator-warning')!;
expect(el).not.to.be.null;
expect(el.textContent).to.eq(
'Running in emulator mode. ' +
'Do not use with production credentials.'
);
}
});

it('logs out a warning to the console', () => {
sinon.stub(console, 'info');
useAuthEmulator(auth, 'http://localhost:2020');
expect(console.info).to.have.been.calledWith(
'WARNING: You are using the Auth Emulator,' +
' which is intended for local testing only. Do not use with' +
' production credentials.'
);
});

it('logs out the warning but has no banner if disableBanner true', () => {
sinon.stub(console, 'info');
useAuthEmulator(auth, 'http://localhost:2020', { disableWarnings: true });
expect(console.info).to.have.been.calledWith(
'WARNING: You are using the Auth Emulator,' +
' which is intended for local testing only. Do not use with' +
' production credentials.'
);
if (typeof document !== 'undefined') {
expect(document.querySelector('.firebase-emulator-warning')).to.be.null;
}
});
});

context('toJSON', () => {
it('works when theres no current user', () => {
expect(JSON.stringify(auth)).to.eq(
'{"apiKey":"test-api-key","authDomain":"localhost","appName":"test-app"}'
);
});

it('also stringifies the current user', () => {
auth.currentUser = ({
toJSON: (): object => ({ foo: 'bar' })
} as unknown) as User;
expect(JSON.stringify(auth)).to.eq(
'{"apiKey":"test-api-key","authDomain":"localhost",' +
'"appName":"test-app","currentUser":{"foo":"bar"}}'
);
});
});
});
Loading