-
Notifications
You must be signed in to change notification settings - Fork 875
/
index.ts
146 lines (131 loc) · 4.74 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/**
* @license
* Copyright 2021 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 { FirebaseApp, getApp, _getProvider } from '@firebase/app';
import {
initializeAuth,
beforeAuthStateChanged,
onIdTokenChanged,
connectAuthEmulator
} from '..';
import { registerAuth } from '../core/auth/register';
import { ClientPlatform } from '../core/util/version';
import { browserLocalPersistence } from './persistence/local_storage';
import { browserSessionPersistence } from './persistence/session_storage';
import { indexedDBLocalPersistence } from './persistence/indexed_db';
import { browserPopupRedirectResolver } from './popup_redirect';
import { Auth, User } from '../model/public_types';
import { getDefaultEmulatorHost, getExperimentalSetting } from '@firebase/util';
import { _setExternalJSProvider } from './load_js';
import { _createError } from '../core/util/assert';
import { AuthErrorCode } from '../core/errors';
const DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;
const authIdTokenMaxAge =
getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;
let lastPostedIdToken: string | undefined | null = null;
const mintCookieFactory = (url: string) => async (user: User | null) => {
const idTokenResult = user && (await user.getIdTokenResult());
const idTokenAge =
idTokenResult &&
(new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1_000;
if (idTokenAge && idTokenAge > authIdTokenMaxAge) {
return;
}
// Specifically trip null => undefined when logged out, to delete any existing cookie
const idToken = idTokenResult?.token;
if (lastPostedIdToken === idToken) {
return;
}
lastPostedIdToken = idToken;
await fetch(url, {
method: idToken ? 'POST' : 'DELETE',
headers: idToken
? {
'Authorization': `Bearer ${idToken}`
}
: {}
});
};
/**
* Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.
* If no instance exists, initializes an Auth instance with platform-specific default dependencies.
*
* @param app - The Firebase App.
*
* @public
*/
export function getAuth(app: FirebaseApp = getApp()): Auth {
const provider = _getProvider(app, 'auth');
if (provider.isInitialized()) {
return provider.getImmediate();
}
const auth = initializeAuth(app, {
popupRedirectResolver: browserPopupRedirectResolver,
persistence: [
indexedDBLocalPersistence,
browserLocalPersistence,
browserSessionPersistence
]
});
const authTokenSyncPath = getExperimentalSetting('authTokenSyncURL');
// Only do the Cookie exchange in a secure context
if (
authTokenSyncPath &&
typeof isSecureContext === 'boolean' &&
isSecureContext
) {
// Don't allow urls (XSS possibility), only paths on the same domain
const authTokenSyncUrl = new URL(authTokenSyncPath, location.origin);
if (location.origin === authTokenSyncUrl.origin) {
const mintCookie = mintCookieFactory(authTokenSyncUrl.toString());
beforeAuthStateChanged(auth, mintCookie, () =>
mintCookie(auth.currentUser)
);
onIdTokenChanged(auth, user => mintCookie(user));
}
}
const authEmulatorHost = getDefaultEmulatorHost('auth');
if (authEmulatorHost) {
connectAuthEmulator(auth, `http://${authEmulatorHost}`);
}
return auth;
}
function getScriptParentElement(): HTMLDocument | HTMLHeadElement {
return document.getElementsByTagName('head')?.[0] ?? document;
}
_setExternalJSProvider({
loadJS(url: string): Promise<Event> {
// TODO: consider adding timeout support & cancellation
return new Promise((resolve, reject) => {
const el = document.createElement('script');
el.setAttribute('src', url);
el.onload = resolve;
el.onerror = e => {
const error = _createError(AuthErrorCode.INTERNAL_ERROR);
error.customData = e as unknown as Record<string, unknown>;
reject(error);
};
el.type = 'text/javascript';
el.charset = 'UTF-8';
getScriptParentElement().appendChild(el);
});
},
gapiScript: 'https://apis.google.com/js/api.js',
recaptchaV2Script: 'https://www.google.com/recaptcha/api.js',
recaptchaEnterpriseScript:
'https://www.google.com/recaptcha/enterprise.js?render='
});
registerAuth(ClientPlatform.BROWSER);