Skip to content

Add hooks into auth-next for emulator config #3716

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 5 commits into from
Sep 1, 2020
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
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ describe('requestStsToken', () => {
beforeEach(async () => {
auth = await testAuth();
const { apiKey, tokenApiHost, apiScheme } = auth.config;
endpoint = `${apiScheme}://${tokenApiHost}/${_ENDPOINT}?key=${apiKey}`;
endpoint = `${apiScheme}://${tokenApiHost}${_ENDPOINT}?key=${apiKey}`;
fetch.setUp();
});

Expand Down
16 changes: 10 additions & 6 deletions packages-exp/auth-exp/src/api/authentication/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,15 @@

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

import { _performFetchWithErrorHandling, HttpMethod } from '../';
import { AuthCore } from '../../model/auth';
import {
_getFinalTarget,
_performFetchWithErrorHandling,
HttpMethod
} from '../';
import { FetchProvider } from '../../core/util/fetch_provider';
import { AuthCore } from '../../model/auth';

export const _ENDPOINT = 'v1/token';
export const _ENDPOINT = '/v1/token';
const GRANT_TYPE = 'refresh_token';

/** The server responses with snake_case; we convert to camelCase */
Expand All @@ -50,10 +54,10 @@ export async function requestStsToken(
'grant_type': GRANT_TYPE,
'refresh_token': refreshToken
}).slice(1);
const { apiScheme, tokenApiHost, apiKey, sdkClientVersion } = auth.config;
const url = `${apiScheme}://${tokenApiHost}/${_ENDPOINT}`;
const { tokenApiHost, apiKey, sdkClientVersion } = auth.config;
const url = _getFinalTarget(auth, tokenApiHost, _ENDPOINT, `key=${apiKey}`);

return FetchProvider.fetch()(`${url}?key=${apiKey}`, {
return FetchProvider.fetch()(url, {
method: HttpMethod.POST,
headers: {
'X-Client-Version': sdkClientVersion,
Expand Down
21 changes: 19 additions & 2 deletions packages-exp/auth-exp/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
import { fail } from '../core/util/assert';
import { Delay } from '../core/util/delay';
import { FetchProvider } from '../core/util/fetch_provider';
import { AuthCore } from '../model/auth';
import { Auth, AuthCore } from '../model/auth';
import { IdTokenResponse, TaggedWithTokenResponse } from '../model/id_token';
import { IdTokenMfaResponse } from './authentication/mfa';
import { SERVER_ERROR_MAP, ServerError, ServerErrorMap } from './errors';
Expand Down Expand Up @@ -99,7 +99,7 @@ export async function _performApiRequest<T, V>(
}

return FetchProvider.fetch()(
`${auth.config.apiScheme}://${auth.config.apiHost}${path}?${query}`,
_getFinalTarget(auth, auth.config.apiHost, path, query),
{
method,
headers,
Expand All @@ -115,6 +115,7 @@ export async function _performFetchWithErrorHandling<V>(
customErrorMap: Partial<ServerErrorMap<ServerError>>,
fetchFn: () => Promise<Response>
): Promise<V> {
(auth as Auth)._canInitEmulator = false;
const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };
try {
const response: Response = await Promise.race<Promise<Response>>([
Expand Down Expand Up @@ -183,6 +184,22 @@ export async function _performSignInRequest<T, V extends IdTokenResponse>(
return serverResponse;
}

export function _getFinalTarget(
auth: AuthCore,
host: string,
path: string,
query: string
): string {
const { emulator } = auth.config;
const base = `${host}${path}?${query}`;

if (!emulator) {
return `${auth.config.apiScheme}://${base}`;
}

return `http://${emulator.hostname}:${emulator.port}/${base}`;
}

function makeNetworkTimeout<T>(appName: string): Promise<T> {
return new Promise((_, reject) =>
setTimeout(() => {
Expand Down
4 changes: 4 additions & 0 deletions packages-exp/auth-exp/src/core/auth/auth_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ export class AuthImplCompat<T extends User> implements Auth, _FirebaseService {
private idTokenSubscription = new Subscription<T>(this);
private redirectUser: T | null = null;
private isProactiveRefreshEnabled = false;

// Any network calls will set this to true and prevent subsequent emulator
// initialization
_canInitEmulator = true;
_isInitialized = false;
_initializationPromise: Promise<void> | null = null;
_popupRedirectResolver: PopupRedirectResolver | null = null;
Expand Down
70 changes: 70 additions & 0 deletions packages-exp/auth-exp/src/core/auth/initialize.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/**
* @license
* Copyright 2020 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 } from 'chai';

import { Auth, User } from '@firebase/auth-types-exp';
import { FirebaseError } from '@firebase/util';

import { endpointUrl, mockEndpoint } from '../../../test/helpers/api/helper';
import { testAuth, testUser } from '../../../test/helpers/mock_auth';
import * as fetch from '../../../test/helpers/mock_fetch';
import { _getFinalTarget, Endpoint } from '../../api';
import { _castAuth } from './auth_impl';
import { useEmulator } from './initialize';

describe('core/auth/initialize', () => {
let auth: Auth;
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();
});

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

it('updates the endpoint appropriately', async () => {
useEmulator(auth, 'localhost', 2020);
await user.delete();
expect(normalEndpoint.calls.length).to.eq(0);
expect(emulatorEndpoint.calls.length).to.eq(1);
});
});
});
20 changes: 19 additions & 1 deletion packages-exp/auth-exp/src/core/auth/initialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ import { FirebaseApp } from '@firebase/app-types-exp';
import * as externs from '@firebase/auth-types-exp';

import { Dependencies } from '../../model/auth';
import { AuthErrorCode } from '../errors';
import { Persistence } from '../persistence';
import { assert } from '../util/assert';
import { _getInstance } from '../util/instantiator';
import { AuthImpl } from './auth_impl';
import { _castAuth, AuthImpl } from './auth_impl';

export function initializeAuth(
app: FirebaseApp = getApp(),
Expand All @@ -34,6 +36,22 @@ export function initializeAuth(
return auth;
}

export function useEmulator(
authExtern: externs.Auth,
hostname: string,
port: number
): void {
const auth = _castAuth(authExtern);
assert(auth._canInitEmulator, AuthErrorCode.EMULATOR_CONFIG_FAILED, {
appName: auth.name
});

auth.config.emulator = {
hostname,
port
};
}

export function _initializeAuthInstance(
auth: AuthImpl,
deps?: Dependencies
Expand Down
7 changes: 6 additions & 1 deletion packages-exp/auth-exp/src/core/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
import * as externs from '@firebase/auth-types-exp';
import { ErrorFactory, ErrorMap } from '@firebase/util';

import { AppName } from '../model/auth';
import { IdTokenMfaResponse } from '../api/authentication/mfa';
import { AppName } from '../model/auth';

/*
* Developer facing Firebase Auth error codes.
Expand All @@ -40,6 +40,7 @@ export const enum AuthErrorCode {
DYNAMIC_LINK_NOT_ACTIVATED = 'dynamic-link-not-activated',
EMAIL_CHANGE_NEEDS_VERIFICATION = 'email-change-needs-verification',
EMAIL_EXISTS = 'email-already-in-use',
EMULATOR_CONFIG_FAILED = 'emulator-config-failed',
EXPIRED_OOB_CODE = 'expired-action-code',
EXPIRED_POPUP_REQUEST = 'cancelled-popup-request',
INTERNAL_ERROR = 'internal-error',
Expand Down Expand Up @@ -154,6 +155,10 @@ const ERRORS: ErrorMap<AuthErrorCode> = {
'Multi-factor users must always have a verified email.',
[AuthErrorCode.EMAIL_EXISTS]:
'The email address is already in use by another account.',
[AuthErrorCode.EMULATOR_CONFIG_FAILED]:
'Auth instance has already been used to make a network call. Auth can ' +
'no longer be configured to use the emulator. Try calling ' +
'"useEmulator()" sooner.',
[AuthErrorCode.EXPIRED_OOB_CODE]: 'The action code has expired.',
[AuthErrorCode.EXPIRED_POPUP_REQUEST]:
'This operation has been cancelled due to another conflicting popup being opened.',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ describe('core/user/token_manager', () => {
let mock: fetch.Route;
beforeEach(() => {
const { apiKey, tokenApiHost, apiScheme } = auth.config;
const endpoint = `${apiScheme}://${tokenApiHost}/${_ENDPOINT}?key=${apiKey}`;
const endpoint = `${apiScheme}://${tokenApiHost}${_ENDPOINT}?key=${apiKey}`;
mock = fetch.mock(endpoint, {
'access_token': 'new-access-token',
'refresh_token': 'new-refresh-token',
Expand Down
10 changes: 9 additions & 1 deletion packages-exp/auth-exp/src/model/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,20 @@ export type AppName = string;
export type ApiKey = string;
export type AuthDomain = string;

interface ConfigInternal extends externs.Config {
emulator?: {
hostname: string;
port: number;
};
}

/**
* Core implementation of the Auth object, the signatures here should match across both legacy
* and modern implementations
*/
export interface AuthCore {
readonly name: AppName;
readonly config: externs.Config;
readonly config: ConfigInternal;
languageCode: string | null;
tenantId: string | null;
readonly settings: externs.AuthSettings;
Expand All @@ -42,6 +49,7 @@ export interface AuthCore {

export interface Auth extends AuthCore {
currentUser: User | null;
_canInitEmulator: boolean;
_isInitialized: boolean;
_initializationPromise: Promise<void> | null;
updateCurrentUser(user: User | null): Promise<void>;
Expand Down
10 changes: 5 additions & 5 deletions packages-exp/auth-exp/test/helpers/api/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ import { Endpoint } from '../../../src/api';
import { TEST_HOST, TEST_KEY, TEST_SCHEME } from '../mock_auth';
import { mock, Route } from '../mock_fetch';

export function endpointUrl(endpoint: Endpoint): string {
return `${TEST_SCHEME}://${TEST_HOST}${endpoint}?key=${TEST_KEY}`;
}

export function mockEndpoint(
endpoint: Endpoint,
response: object,
status = 200
): Route {
return mock(
`${TEST_SCHEME}://${TEST_HOST}${endpoint}?key=${TEST_KEY}`,
response,
status
);
return mock(endpointUrl(endpoint), response, status);
}