Skip to content

Add a persistence manager class #2925

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 26 commits into from
Apr 20, 2020
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
f6d83b5
Add persistence layer: index db, in memory, and browser{local, session}
sam-gc Apr 14, 2020
efab6d0
[AUTOMATED]: Prettier Code Styling
sam-gc Apr 14, 2020
b561823
Add indexed_db isAvailable test
sam-gc Apr 15, 2020
67e46a9
[AUTOMATED]: Prettier Code Styling
sam-gc Apr 15, 2020
7cc84c1
Add persistence layer: index db, in memory, and browser{local, session}
sam-gc Apr 14, 2020
c9bbfe8
[AUTOMATED]: Prettier Code Styling
sam-gc Apr 14, 2020
67446ea
[AUTOMATED]: License Headers
sam-gc Apr 14, 2020
afdce7e
Add persistence manager class
sam-gc Apr 16, 2020
ef91d2b
[AUTOMATED]: Prettier Code Styling
sam-gc Apr 16, 2020
0d8659d
[AUTOMATED]: License Headers
sam-gc Apr 16, 2020
a15679c
Formatting
sam-gc Apr 16, 2020
4254fac
Formatting
sam-gc Apr 16, 2020
2711c51
Address review comments
sam-gc Apr 16, 2020
ed0ff67
[AUTOMATED]: Prettier Code Styling
sam-gc Apr 16, 2020
a1cbef8
Add util/assert
sam-gc Apr 16, 2020
f1cfec2
[AUTOMATED]: Prettier Code Styling
sam-gc Apr 16, 2020
eebc885
Update assertType to allow multiple types
sam-gc Apr 17, 2020
1d93a6d
[AUTOMATED]: Prettier Code Styling
sam-gc Apr 17, 2020
a6338ec
UserImpl toPlainObject
sam-gc Apr 17, 2020
ede366c
Move instantiation into persistence manager, add a toPlainObject as well
sam-gc Apr 17, 2020
8ccb75e
[AUTOMATED]: Prettier Code Styling
sam-gc Apr 17, 2020
1fce8ba
Move CONST_ to _CONST
sam-gc Apr 17, 2020
df6c1d0
[AUTOMATED]: Prettier Code Styling
sam-gc Apr 17, 2020
cd255da
PR feedback
sam-gc Apr 17, 2020
ea70a8a
[AUTOMATED]: Prettier Code Styling
sam-gc Apr 17, 2020
2749d1e
Addressing PR feedback
sam-gc Apr 17, 2020
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
6 changes: 5 additions & 1 deletion packages-exp/auth-exp/src/core/persistence/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,12 @@ export enum PersistenceType {
NONE = 'NONE'
}

export interface PersistedBlob {
[key: string]: unknown;
}

export interface Instantiator<T> {
(blob: { [key: string]: unknown }): T;
(blob: PersistedBlob): T;
}

export type PersistenceValue = PersistenceType | User;
Expand Down
5 changes: 3 additions & 2 deletions packages-exp/auth-exp/src/core/persistence/indexed_db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ import {
Persistence,
PersistenceType,
PersistenceValue,
Instantiator
Instantiator,
PersistedBlob
} from '.';

const STORAGE_AVAILABLE_KEY_ = '__sak';
Expand All @@ -29,7 +30,7 @@ const DB_VERSION = 1;
const DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';
const DB_DATA_KEYPATH = 'fbase_key';

type DBValue = { [key: string]: unknown } | string;
type DBValue = PersistedBlob | string;

