-
Notifications
You must be signed in to change notification settings - Fork 946
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
Changes from 14 commits
f6d83b5
efab6d0
b561823
67e46a9
7cc84c1
c9bbfe8
67446ea
afdce7e
ef91d2b
0d8659d
a15679c
4254fac
2711c51
ed0ff67
a1cbef8
f1cfec2
eebc885
1d93a6d
a6338ec
ede366c
8ccb75e
1fce8ba
df6c1d0
cd255da
ea70a8a
2749d1e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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>; | ||
} { | ||
avolkovi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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_( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 _. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sg, done There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: change to prefix _ There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
avolkovi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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) { | ||
avolkovi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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 | ||
sam-gc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// 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); | ||
} | ||
} |
Uh oh!
There was an error while loading. Please reload this page.