-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth-service-worker.js
49 lines (42 loc) · 1.59 KB
/
auth-service-worker.js
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
import { initializeApp } from 'firebase/app';
import { getAuth, getIdToken } from 'firebase/auth';
import { getInstallations, getToken } from 'firebase/installations';
// this is set during install
let firebaseConfig;
self.addEventListener('install', (event) => {
// extract firebase config from query string
const serializedFirebaseConfig = new URL(location).searchParams.get(
'firebaseConfig'
);
if (!serializedFirebaseConfig) {
throw new Error(
'Firebase Config object not found in service worker query string.'
);
}
firebaseConfig = JSON.parse(serializedFirebaseConfig);
console.log('Service worker installed with Firebase config', firebaseConfig);
});
self.addEventListener('fetch', (event) => {
const { origin } = new URL(event.request.url);
if (origin !== self.location.origin) return;
event.respondWith(fetchWithFirebaseHeaders(event.request));
});
async function fetchWithFirebaseHeaders(request) {
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const installations = getInstallations(app);
const headers = new Headers(request.headers);
const [authIdToken, installationToken] = await Promise.all([
getAuthIdToken(auth),
getToken(installations),
]);
headers.append('Firebase-Instance-ID-Token', installationToken);
if (authIdToken) headers.append('Authorization', `Bearer ${authIdToken}`);
const newRequest = new Request(request, { headers });
return await fetch(newRequest);
}
async function getAuthIdToken(auth) {
await auth.authStateReady();
if (!auth.currentUser) return;
return await getIdToken(auth.currentUser);
}