Skip to content

Commit 7b0c2dd

Browse files
committed
API Method
1 parent ff14e14 commit 7b0c2dd

File tree

2 files changed

+65
-29
lines changed

2 files changed

+65
-29
lines changed

packages-exp/auth-exp/src/api/index.ts

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,12 @@
1616
*/
1717

1818
import { FirebaseError, querystring } from '@firebase/util';
19-
import { AuthErrorCode, AUTH_ERROR_FACTORY } from '../core/errors';
19+
20+
import { AUTH_ERROR_FACTORY, AuthErrorCode } from '../core/errors';
21+
import { Delay } from '../core/util/delay';
2022
import { Auth } from '../model/auth';
2123
import { IdTokenResponse } from '../model/id_token';
22-
import {
23-
JsonError,
24-
ServerError,
25-
ServerErrorMap,
26-
SERVER_ERROR_MAP
27-
} from './errors';
28-
import { Delay } from '../core/util/delay';
24+
import { JsonError, SERVER_ERROR_MAP, ServerError, ServerErrorMap } from './errors';
2925

3026
export enum HttpMethod {
3127
POST = 'POST',
@@ -61,10 +57,9 @@ export async function _performApiRequest<T, V>(
6157
method: HttpMethod,
6258
path: Endpoint,
6359
request?: T,
64-
customErrorMap: Partial<ServerErrorMap<ServerError>> = {}
60+
customErrorMap: Partial<ServerErrorMap<ServerError>> = {},
6561
): Promise<V> {
66-
const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };
67-
try {
62+
return performFetchWithErrorHandling(auth, customErrorMap, () => {
6863
let body = {};
6964
let params = {};
7065
if (request) {
@@ -82,8 +77,7 @@ export async function _performApiRequest<T, V>(
8277
...params
8378
}).slice(1);
8479

85-
const response: Response = await Promise.race<Promise<Response>>([
86-
fetch(
80+
return fetch(
8781
`${auth.config.apiScheme}://${auth.config.apiHost}${path}?${query}`,
8882
{
8983
method,
@@ -94,16 +88,20 @@ export async function _performApiRequest<T, V>(
9488
referrerPolicy: 'no-referrer',
9589
...body
9690
}
97-
),
98-
new Promise((_, reject) =>
99-
setTimeout(() => {
100-
return reject(
101-
AUTH_ERROR_FACTORY.create(AuthErrorCode.TIMEOUT, {
102-
appName: auth.name
103-
})
104-
);
105-
}, DEFAULT_API_TIMEOUT_MS.get())
106-
)
91+
);
92+
});
93+
}
94+
95+
export async function performFetchWithErrorHandling<V>(
96+
auth: Auth,
97+
customErrorMap: Partial<ServerErrorMap<ServerError>>,
98+
fetchFn: () => Promise<Response>,
99+
): Promise<V> {
100+
const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };
101+
try {
102+
const response: Response = await Promise.race<Promise<Response>>([
103+
fetchFn(),
104+
makeNetworkTimeout(auth.name),
107105
]);
108106
if (response.ok) {
109107
return response.json();
@@ -154,3 +152,15 @@ export async function _performSignInRequest<T, V extends IdTokenResponse>(
154152

155153
return serverResponse;
156154
}
155+
156+
function makeNetworkTimeout<T>(appName: string): Promise<T> {
157+
return new Promise((_, reject) =>
158+
setTimeout(() => {
159+
return reject(
160+
AUTH_ERROR_FACTORY.create(AuthErrorCode.TIMEOUT, {
161+
appName,
162+
})
163+
);
164+
}, DEFAULT_API_TIMEOUT_MS.get())
165+
)
166+
}

packages-exp/auth-exp/src/core/user/token_manager.ts

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@
1515
* limitations under the License.
1616
*/
1717

18+
import { requestStsToken } from '../../api/authentication/token';
19+
import { Auth } from '../../model/auth';
1820
import { IdTokenResponse } from '../../model/id_token';
21+
import { AUTH_ERROR_FACTORY, AuthErrorCode } from '../errors';
1922
import { PersistedBlob } from '../persistence';
2023
import { assert } from '../util/assert';
2124

@@ -52,15 +55,23 @@ export class StsTokenManager {
5255
this.expirationTime = Date.now() + Number(expiresInSec) * 1000;
5356
}
5457

55-
async getToken(forceRefresh = false): Promise<Tokens> {
58+
async getToken(auth: Auth, forceRefresh = false): Promise<Tokens|null> {
5659
if (!forceRefresh && this.accessToken && !this.isExpired) {
57-
return {
58-
accessToken: this.accessToken,
59-
refreshToken: this.refreshToken
60-
};
60+
return this.tokens;
6161
}
6262

63-
throw new Error('StsTokenManager: token refresh not implemented');
63+
if (this.accessToken && !this.refreshToken) {
64+
throw AUTH_ERROR_FACTORY.create(AuthErrorCode.TOKEN_EXPIRED, {
65+
appName: auth.name,
66+
});
67+
}
68+
69+
if (!this.refreshToken) {
70+
return null;
71+
}
72+
73+
await this.refresh(auth, this.refreshToken);
74+
return this.tokens;
6475
}
6576

6677
toPlainObject(): object {
@@ -71,6 +82,21 @@ export class StsTokenManager {
7182
};
7283
}
7384

85+
private get tokens(): Tokens {
86+
return {
87+
accessToken: this.accessToken!,
88+
refreshToken: this.refreshToken,
89+
};
90+
}
91+
92+
private async refresh(auth: Auth, refreshToken: string) {
93+
const {access_token, refresh_token, expires_in} = await requestStsToken(auth, refreshToken);
94+
95+
this.accessToken = access_token || null;
96+
this.refreshToken = refresh_token || null;
97+
this.expirationTime = expires_in ? Date.now() + Number(expires_in) * 1000 : null;
98+
}
99+
74100
static fromPlainObject(
75101
appName: string,
76102
object: PersistedBlob

0 commit comments

Comments
 (0)