-
Notifications
You must be signed in to change notification settings - Fork 938
Add initial user object implementation #2896
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
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
34ae33a
Initial user object implementation
sam-gc 4a3a125
[AUTOMATED]: Prettier Code Styling
sam-gc af1571a
Add token manager
sam-gc 50bfb92
[AUTOMATED]: Prettier Code Styling
sam-gc b62faba
Address comments in token manager, restore yarn.lock
sam-gc 09f95ef
[AUTOMATED]: Prettier Code Styling
sam-gc c93391f
parseInt() -> Number()
sam-gc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
105 changes: 105 additions & 0 deletions
105
packages-exp/auth-exp/src/core/user/token_manager.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
/** | ||
* @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 { StsTokenManager, DATE_GENERATOR } from './token_manager'; | ||
import { IdTokenResponse } from '../../model/id_token'; | ||
import { createSandbox } from 'sinon'; | ||
|
||
use(chaiAsPromised); | ||
|
||
const sandbox = createSandbox(); | ||
|
||
describe('core/user/token_manager', () => { | ||
let stsTokenManager: StsTokenManager; | ||
let now: number; | ||
|
||
beforeEach(() => { | ||
stsTokenManager = new StsTokenManager(); | ||
now = Date.now(); | ||
sandbox.stub(DATE_GENERATOR, 'now').returns(now); | ||
}); | ||
|
||
afterEach(() => sandbox.restore()); | ||
|
||
describe('#isExpired', () => { | ||
it('is true if past expiration time', () => { | ||
stsTokenManager.expirationTime = 1; // Ancient history | ||
expect(stsTokenManager.isExpired).to.eq(true); | ||
}); | ||
|
||
it('is true if exp is in future but within buffer', () => { | ||
// Buffer is 30_000 | ||
stsTokenManager.expirationTime = now + 20_000; | ||
expect(stsTokenManager.isExpired).to.eq(true); | ||
}); | ||
|
||
it('is fals if exp is far enough in future', () => { | ||
stsTokenManager.expirationTime = now + 40_000; | ||
expect(stsTokenManager.isExpired).to.eq(false); | ||
}); | ||
}); | ||
|
||
describe('#updateFromServerResponse', () => { | ||
it('sets all the fields correctly', () => { | ||
stsTokenManager.updateFromServerResponse({ | ||
idToken: 'id-token', | ||
refreshToken: 'refresh-token', | ||
expiresIn: '60' // From the server this is 30s | ||
} as IdTokenResponse); | ||
|
||
expect(stsTokenManager.expirationTime).to.eq(now + 60_000); | ||
expect(stsTokenManager.accessToken).to.eq('id-token'); | ||
expect(stsTokenManager.refreshToken).to.eq('refresh-token'); | ||
}); | ||
}); | ||
|
||
describe('#getToken', () => { | ||
it('throws if forceRefresh is true', async () => { | ||
Object.assign(stsTokenManager, { | ||
accessToken: 'token', | ||
expirationTime: now + 100_000 | ||
}); | ||
await expect(stsTokenManager.getToken(true)).to.be.rejectedWith(Error); | ||
}); | ||
|
||
it('throws if token is expired', async () => { | ||
Object.assign(stsTokenManager, { | ||
accessToken: 'token', | ||
expirationTime: now - 1 | ||
}); | ||
await expect(stsTokenManager.getToken()).to.be.rejectedWith(Error); | ||
}); | ||
|
||
it('throws if access token is missing', async () => { | ||
await expect(stsTokenManager.getToken()).to.be.rejectedWith(Error); | ||
}); | ||
|
||
it('returns access token if not expired, not refreshing', async () => { | ||
Object.assign(stsTokenManager, { | ||
accessToken: 'token', | ||
refreshToken: 'refresh', | ||
expirationTime: now + 100_000 | ||
}); | ||
|
||
const tokens = await stsTokenManager.getToken(); | ||
expect(tokens.accessToken).to.eq('token'); | ||
expect(tokens.refreshToken).to.eq('refresh'); | ||
}); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
/** | ||
* @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 { IdTokenResponse } from '../../model/id_token'; | ||
|
||
/** | ||
* The number of milliseconds before the official expiration time of a token | ||
* to refresh that token, to provide a buffer for RPCs to complete. | ||
*/ | ||
const TOKEN_REFRESH_BUFFER_MS = 30_000; | ||
|
||
export interface Tokens { | ||
accessToken: string; | ||
refreshToken: string | null; | ||
} | ||
|
||
export const DATE_GENERATOR = { | ||
sam-gc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
now: () => Date.now() | ||
}; | ||
|
||
export class StsTokenManager { | ||
refreshToken: string | null = null; | ||
sam-gc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
accessToken: string | null = null; | ||
expirationTime: number | null = null; | ||
|
||
get isExpired(): boolean { | ||
return ( | ||
!this.expirationTime || | ||
DATE_GENERATOR.now() > this.expirationTime - TOKEN_REFRESH_BUFFER_MS | ||
); | ||
} | ||
|
||
updateFromServerResponse({ | ||
idToken, | ||
refreshToken, | ||
expiresIn | ||
sam-gc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}: IdTokenResponse): void { | ||
this.refreshToken = refreshToken; | ||
this.accessToken = idToken; | ||
this.expirationTime = | ||
DATE_GENERATOR.now() + Number.parseInt(expiresIn, 10) * 1000; | ||
} | ||
|
||
async getToken(forceRefresh = false): Promise<Tokens> { | ||
if (!forceRefresh && this.accessToken && !this.isExpired) { | ||
return { | ||
accessToken: this.accessToken, | ||
refreshToken: this.refreshToken | ||
}; | ||
} | ||
|
||
throw new Error('StsTokenManager: token refresh not implemented'); | ||
} | ||
|
||
// TODO: There are a few more methods in here that need implemented | ||
sam-gc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
/** | ||
* @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 { UserImpl } from './user_impl'; | ||
import { mockAuth } from '../../../test/mock_auth'; | ||
import { StsTokenManager } from './token_manager'; | ||
import { IdTokenResponse } from '../../model/id_token'; | ||
|
||
use(chaiAsPromised); | ||
|
||
describe('core/user/user_impl', () => { | ||
const auth = mockAuth('foo', 'i-am-the-api-key'); | ||
let stsTokenManager: StsTokenManager; | ||
|
||
beforeEach(() => { | ||
stsTokenManager = new StsTokenManager(); | ||
}); | ||
|
||
describe('constructor', () => { | ||
it('attaches required fields', () => { | ||
const user = new UserImpl({ uid: 'uid', auth, stsTokenManager }); | ||
expect(user.auth).to.eq(auth); | ||
expect(user.uid).to.eq('uid'); | ||
}); | ||
|
||
it('attaches optional fields if provided', () => { | ||
const user = new UserImpl({ | ||
uid: 'uid', | ||
auth, | ||
stsTokenManager, | ||
displayName: 'displayName', | ||
email: 'email', | ||
phoneNumber: 'phoneNumber', | ||
photoURL: 'photoURL' | ||
}); | ||
|
||
expect(user.displayName).to.eq('displayName'); | ||
expect(user.email).to.eq('email'); | ||
expect(user.phoneNumber).to.eq('phoneNumber'); | ||
expect(user.photoURL).to.eq('photoURL'); | ||
}); | ||
|
||
it('sets optional fields to null if not provided', () => { | ||
const user = new UserImpl({ uid: 'uid', auth, stsTokenManager }); | ||
expect(user.displayName).to.eq(null); | ||
expect(user.email).to.eq(null); | ||
expect(user.phoneNumber).to.eq(null); | ||
expect(user.photoURL).to.eq(null); | ||
}); | ||
}); | ||
|
||
describe('#getIdToken', () => { | ||
it('returns the raw token if refresh tokens are in order', async () => { | ||
stsTokenManager.updateFromServerResponse({ | ||
idToken: 'id-token-string', | ||
refreshToken: 'refresh-token-string', | ||
expiresIn: '100000' | ||
} as IdTokenResponse); | ||
|
||
const user = new UserImpl({ uid: 'uid', auth, stsTokenManager }); | ||
const token = await user.getIdToken(); | ||
expect(token).to.eq('id-token-string'); | ||
expect(user.refreshToken).to.eq('refresh-token-string'); | ||
}); | ||
|
||
it('throws if refresh is required', async () => { | ||
const user = new UserImpl({ uid: 'uid', auth, stsTokenManager }); | ||
await expect(user.getIdToken()).to.be.rejectedWith(Error); | ||
avolkovi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}); | ||
}); | ||
|
||
describe('#getIdTokenResult', () => { | ||
it('throws', async () => { | ||
const user = new UserImpl({ uid: 'uid', auth, stsTokenManager }); | ||
await expect(user.getIdTokenResult()).to.be.rejectedWith(Error); | ||
}); | ||
}); | ||
|
||
describe('#reload', () => { | ||
it('throws', () => { | ||
const user = new UserImpl({ uid: 'uid', auth, stsTokenManager }); | ||
expect(() => user.reload()).to.throw(); | ||
}); | ||
}); | ||
|
||
describe('#delete', () => { | ||
it('throws', () => { | ||
const user = new UserImpl({ uid: 'uid', auth, stsTokenManager }); | ||
expect(() => user.delete()).to.throw(); | ||
}); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
/** | ||
* @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 { User } from '../../model/user'; | ||
import { Auth } from '../../model/auth'; | ||
import { IdTokenResult } from '../../model/id_token'; | ||
import { ProviderId } from '../providers'; | ||
import { StsTokenManager } from './token_manager'; | ||
|
||
export interface UserParameters { | ||
uid: string; | ||
auth: Auth; | ||
stsTokenManager: StsTokenManager; | ||
|
||
displayName?: string; | ||
email?: string; | ||
phoneNumber?: string; | ||
photoURL?: string; | ||
} | ||
|
||
export class UserImpl implements User { | ||
// For the user object, provider is always Firebase. | ||
readonly providerId = ProviderId.FIREBASE; | ||
stsTokenManager: StsTokenManager; | ||
refreshToken = ''; | ||
|
||
uid: string; | ||
auth: Auth; | ||
|
||
// Optional fields from UserInfo | ||
displayName: string | null; | ||
email: string | null; | ||
phoneNumber: string | null; | ||
photoURL: string | null; | ||
|
||
constructor({ uid, auth, stsTokenManager, ...opt }: UserParameters) { | ||
this.uid = uid; | ||
this.auth = auth; | ||
this.stsTokenManager = stsTokenManager; | ||
this.displayName = opt.displayName || null; | ||
this.email = opt.email || null; | ||
this.phoneNumber = opt.phoneNumber || null; | ||
this.photoURL = opt.photoURL || null; | ||
} | ||
|
||
async getIdToken(forceRefresh?: boolean): Promise<string> { | ||
const { refreshToken, accessToken } = await this.stsTokenManager.getToken( | ||
forceRefresh | ||
); | ||
this.refreshToken = refreshToken || ''; | ||
|
||
// TODO: notify listeners at this point | ||
return accessToken; | ||
} | ||
|
||
async getIdTokenResult(forceRefresh?: boolean): Promise<IdTokenResult> { | ||
await this.getIdToken(forceRefresh); | ||
// TODO: Parse token | ||
throw new Error('Method not implemented'); | ||
} | ||
|
||
reload(): Promise<void> { | ||
throw new Error('Method not implemented.'); | ||
} | ||
|
||
delete(): Promise<void> { | ||
throw new Error('Method not implemented.'); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.