-
Notifications
You must be signed in to change notification settings - Fork 2
/
oauth-receiver.html
76 lines (64 loc) · 2.28 KB
/
oauth-receiver.html
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
<script>
/**
* `oauth-receiver`
*
* The second part of the OAuth-Element story, that receives the authentication
* data in the redirected window and sends them back to the window opener via
* `window.postMessage`.
*
* @customElement
*/
class OAuthReceiver extends HTMLElement {
static get is() {
return 'oauth-receiver';
}
connectedCallback() {
if (!this.hasAttribute('manual')) {
this.receive();
window.addEventListener("storage", e => this.receiveStorage(e), true);
}
}
get target() {
const attrValue = this.getAttribute('target');
return this._target ? this._target : (attrValue ? attrValue : '*')
}
set target(val) {
this._target = val;
}
/**
* Attempts to read OAuth2 authentication parameters and sends them off
* to the window opener through `window.postMessage`.
*/
receive() {
const query = new URLSearchParams(document.location.search);
const code = query.get('code');
const error = query.get('error');
const state = query.get('state');
if(!code) {
return;
}
const authData = { code, error, state };
if (window.opener) {
window.opener.postMessage(authData, this.target);
return false;
}
console.log("Missing window.opener. Going through localStorage");
localStorage.setItem('tempOAuthResult', JSON.stringify(authData));
// Close when in Electron
if(window && window.process && window.process.type) {
const { remote } = require('electron');
const window = remote.getCurrentWindow();
window.close();
}
}
receiveStorage(e) {
if (e.key !== 'tempOAuthResult') {
console.debug(`Received wrong storage event key ${e.key}`);
return;
}
const data = JSON.parse(e.newValue);
window.parent.postMessage(data, this.target);
}
}
customElements.define(OAuthReceiver.is, OAuthReceiver);
</script>