Skip to content

Add auth listener implementation, add user.reload() #2961

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 11 commits into from
Apr 23, 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
4 changes: 2 additions & 2 deletions packages-exp/auth-exp/src/api/account_management/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

import { Endpoint, HttpMethod, performApiRequest } from '..';
import { Endpoint, HttpMethod, performApiRequest } from '../';
import { Auth } from '../../model/auth';
import { APIMFAInfo } from '../../model/id_token';

Expand Down Expand Up @@ -74,7 +74,7 @@ export interface APIUserInfo {
createdAt?: number;
tenantId?: string;
passwordHash?: string;
providerUserInfo: ProviderUserInfo[];
providerUserInfo?: ProviderUserInfo[];
mfaInfo?: APIMFAInfo[];
}

Expand Down
134 changes: 134 additions & 0 deletions packages-exp/auth-exp/src/core/auth/auth_impl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { FirebaseError } from '@firebase/util';

import { testUser } from '../../../test/mock_auth';
import { Auth } from '../../model/auth';
import { User } from '../../model/user';
import { Persistence } from '../persistence';
import { browserLocalPersistence } from '../persistence/browser';
import { inMemoryPersistence } from '../persistence/in_memory';
Expand Down Expand Up @@ -117,6 +118,139 @@ describe('AuthImpl', () => {
);
});
});

describe('change listeners', () => {
// // Helpers to convert auth state change results to promise
// function onAuthStateChange(callback: NextFn<User|null>)

it('immediately calls authStateChange if initialization finished', done => {
const user = testUser('uid');
auth.currentUser = user;
auth._isInitialized = true;
auth.onAuthStateChanged(user => {
expect(user).to.eq(user);
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 use expect(callback).to.have.been.calledWith() instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

Copy link
Contributor

Choose a reason for hiding this comment

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

oh, maybe I misunderstood, it looks like you used calledWith() down below, but not in these test cases

done();
});
});

it('immediately calls idTokenChange if initialization finished', done => {
const user = testUser('uid');
auth.currentUser = user;
auth._isInitialized = true;
auth.onIdTokenChange(user => {
expect(user).to.eq(user);
done();
});
});

it('immediate callback is done async', () => {
auth._isInitialized = true;
let callbackCalled = false;
auth.onIdTokenChange(() => {
callbackCalled = true;
});

expect(callbackCalled).to.be.false;
});

describe('user logs in/out, tokens refresh', () => {
let user: User;
let authStateCallback: sinon.SinonSpy;
let idTokenCallback: sinon.SinonSpy;

beforeEach(() => {
user = testUser('uid');
authStateCallback = sinon.spy();
idTokenCallback = sinon.spy();
});

context('initially currentUser is null', () => {
beforeEach(async () => {
auth.onAuthStateChanged(authStateCallback);
auth.onIdTokenChange(idTokenCallback);
await auth.updateCurrentUser(null);
authStateCallback.resetHistory();
idTokenCallback.resetHistory();
});

it('onAuthStateChange triggers on log in', async () => {
await auth.updateCurrentUser(user);
expect(authStateCallback).to.have.been.calledWith(user);
});

it('onIdTokenChange triggers on log in', async () => {
await auth.updateCurrentUser(user);
expect(idTokenCallback).to.have.been.calledWith(user);
});
});

context('initially currentUser is user', () => {
beforeEach(async () => {
auth.onAuthStateChanged(authStateCallback);
auth.onIdTokenChange(idTokenCallback);
await auth.updateCurrentUser(user);
authStateCallback.resetHistory();
idTokenCallback.resetHistory();
});

it('onAuthStateChange triggers on log out', async () => {
await auth.updateCurrentUser(null);
expect(authStateCallback).to.have.been.calledWith(null);
});

it('onIdTokenChange triggers on log out', async () => {
await auth.updateCurrentUser(null);
expect(idTokenCallback).to.have.been.calledWith(null);
});

it('onAuthStateChange does not trigger for user props change', async () => {
user.refreshToken = 'hey look I changed';
await auth.updateCurrentUser(user);
expect(authStateCallback).not.to.have.been.called;
});

it('onIdTokenChange triggers for user props change', async () => {
user.refreshToken = 'hey look I changed';
await auth.updateCurrentUser(user);
expect(idTokenCallback).to.have.been.calledWith(user);
});

it('onAuthStateChange triggers if uid changes', async () => {
const newUser = testUser('different-uid');
await auth.updateCurrentUser(newUser);
expect(authStateCallback).to.have.been.calledWith(newUser);
});
});

it('onAuthStateChange works for multiple listeners', async () => {
const cb1 = sinon.spy();
const cb2 = sinon.spy();
auth.onAuthStateChanged(cb1);
auth.onAuthStateChanged(cb2);
await auth.updateCurrentUser(null);
cb1.resetHistory();
cb2.resetHistory();

await auth.updateCurrentUser(user);
expect(cb1).to.have.been.calledWith(user);
expect(cb2).to.have.been.calledWith(user);
});

it('onIdTokenChange works for multiple listeners', async () => {
const cb1 = sinon.spy();
const cb2 = sinon.spy();
auth.onIdTokenChange(cb1);
auth.onIdTokenChange(cb2);
await auth.updateCurrentUser(null);
cb1.resetHistory();
cb2.resetHistory();

await auth.updateCurrentUser(user);
expect(cb1).to.have.been.calledWith(user);
expect(cb2).to.have.been.calledWith(user);
});
});
});
});

