Skip to content

Add Cordova support to the compatibility layer #4535

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
Feb 25, 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
3 changes: 2 additions & 1 deletion packages-exp/auth-compat-exp/src/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { expect, use } from 'chai';
import * as sinon from 'sinon';
import * as sinonChai from 'sinon-chai';
import { Auth } from './auth';
import { CompatPopupRedirectResolver } from './popup_redirect';

use(sinonChai);

Expand Down Expand Up @@ -69,7 +70,7 @@ describe('auth compat', () => {
exp._getInstance(exp.inMemoryPersistence),
exp._getInstance(exp.indexedDBLocalPersistence)
],
exp.browserPopupRedirectResolver
CompatPopupRedirectResolver
);
}
});
Expand Down
9 changes: 5 additions & 4 deletions packages-exp/auth-compat-exp/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {

import { _validatePersistenceArgument, Persistence } from './persistence';
import { _isPopupRedirectSupported } from './platform';
import { CompatPopupRedirectResolver } from './popup_redirect';
import { User } from './user';
import {
convertConfirmationResult,
Expand Down Expand Up @@ -71,7 +72,7 @@ export class Auth
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.auth._initializeWithPersistence(
hierarchy,
exp.browserPopupRedirectResolver
CompatPopupRedirectResolver
);
}

Expand Down Expand Up @@ -142,7 +143,7 @@ export class Auth
);
const credential = await exp.getRedirectResult(
this.auth,
exp.browserPopupRedirectResolver
CompatPopupRedirectResolver
);
if (!credential) {
return {
Expand Down Expand Up @@ -283,7 +284,7 @@ export class Auth
exp.signInWithPopup(
this.auth,
provider as exp.AuthProvider,
exp.browserPopupRedirectResolver
CompatPopupRedirectResolver
)
);
}
Expand All @@ -297,7 +298,7 @@ export class Auth
return exp.signInWithRedirect(
this.auth,
provider as exp.AuthProvider,
exp.browserPopupRedirectResolver
CompatPopupRedirectResolver
);
}
updateCurrentUser(user: compat.User | null): Promise<void> {
Expand Down
22 changes: 21 additions & 1 deletion packages-exp/auth-compat-exp/src/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ declare global {
}
}

const CORDOVA_ONDEVICEREADY_TIMEOUT_MS = 1000;

