-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathfirebase.js
More file actions
271 lines (231 loc) · 7.49 KB
/
firebase.js
File metadata and controls
271 lines (231 loc) · 7.49 KB
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import Cookies from 'js-cookie';
import get from 'lodash-es/get';
import isEmpty from 'lodash-es/isEmpty';
import isEqual from 'lodash-es/isEqual';
import isNil from 'lodash-es/isNil';
import isNull from 'lodash-es/isNull';
import map from 'lodash-es/map';
import omit from 'lodash-es/omit';
import values from 'lodash-es/values';
import uuid from 'uuid/v4';
import once from 'lodash-es/once';
import {firebase} from '@firebase/app';
import '@firebase/auth';
import {bugsnagClient} from '../util/bugsnag';
import config from '../config';
import retryingFailedImports from '../util/retryingFailedImports';
import {getGapiSync, SCOPES as GOOGLE_SCOPES} from '../services/gapi';
const GITHUB_SCOPES = ['gist', 'public_repo', 'read:user', 'user:email'];
const VALID_SESSION_UID_COOKIE = 'firebaseAuth.validSessionUid';
const SESSION_TTL_MS = 5 * 60 * 1000;
const githubAuthProvider = new firebase.auth.GithubAuthProvider();
for (const scope of GITHUB_SCOPES) {
githubAuthProvider.addScope(scope);
}
const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
for (const scope of GOOGLE_SCOPES) {
googleAuthProvider.addScope(scope);
}
const {auth, loadDatabase} = buildFirebase();
async function loadDatabaseSdk() {
return retryingFailedImports(() =>
import(
/* webpackChunkName: "mainAsync" */
'@firebase/database',
),
);
}
function buildFirebase(appName = undefined) {
const app = firebase.initializeApp({
apiKey: config.firebaseApiKey,
authDomain: `${config.firebaseApp}.firebaseapp.com`,
databaseURL: `https://${config.firebaseApp}.firebaseio.com`,
}, appName);
return {
auth: firebase.auth(app),
loadDatabase: once(async() => {
await loadDatabaseSdk();
return firebase.database(app);
}),
};
}
export function onAuthStateChanged(listener) {
const unsubscribe = auth.onAuthStateChanged(async(user) => {
if (isNull(user)) {
listener({user: null});
} else {
listener(await decorateUserWithCredentials(user));
}
});
return unsubscribe;
}
async function workspace(uid) {
const database = await loadDatabase();
return database.ref(`workspaces/${uid}`);
}
export async function loadAllProjects(uid) {
const userWorkspace = await workspace(uid);
const projects = await userWorkspace.child('projects').once('value');
return values(projects.val() || {});
}
function getProjectforSnapshot(project) {
const snapshotBlacklist = ['externalLocations'];
return omit(project, snapshotBlacklist);
}
export async function createProjectSnapshot(project) {
const snapshotKey = uuid().toString();
const database = await loadDatabase();
const projectForSnapshot = getProjectforSnapshot(project);
await database.ref('snapshots').child(snapshotKey).set(projectForSnapshot);
return snapshotKey;
}
export async function loadProjectSnapshot(snapshotKey) {
const database = await loadDatabase();
const event =
await database.ref('snapshots').child(snapshotKey).once('value');
return event.val();
}
export async function saveProject(uid, project) {
const userWorkspace = await workspace(uid);
await userWorkspace.child('projects').child(project.projectKey).
setWithPriority(project, -Date.now());
}
async function decorateUserWithCredentials(user) {
const database = await loadDatabase();
const credentialEvent =
await database.ref(`authTokens/${user.uid}`).once('value');
const credentials = values(credentialEvent.val() || {});
if (
!isEqual(
map(credentials, 'providerId').sort(),
map(user.providerData, 'providerId').sort(),
)
) {
await auth.signOut();
return {user: null};
}
return {user, credentials};
}
export async function signIn(provider) {
const originalOnerror = window.onerror;
window.onerror = message => message.toLowerCase().includes('network error');
try {
let userCredential;
if (provider === 'github') {
userCredential = await signInWithGithub();
} else if (provider === 'google') {
userCredential = await signInWithGoogle();
}
await saveUserCredential(userCredential);
return userCredential;
} finally {
setTimeout(() => {
window.onerror = originalOnerror;
});
}
}
export async function linkGithub() {
const userCredential =
await auth.currentUser.linkWithPopup(githubAuthProvider);
await saveUserCredential(userCredential);
return userCredential.credential;
}
export async function migrateAccount(inboundAccountCredential) {
const inboundAccountFirebase = buildFirebase('migration');
const {auth: inboundAccountAuth} = inboundAccountFirebase;
try {
await inboundAccountAuth.signInWithCredential(inboundAccountCredential);
const inboundUid = inboundAccountAuth.currentUser.uid;
await logMigration(inboundUid, 'attempt');
const migratedProjects = await migrateProjects(inboundAccountFirebase);
await migrateCredential(inboundAccountCredential, inboundAccountFirebase);
await logMigration(inboundUid, 'success');
return migratedProjects;
} finally {
inboundAccountAuth.app.delete();
}
}
async function migrateCredential(credential, {auth: inboundAccountAuth}) {
await inboundAccountAuth.currentUser.unlink(credential.providerId);
await auth.currentUser.linkWithCredential(credential);
await saveUserCredential({user: auth.currentUser, credential});
}
async function migrateProjects({
auth: inboundAccountAuth,
loadDatabase: loadinboundAccountDatabase,
}) {
const currentAccountDatabase = await loadDatabase();
const inboundAccountDatabase = await loadinboundAccountDatabase();
const allProjectsValue = await inboundAccountDatabase.
ref(`workspaces/${inboundAccountAuth.currentUser.uid}/projects`).
once('value');
if (isNull(allProjectsValue)) {
return [];
}
const allProjects = allProjectsValue.val();
if (isNull(allProjects) || isEmpty(allProjects)) {
return [];
}
await currentAccountDatabase.
ref(`workspaces/${auth.currentUser.uid}/projects`).
update(allProjects);
return values(allProjects);
}
async function logMigration(inboundUid, eventName) {
bugsnagClient.notify(
new Error(`Account migration ${eventName}`),
{
metaData: {migration: {inboundUid}},
severity: 'info',
},
);
}
async function signInWithGithub() {
return auth.signInWithPopup(githubAuthProvider);
}
async function signInWithGoogle() {
const gapi = getGapiSync();
const googleUser =
await gapi.auth2.getAuthInstance().signIn({prompt: 'select_account'});
const googleCredential =
googleAuthProvider.credential(googleUser.getAuthResponse().id_token);
return auth.signInAndRetrieveDataWithCredential(googleCredential);
}
export async function signOut() {
const gapi = getGapiSync();
if (await gapi.auth2.getAuthInstance().isSignedIn.get()) {
gapi.auth2.getAuthInstance().signOut();
}
return auth.signOut();
}
async function saveUserCredential({
user: {uid},
credential,
}) {
const database = await loadDatabase();
await database.
ref(`authTokens/${providerPath(uid, credential.providerId)}`).
set(credential);
}
function providerPath(uid, providerId) {
return `${uid}/${providerId.replace('.', '_')}`;
}
export function startSessionHeartbeat() {
setInterval(setSessionUid, 1000);
}
export function getSessionUid() {
return Cookies.get(VALID_SESSION_UID_COOKIE);
}
export function setSessionUid() {
const uid = get(auth, 'currentUser.uid');
if (!isNil(uid)) {
Cookies.set(
VALID_SESSION_UID_COOKIE,
uid,
{
expires: new Date(Date.now() + SESSION_TTL_MS),
secure: true,
},
);
}
}