describe('initializeAuth', () => {
Expand Down
102 changes: 100 additions & 2 deletions packages-exp/auth-exp/src/core/auth/auth_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,17 @@

import { getApp } from '@firebase/app-exp';
import { FirebaseApp } from '@firebase/app-types-exp';

import { Auth, Config, Dependencies } from '../../model/auth';
import {
CompleteFn,
createSubscribe,
ErrorFn,
NextFn,
Observer,
Subscribe,
Unsubscribe
} from '@firebase/util';

import { Auth, Config, Dependencies, NextOrObserver } from '../../model/auth';
import { User } from '../../model/user';
import { AuthErrorCode } from '../errors';
import { Persistence } from '../persistence';
Expand All @@ -37,6 +46,13 @@ class AuthImpl implements Auth {
currentUser: User | null = null;
private operations = Promise.resolve();
private persistenceManager?: PersistenceUserManager;
private authStateSubscription = new Subscription<User>(this);
private idTokenSubscription = new Subscription<User>(this);
_isInitialized = false;

// Tracks the last notified UID for state change listeners to prevent
// repeated calls to the callbacks
private lastNotifiedUid: string | undefined = undefined;

constructor(
public readonly name: string,
Expand All @@ -57,6 +73,9 @@ class AuthImpl implements Auth {
if (storedUser) {
await this.directlySetCurrentUser(storedUser);
}

this._isInitialized = true;
this._notifyStateListeners();
});
}

Expand All @@ -74,6 +93,68 @@ class AuthImpl implements Auth {
});
}

onAuthStateChanged(
nextOrObserver: NextOrObserver<User>,
error?: ErrorFn,
completed?: CompleteFn
): Unsubscribe {
return this.registerStateListener(
this.authStateSubscription,
nextOrObserver,
error,
completed
);
}

onIdTokenChange(
nextOrObserver: NextOrObserver<User>,
error?: ErrorFn,
completed?: CompleteFn
): Unsubscribe {
return this.registerStateListener(
this.idTokenSubscription,
nextOrObserver,
error,
completed
);
}

_notifyStateListeners(): void {
if (!this._isInitialized) {
return;
}

this.idTokenSubscription.next(this.currentUser);

if (this.lastNotifiedUid !== this.currentUser?.uid) {
this.lastNotifiedUid = this.currentUser?.uid;
this.authStateSubscription.next(this.currentUser);
}
}

private registerStateListener(
subscription: Subscription<User>,
nextOrObserver: NextOrObserver<User>,
error?: ErrorFn,
completed?: CompleteFn
): Unsubscribe {
if (this._isInitialized) {
const cb =
typeof nextOrObserver === 'function'
? nextOrObserver
: nextOrObserver.next;
// The callback needs to be called asynchronously per the spec.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Promise.resolve().then(() => cb(this.currentUser));
}

if (typeof nextOrObserver === 'function') {
return subscription.addObserver(nextOrObserver, error, completed);
} else {
return subscription.addObserver(nextOrObserver);
}
}

/**
* Unprotected (from race conditions) method to set the current user. This
* should only be called from within a queued callback. This is necessary
Expand All @@ -87,6 +168,8 @@ class AuthImpl implements Auth {
} else {
await this.assertedPersistence.removeCurrentUser();
}

this._notifyStateListeners();
}

private queue(action: AsyncAction): Promise<void> {
Expand Down Expand Up @@ -122,3 +205,18 @@ export function initializeAuth(

return new AuthImpl(app.name, config, hierarchy);
}

/** Helper class to wrap subscriber logic */
class Subscription<T> {
private observer: Observer<T | null> | null = null;
readonly addObserver: Subscribe<T | null> = createSubscribe(
observer => (this.observer = observer)
);

constructor(readonly auth: Auth) {}

get next(): NextFn<T | null> {
assert(this.observer, this.auth.name);
return this.observer.next.bind(this.observer);
}
}
Loading