/
auth_svc_intercept.js
82 lines (78 loc) · 2.67 KB
/
auth_svc_intercept.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
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
// This snippet file was generated by processing the source file:
// ./auth-next/service-worker-sessions.js
//
// To update the snippets in this file, edit the source and then run
// 'npm run snippets'.
// [START auth_svc_intercept_modular]
const getOriginFromUrl = (url) => {
// https://stackoverflow.com/questions/1420881/how-to-extract-base-url-from-a-string-in-javascript
const pathArray = url.split('/');
const protocol = pathArray[0];
const host = pathArray[2];
return protocol + '//' + host;
};
// Get underlying body if available. Works for text and json bodies.
const getBodyContent = (req) => {
return Promise.resolve().then(() => {
if (req.method !== 'GET') {
if (req.headers.get('Content-Type').indexOf('json') !== -1) {
return req.json()
.then((json) => {
return JSON.stringify(json);
});
} else {
return req.text();
}
}
}).catch((error) => {
// Ignore error.
});
};
self.addEventListener('fetch', (event) => {
/** @type {FetchEvent} */
const evt = event;
const requestProcessor = (idToken) => {
let req = evt.request;
let processRequestPromise = Promise.resolve();
// For same origin https requests, append idToken to header.
if (self.location.origin == getOriginFromUrl(evt.request.url) &&
(self.location.protocol == 'https:' ||
self.location.hostname == 'localhost') &&
idToken) {
// Clone headers as request headers are immutable.
const headers = new Headers();
req.headers.forEach((val, key) => {
headers.append(key, val);
});
// Add ID token to header.
headers.append('Authorization', 'Bearer ' + idToken);
processRequestPromise = getBodyContent(req).then((body) => {
try {
req = new Request(req.url, {
method: req.method,
headers: headers,
mode: 'same-origin',
credentials: req.credentials,
cache: req.cache,
redirect: req.redirect,
referrer: req.referrer,
body,
// bodyUsed: req.bodyUsed,
// context: req.context
});
} catch (e) {
// This will fail for CORS requests. We just continue with the
// fetch caching logic below and do not pass the ID token.
}
});
}
return processRequestPromise.then(() => {
return fetch(req);
});
};
// Fetch the resource after checking for the ID token.
// This can also be integrated with existing logic to serve cached files
// in offline mode.
evt.respondWith(getIdTokenPromise().then(requestProcessor, requestProcessor));
});
// [END auth_svc_intercept_modular]