function _getCurrentScheme(): string | null {
return self?.location?.protocol || null;
}
Expand All @@ -47,7 +49,7 @@ function _isHttpOrHttps(): boolean {
* @return {boolean} Whether the app is rendered in a mobile iOS or Android
* Cordova environment.
*/
function _isAndroidOrIosCordovaScheme(ua: string = getUA()): boolean {
export function _isAndroidOrIosCordovaScheme(ua: string = getUA()): boolean {
return !!(
(_getCurrentScheme() === 'file:' || _getCurrentScheme() === 'ionic:') &&
ua.toLowerCase().match(/iphone|ipad|ipod|android/)
Expand Down Expand Up @@ -159,3 +161,21 @@ export function _getClientPlatform(): impl.ClientPlatform {
}
return impl.ClientPlatform.BROWSER;
}

export async function _isCordova(): Promise<boolean> {
if (!_isAndroidOrIosCordovaScheme() || typeof document === 'undefined') {
return false;
}

return new Promise(resolve => {
const timeoutId = setTimeout(() => {
// We've waited long enough; the telltale Cordova event didn't happen
resolve(false);
}, CORDOVA_ONDEVICEREADY_TIMEOUT_MS);

document.addEventListener('deviceready', () => {
clearTimeout(timeoutId);
resolve(true);
});
});
}
151 changes: 151 additions & 0 deletions packages-exp/auth-compat-exp/src/popup_redirect.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/**
* @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, use } from 'chai';
import * as sinonChai from 'sinon-chai';
import * as sinon from 'sinon';
import * as exp from '@firebase/auth-exp/internal';
import * as platform from './platform';
import { CompatPopupRedirectResolver } from './popup_redirect';
import { FirebaseApp } from '@firebase/app-compat';

use(sinonChai);

describe('popup_redirect/CompatPopupRedirectResolver', () => {
let compatResolver: CompatPopupRedirectResolver;
let auth: exp.AuthImpl;

beforeEach(() => {
compatResolver = new CompatPopupRedirectResolver();
const app = { options: { apiKey: 'api-key' } } as FirebaseApp;
auth = new exp.AuthImpl(app, {
apiKey: 'api-key'
} as exp.Config);
});

afterEach(() => {
sinon.restore();
});

context('initialization and resolver selection', () => {
const browserResolver = exp._getInstance<exp.PopupRedirectResolverInternal>(
exp.browserPopupRedirectResolver
);
const cordovaResolver = exp._getInstance<exp.PopupRedirectResolverInternal>(
exp.cordovaPopupRedirectResolver
);

beforeEach(() => {
sinon.stub(browserResolver, '_initialize');
sinon.stub(cordovaResolver, '_initialize');
});

it('selects the Cordova resolver if in Cordova', async () => {
sinon.stub(platform, '_isCordova').returns(Promise.resolve(true));
await compatResolver._initialize(auth);
expect(cordovaResolver._initialize).to.have.been.calledWith(auth);
expect(browserResolver._initialize).not.to.have.been.called;
});

it('selects the Browser resolver if in Browser', async () => {
sinon.stub(platform, '_isCordova').returns(Promise.resolve(false));
await compatResolver._initialize(auth);
expect(cordovaResolver._initialize).not.to.have.been.called;
expect(browserResolver._initialize).to.have.been.calledWith(auth);
});
});

context('callthrough methods', () => {
let underlyingResolver: sinon.SinonStubbedInstance<exp.PopupRedirectResolverInternal>;
let provider: exp.AuthProvider;

beforeEach(() => {
underlyingResolver = sinon.createStubInstance(FakeResolver);
((compatResolver as unknown) as {
underlyingResolver: exp.PopupRedirectResolverInternal;
}).underlyingResolver = underlyingResolver;
provider = new exp.GoogleAuthProvider();
});

it('_openPopup', async () => {
await compatResolver._openPopup(
auth,
provider,
exp.AuthEventType.LINK_VIA_POPUP,
'eventId'
);
expect(underlyingResolver._openPopup).to.have.been.calledWith(
auth,
provider,
exp.AuthEventType.LINK_VIA_POPUP,
'eventId'
);
});

it('_openRedirect', async () => {
await compatResolver._openRedirect(
auth,
provider,
exp.AuthEventType.LINK_VIA_REDIRECT,
'eventId'
);
expect(underlyingResolver._openRedirect).to.have.been.calledWith(
auth,
provider,
exp.AuthEventType.LINK_VIA_REDIRECT,
'eventId'
);
});

it('_isIframeWebStorageSupported', () => {
const cb = (): void => {};
compatResolver._isIframeWebStorageSupported(auth, cb);
expect(
underlyingResolver._isIframeWebStorageSupported
).to.have.been.calledWith(auth, cb);
});

it('_originValidation', async () => {
await compatResolver._originValidation(auth);
expect(underlyingResolver._originValidation).to.have.been.calledWith(
auth
);
});
});
});

class FakeResolver implements exp.PopupRedirectResolverInternal {
_completeRedirectFn = async (): Promise<null> => null;
_redirectPersistence = exp.inMemoryPersistence;

_initialize(): Promise<exp.EventManager> {
throw new Error('Method not implemented.');
}
_openPopup(): Promise<exp.AuthPopup> {
throw new Error('Method not implemented.');
}
_openRedirect(): Promise<void> {
throw new Error('Method not implemented.');
}
_isIframeWebStorageSupported(): void {
throw new Error('Method not implemented.');
}

_originValidation(): Promise<void> {
throw new Error('Method not implemented.');
}
}
94 changes: 94 additions & 0 deletions packages-exp/auth-compat-exp/src/popup_redirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* @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 * as exp from '@firebase/auth-exp/internal';
import { _isCordova } from './platform';

const _assert: typeof exp._assert = exp._assert;

/** Platform-agnostic popup-redirect resolver */
export class CompatPopupRedirectResolver
implements exp.PopupRedirectResolverInternal {
private underlyingResolver: exp.PopupRedirectResolverInternal | null = null;
_redirectPersistence = exp.browserSessionPersistence;

_completeRedirectFn: (
auth: exp.Auth,
resolver: exp.PopupRedirectResolver,
bypassAuthState: boolean
) => Promise<exp.UserCredential | null> = exp._getRedirectResult;

async _initialize(auth: exp.AuthImpl): Promise<exp.EventManager> {
if (this.underlyingResolver) {
return this.underlyingResolver._initialize(auth);
}

// We haven't yet determined whether or not we're in Cordova; go ahead
// and determine that state now.
const isCordova = await _isCordova();
this.underlyingResolver = exp._getInstance(
isCordova
? exp.cordovaPopupRedirectResolver
: exp.browserPopupRedirectResolver
);
return this.assertedUnderlyingResolver._initialize(auth);
}

_openPopup(
auth: exp.AuthImpl,
provider: exp.AuthProvider,
authType: exp.AuthEventType,
eventId?: string
): Promise<exp.AuthPopup> {
return this.assertedUnderlyingResolver._openPopup(
auth,
provider,
authType,
eventId
);
}

_openRedirect(
auth: exp.AuthImpl,
provider: exp.AuthProvider,
authType: exp.AuthEventType,
eventId?: string
): Promise<void> {
return this.assertedUnderlyingResolver._openRedirect(
auth,
provider,
authType,
eventId
);
}

_isIframeWebStorageSupported(
auth: exp.AuthImpl,
cb: (support: boolean) => unknown
): void {
this.assertedUnderlyingResolver._isIframeWebStorageSupported(auth, cb);
}

_originValidation(auth: exp.Auth): Promise<void> {
return this.assertedUnderlyingResolver._originValidation(auth);
}

private get assertedUnderlyingResolver(): exp.PopupRedirectResolverInternal {
_assert(this.underlyingResolver, exp.AuthErrorCode.INTERNAL_ERROR);
return this.underlyingResolver;
}
}
9 changes: 5 additions & 4 deletions packages-exp/auth-compat-exp/src/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import * as exp from '@firebase/auth-exp/internal';
import * as compat from '@firebase/auth-types';
import { CompatPopupRedirectResolver } from './popup_redirect';
import {
convertConfirmationResult,
convertCredential
Expand Down Expand Up @@ -91,15 +92,15 @@ export class User implements compat.User, Wrapper<exp.User> {
exp.linkWithPopup(
this.user,
provider as exp.AuthProvider,
exp.browserPopupRedirectResolver
CompatPopupRedirectResolver
)
);
}
linkWithRedirect(provider: compat.AuthProvider): Promise<void> {
return exp.linkWithRedirect(
this.user,
provider as exp.AuthProvider,
exp.browserPopupRedirectResolver
CompatPopupRedirectResolver
);
}
reauthenticateAndRetrieveDataWithCredential(
Expand Down Expand Up @@ -139,15 +140,15 @@ export class User implements compat.User, Wrapper<exp.User> {
exp.reauthenticateWithPopup(
this.user,
provider as exp.AuthProvider,
exp.browserPopupRedirectResolver
CompatPopupRedirectResolver
)
);
}
reauthenticateWithRedirect(provider: compat.AuthProvider): Promise<void> {
return exp.reauthenticateWithRedirect(
this.user,
provider as exp.AuthProvider,
exp.browserPopupRedirectResolver
CompatPopupRedirectResolver
);
}
sendEmailVerification(
Expand Down
Loading