interface DBObject {
[DB_DATA_KEYPATH]: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
/**
* @license
* Copyright 2019 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 sinon from 'sinon';
import * as chai from 'chai';
import { inMemoryPersistence } from './in_memory';
import { PersistenceType, Persistence, Instantiator } from '.';
import { expect } from 'chai';
import { testUser, mockAuth } from '../../../test/mock_auth';
import { PersistenceUserManager } from './persistence_user_manager';
import * as sinonChai from 'sinon-chai';
import { UserImpl } from '../user/user_impl';

chai.use(sinonChai);

function makePersistence(
type = PersistenceType.NONE
): {
persistence: Persistence;
stub: sinon.SinonStubbedInstance<Persistence>;
} {
const persistence: Persistence = {
type,
isAvailable: () => Promise.resolve(true),
set: async () => {},
get() {
return Promise.resolve(null);
},
remove: async () => {}
};

const stub = sinon.stub(persistence);
return { persistence, stub };
}

describe('core/persistence/persistence_user_manager', () => {
describe('create', () => {
it('defaults to inMemory if no list provided', async () => {
const manager = await PersistenceUserManager.create(mockAuth, []);
expect(manager.persistence).to.eq(inMemoryPersistence);
});

it('searches in order for a user', async () => {
const a = makePersistence();
const b = makePersistence();
const c = makePersistence();
const search = [a.persistence, b.persistence, c.persistence];
b.stub.get.returns(Promise.resolve(testUser('uid')));

const out = await PersistenceUserManager.create(mockAuth, search);
expect(out.persistence).to.eq(b.persistence);
expect(a.stub.get).to.have.been.calledOnce;
expect(b.stub.get).to.have.been.calledOnce;
expect(c.stub.get).not.to.have.been.called;
});

it('uses default user key if none provided', async () => {
const { stub, persistence } = makePersistence();
await PersistenceUserManager.create(mockAuth, [persistence]);
expect(stub.get).to.have.been.calledWith(
'firebase:authUser:test-api-key:test-app'
);
});

it('uses user key if provided', async () => {
const { stub, persistence } = makePersistence();
await PersistenceUserManager.create(
mockAuth,
[persistence],
'redirectUser'
);
expect(stub.get).to.have.been.calledWith(
'firebase:redirectUser:test-api-key:test-app'
);
});

it('returns zeroth persistence if all else fails', async () => {
const a = makePersistence();
const b = makePersistence();
const c = makePersistence();
const search = [a.persistence, b.persistence, c.persistence];
const out = await PersistenceUserManager.create(mockAuth, search);
expect(out.persistence).to.eq(a.persistence);
expect(a.stub.get).to.have.been.calledOnce;
expect(b.stub.get).to.have.been.calledOnce;
expect(c.stub.get).to.have.been.called;
});
});

describe('manager methods', () => {
let persistenceStub: sinon.SinonStubbedInstance<Persistence>;
let manager: PersistenceUserManager;

beforeEach(async () => {
const { persistence, stub } = makePersistence(PersistenceType.SESSION);
persistenceStub = stub;
manager = await PersistenceUserManager.create(mockAuth, [persistence]);
});

it('#setCurrentUser calls underlying persistence w/ key', async () => {
const user = testUser('uid');
await manager.setCurrentUser(user);
expect(persistenceStub.set).to.have.been.calledWith(
'firebase:authUser:test-api-key:test-app',
user
);
});

it('#removeCurrentUser calls underlying persistence', async () => {
await manager.removeCurrentUser();
expect(persistenceStub.remove).to.have.been.calledWith(
'firebase:authUser:test-api-key:test-app'
);
});

it('#getCurrentUser calls with instantiator', async () => {
const rawObject = {};
const userImplStub = sinon.stub(UserImpl, 'fromPlainObject');
persistenceStub.get.callsFake((_: string, cb?: Instantiator<any>) => {
// Call through to the callback, to exercise the instantiator
// provided in PersistenceUserManager
return cb!(rawObject);
});

await manager.getCurrentUser();
expect(userImplStub).to.have.been.calledWith(mockAuth, rawObject);

userImplStub.restore();
});

it('#savePersistenceForRedirect calls through', async () => {
await manager.savePersistenceForRedirect();
expect(persistenceStub.set).to.have.been.calledWith(
'firebase:persistence:test-api-key:test-app',
'SESSION'
);
});

describe('#setPersistence', () => {
it('returns immediately if types match', async () => {
const { persistence: nextPersistence } = makePersistence(
PersistenceType.SESSION
);
const spy = sinon.spy(manager, 'getCurrentUser');
await manager.setPersistence(nextPersistence);
expect(spy).not.to.have.been.called;
spy.restore();
});

it('removes current user & sets it in the new persistene', async () => {
const {
persistence: nextPersistence,
stub: nextStub
} = makePersistence();
const user = testUser('uid');
persistenceStub.get.returns(Promise.resolve(user));

await manager.setPersistence(nextPersistence);
expect(persistenceStub.get).to.have.been.called;
expect(persistenceStub.remove).to.have.been.called;
expect(nextStub.set).to.have.been.calledWith(
'firebase:authUser:test-api-key:test-app',
user
);
});
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/**
* @license
* Copyright 2019 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 { Persistence, PersistedBlob } from '../persistence';
import { User } from '../../model/user';
import { ApiKey, AppName, Auth } from '../../model/auth';
import { inMemoryPersistence } from './in_memory';
import { UserImpl } from '../user/user_impl';

export const AUTH_USER_KEY_NAME_ = 'authUser';
export const PERSISTENCE_KEY_NAME_ = 'persistence';
const PERSISTENCE_NAMESPACE_ = 'firebase';

export function persistenceKeyName_(
Copy link
Member

@Feiyang1 Feiyang1 Apr 17, 2020

Choose a reason for hiding this comment

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

I don't think we have an official rule on prefix _ vs suffix _ for internal functions/constants yet, but I'd like to establish the convention of using prefix _. @firebase/firestore and @firebase/app are already using prefix _ today and the documentation tool we are going to use will flag functions with @internal annotation without prefix _.
WDYT?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sg, done

Copy link
Member

Choose a reason for hiding this comment

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

nit: change to prefix _

Copy link
Contributor Author

Choose a reason for hiding this comment

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

woops done

key: string,
apiKey: ApiKey,
appName: AppName
): string {
return `${PERSISTENCE_NAMESPACE_}:${key}:${apiKey}:${appName}`;
}

export class PersistenceUserManager {
private readonly fullUserKey: string;
private readonly fullPersistenceKey: string;
private constructor(
public persistence: Persistence,
private readonly auth: Auth,
private readonly userKey: string
) {
const { config, name } = this.auth;
this.fullUserKey = persistenceKeyName_(this.userKey, config.apiKey, name);
this.fullPersistenceKey = persistenceKeyName_(
PERSISTENCE_KEY_NAME_,
config.apiKey,
name
);
}

setCurrentUser(user: User): Promise<void> {
return this.persistence.set(this.fullUserKey, user);
}

getCurrentUser(): Promise<User | null> {
return this.persistence.get<User>(this.fullUserKey, (blob: PersistedBlob) =>
UserImpl.fromPlainObject(this.auth, blob)
);
}

removeCurrentUser(): Promise<void> {
return this.persistence.remove(this.fullUserKey);
}

savePersistenceForRedirect(): Promise<void> {
return this.persistence.set(this.fullPersistenceKey, this.persistence.type);
}

async setPersistence(newPersistence: Persistence): Promise<void> {
if (this.persistence.type === newPersistence.type) {
return;
}

const currentUser = await this.getCurrentUser();
await this.removeCurrentUser();

this.persistence = newPersistence;

if (currentUser) {
return this.setCurrentUser(currentUser);
}
}

static async create(
auth: Auth,
persistenceHierarchy: Persistence[],
userKey = AUTH_USER_KEY_NAME_
): Promise<PersistenceUserManager> {
if (!persistenceHierarchy.length) {
return new PersistenceUserManager(inMemoryPersistence, auth, userKey);
}

const key = persistenceKeyName_(userKey, auth.config.apiKey, auth.name);
for (const persistence of persistenceHierarchy) {
if (await persistence.get<User>(key)) {
return new PersistenceUserManager(persistence, auth, userKey);
}
}

// Check all the available storage options.
// TODO: Migrate from local storage to indexedDB
// TODO: Clear other forms once one is found

// All else failed, fall back to zeroth persistence
// TODO: Modify this to support non-browser devices
return new PersistenceUserManager(persistenceHierarchy[0], auth, userKey);
}
}
47 changes: 47 additions & 0 deletions packages-exp/auth-exp/src/core/user/token_manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import * as chaiAsPromised from 'chai-as-promised';
import { createSandbox } from 'sinon';
import { IdTokenResponse } from '../../model/id_token';
import { StsTokenManager, TOKEN_REFRESH_BUFFER_MS } from './token_manager';
import { FirebaseError } from '@firebase/util';

use(chaiAsPromised);

Expand Down Expand Up @@ -110,4 +111,50 @@ describe('core/user/token_manager', () => {
expect(tokens.refreshToken).to.eq('refresh');
});
});

describe('fromPlainObject', () => {
const errorString =
'Firebase: An internal AuthError has occurred. (auth/internal-error).';

it('throws if refresh token is not a string', () => {
expect(() =>
StsTokenManager.fromPlainObject('app', {
refreshToken: 45,
accessToken: 't',
expirationTime: 3
})
).to.throw(FirebaseError, errorString);
});

it('throws if access token is not a string', () => {
expect(() =>
StsTokenManager.fromPlainObject('app', {
refreshToken: 't',
accessToken: 45,
expirationTime: 3
})
).to.throw(FirebaseError, errorString);
});

it('throws if expiration time is not a number', () => {
expect(() =>
StsTokenManager.fromPlainObject('app', {
refreshToken: 't',
accessToken: 't',
expirationTime: 'lol'
})
).to.throw(FirebaseError, errorString);
});

it('builds an object correctly', () => {
const manager = StsTokenManager.fromPlainObject('app', {
refreshToken: 'r',
accessToken: 'a',
expirationTime: 45
});
expect(manager.accessToken).to.eq('a');
expect(manager.refreshToken).to.eq('r');
expect(manager.expirationTime).to.eq(45);
});
});
});
Loading