Skip to content

Add signInWithPhoneNumber implementation #3191

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 4 commits into from
Jun 9, 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
78 changes: 78 additions & 0 deletions packages-exp/auth-exp/src/core/providers/phone.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* @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 * as sinon from 'sinon';

import { mockEndpoint } from '../../../test/api/helper';
import { testAuth } from '../../../test/mock_auth';
import * as fetch from '../../../test/mock_fetch';
import { Endpoint } from '../../api';
import { Auth } from '../../model/auth';
import { RecaptchaVerifier } from '../../platform_browser/recaptcha/recaptcha_verifier';
import { PhoneAuthProvider } from './phone';

describe('core/providers/phone', () => {
let auth: Auth;

beforeEach(async () => {
fetch.setUp();
auth = await testAuth();
});

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

context('#verifyPhoneNumber', () => {
it('calls verify on the appVerifier and then calls the server', async () => {
const route = mockEndpoint(Endpoint.SEND_VERIFICATION_CODE, {
sessionInfo: 'verification-id'
});

const verifier = new RecaptchaVerifier(
document.createElement('div'),
{},
auth
);
sinon
.stub(verifier, 'verify')
.returns(Promise.resolve('verification-code'));

const provider = new PhoneAuthProvider(auth);
const result = await provider.verifyPhoneNumber('+15105550000', verifier);
expect(result).to.eq('verification-id');
expect(route.calls[0].request).to.eql({
phoneNumber: '+15105550000',
recaptchaToken: 'verification-code'
});
});
});

context('.credential', () => {
it('creates a phone auth credential', () => {
const credential = PhoneAuthProvider.credential('id', 'code');

// Allows us to inspect the object
const blob = credential.toJSON() as Record<string, string>;

expect(blob.verificationId).to.eq('id');
expect(blob.verificationCode).to.eq('code');
});
});
});
71 changes: 71 additions & 0 deletions packages-exp/auth-exp/src/core/providers/phone.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* @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 externs from '@firebase/auth-types-exp';
import { FirebaseError } from '@firebase/util';

import { Auth } from '../../model/auth';
import { initializeAuth } from '../auth/auth_impl';
import { _verifyPhoneNumber } from '../strategies/phone';
import { PhoneAuthCredential } from '../strategies/phone_credential';
import { debugFail } from '../util/assert';

export class PhoneAuthProvider implements externs.AuthProvider {
static readonly PROVIDER_ID = externs.ProviderId.PHONE;
static readonly PHONE_SIGN_IN_METHOD = externs.SignInMethod.PHONE;

private readonly auth: Auth;
readonly providerId = PhoneAuthProvider.PROVIDER_ID;

constructor(auth?: externs.Auth | null) {
this.auth = (auth || initializeAuth()) as Auth;
}

verifyPhoneNumber(
phoneNumber: string,
applicationVerifier: externs.ApplicationVerifier
/* multiFactorSession?: MultiFactorSession, */
): Promise<string> {
return _verifyPhoneNumber(this.auth, phoneNumber, applicationVerifier);
}

static credential(
verificationId: string,
verificationCode: string
): PhoneAuthCredential {
return new PhoneAuthCredential({ verificationId, verificationCode });
}

static credentialFromResult(
userCredential: externs.UserCredential
): externs.AuthCredential | null {
void userCredential;
return debugFail('not implemented');
}

static credentialFromError(
error: FirebaseError
): externs.AuthCredential | null {
void error;
return debugFail('not implemented');
}

static credentialFromJSON(json: string | object): externs.AuthCredential {
Copy link
Contributor

Choose a reason for hiding this comment

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

isn't this one trivial to implement in this PR?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm actually not sure the purpose of that one... It's already a static method on the PhoneCredential

void json;
return debugFail('not implemented');
}
}
169 changes: 169 additions & 0 deletions packages-exp/auth-exp/src/core/strategies/phone.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/**
* @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 chaiAsPromised from 'chai-as-promised';
import * as sinon from 'sinon';
import * as sinonChai from 'sinon-chai';

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

import { mockEndpoint } from '../../../test/api/helper';
import { testAuth } from '../../../test/mock_auth';
import * as fetch from '../../../test/mock_fetch';
import { Endpoint } from '../../api';
import { Auth } from '../../model/auth';
import { IdTokenResponse } from '../../model/id_token';
import { RecaptchaVerifier } from '../../platform_browser/recaptcha/recaptcha_verifier';
import { _verifyPhoneNumber, signInWithPhoneNumber } from './phone';

use(chaiAsPromised);
use(sinonChai);

describe('core/strategies/phone', () => {
let auth: Auth;
let verifier: ApplicationVerifier;
let sendCodeEndpoint: fetch.Route;

beforeEach(async () => {
auth = await testAuth();
fetch.setUp();

sendCodeEndpoint = mockEndpoint(Endpoint.SEND_VERIFICATION_CODE, {
sessionInfo: 'session-info'
});

verifier = new RecaptchaVerifier(document.createElement('div'), {}, auth);
sinon.stub(verifier, 'verify').returns(Promise.resolve('recaptcha-token'));
});

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

describe('signInWithPhoneNumber', () => {
it('calls verify phone number', async () => {
await signInWithPhoneNumber(auth, '+15105550000', verifier);

expect(sendCodeEndpoint.calls[0].request).to.eql({
recaptchaToken: 'recaptcha-token',
phoneNumber: '+15105550000'
});
});

context('ConfirmationResult', () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

can you test the callback getting called?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's covered in the test "calling #confirm finishes the sign in flow"

The callback calls signInWithCredential() which itself calls the SIGN_IN_WITH_PHONE_NUMBER endpoint

it('result contains verification id baked in', async () => {
const result = await signInWithPhoneNumber(auth, 'number', verifier);
expect(result.verificationId).to.eq('session-info');
});

it('calling #confirm finishes the sign in flow', async () => {
const idTokenResponse: IdTokenResponse = {
idToken: 'my-id-token',
refreshToken: 'my-refresh-token',
expiresIn: '1234',
localId: 'uid',
kind: 'my-kind'
};

// This endpoint is called from within the callback, in
// signInWithCredential
const signInEndpoint = mockEndpoint(
Endpoint.SIGN_IN_WITH_PHONE_NUMBER,
idTokenResponse
);
mockEndpoint(Endpoint.GET_ACCOUNT_INFO, {
users: [{ localId: 'uid' }]
});

const result = await signInWithPhoneNumber(auth, 'number', verifier);
const userCred = await result.confirm('6789');
expect(userCred.user.uid).to.eq('uid');
expect(userCred.operationType).to.eq(OperationType.SIGN_IN);
expect(signInEndpoint.calls[0].request).to.eql({
sessionInfo: 'session-info',
code: '6789'
});
});
});
});

describe('_verifyPhoneNumber', () => {
it('works with a string phone number', async () => {
await _verifyPhoneNumber(auth, 'number', verifier);
expect(sendCodeEndpoint.calls[0].request).to.eql({
recaptchaToken: 'recaptcha-token',
phoneNumber: 'number'
});
});

it('works with an options object', async () => {
await _verifyPhoneNumber(
auth,
{
phoneNumber: 'number'
},
verifier
);
expect(sendCodeEndpoint.calls[0].request).to.eql({
recaptchaToken: 'recaptcha-token',
phoneNumber: 'number'
});
});

it('throws if the verifier does not return a string', async () => {
(verifier.verify as sinon.SinonStub).returns(Promise.resolve(123));
await expect(
_verifyPhoneNumber(auth, 'number', verifier)
).to.be.rejectedWith(
FirebaseError,
'Firebase: Error (auth/argument-error)'
);
});

it('throws if the verifier type is not recaptcha', async () => {
const mutVerifier: {
-readonly [K in keyof ApplicationVerifier]: ApplicationVerifier[K];
} = verifier;
mutVerifier.type = 'not-recaptcha-thats-for-sure';
await expect(
_verifyPhoneNumber(auth, 'number', mutVerifier)
).to.be.rejectedWith(
FirebaseError,
'Firebase: Error (auth/argument-error)'
);
});

it('resets the verifer after successful verification', async () => {
sinon.spy(verifier, 'reset');
expect(await _verifyPhoneNumber(auth, 'number', verifier)).to.eq(
'session-info'
);
expect(verifier.reset).to.have.been.called;
});

it('resets the verifer after a failed verification', async () => {
sinon.spy(verifier, 'reset');
(verifier.verify as sinon.SinonStub).returns(Promise.resolve(123));

await expect(_verifyPhoneNumber(auth, 'number', verifier)).to.be.rejected;
expect(verifier.reset).to.have.been.called;
});
});
});
Loading