forked from overclocked/gothic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgothic.js
269 lines (229 loc) · 6.34 KB
/
gothic.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
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
// gothic.js
//
// gothic wraps google authentication and authorization api's to make the easy
// things easy. it's quite unnecessary: the google apis are more than adequate
// on their own. i created this because i found the documentation unhelpful in
// solving basic obvious problems.
//
// with this library, it should be easy to trigger sign-in/sign-up events when
// those are required, but to leverage the auto-signin mechanisms when that is
// a better option.
//
// most importantly, this offers a clean integration between ui
import jwt_decode from "jwt-decode";
/**
* The library methods:
*/
export default {
load, // Load all required google libraries from google
recognize, // test to see if the user is one we recognize
button, // construct sign-in/sign-up button
onetap, // institute onetap sign-in flow
observe, // observe gothic for events
unobserve, // stop observing gothic for events
signout, // sign out of google for this app.
revoke, // revoke the users credentials (presumably upon their request)
user // return the user details.
};
/**
* Structures used by the module.
*/
let google; // Google's GIS libraries
let gapi; // Google's API libraries
/**
* Maintain state for the app.
*/
const state = {
prev: false,
loaded: false,
cid: null,
key: null,
scope: null,
discovery: null,
user: null
};
const obs = []; // Observers, listening for actionable events.
/* ------------------------------------------------------------------------- *\
Public Implementation
\* ------------------------------------------------------------------------- */
function load(clientId, apiKey, scope, discovery) {
state.cid = clientId;
state.key = apiKey;
state.scope = scope;
state.discovery = discovery;
state.prev = window.localStorage.getItem(`gothic-id`) ? true : false;
_load_libaries();
}
function recognize() {
return state.prev;
}
function observe(cb) {
obs.push(cb);
}
function button(parent_id, params = {}) {
const ctr = document.getElementById(parent_id);
if (!ctr) {
throw(new Error(`No container for signin button: '${parent_id}' `));
}
const options = {
type: 'standard',
theme: 'outline',
size: 'medium',
shape: 'pill',
...params,
};
google.accounts.id.renderButton(
ctr,
options
);
}
function onetap() {
function _handle_prompt_events(evt) {
if (evt.isNotDisplayed()) {
if (evt.getNotDisplayedReason() === 'suppressed_by_user') {
_disable();
_notify('onetap_suppressed');
}
if (evt.getNotDisplayedReason() === 'unknown_reason') {
_notify('onetap_failed'); // possibly 1password extension blocking onetap
}
}
if (evt.isSkippedMoment()) {
_notify('onetap_suppressed');
}
}
google.accounts.id.prompt(_handle_prompt_events);
}
function unobserve(cb) {
for(let i=0; i < obs.length; i++) {
if (obs[i] == cb) {
obs.splice(i,1);
break;
}
}
}
function signout() {
_disable();
_notify('signout');
}
function revoke() {
google.accounts.id.revoke(state.user.email, done => {
_disable();
_notify('revoke');
});
}
function user() {
return state.user;
}
/* ------------------------------------------------------------------------- *\
Private Methods
\* ------------------------------------------------------------------------- */
/**
* Ensure that the module is cleared of all prior knowledge of user.
*/
function _disable() {
state.user = null;
window.localStorage.removeItem(`gothic-id`);
google.accounts.id.disableAutoSelect();
}
/**
* Attempt to authorize the scopes required.
*/
function _authorize() {
return new Promise((res,rej) => {
state.tok_client = google.accounts.oauth2.initTokenClient({
client_id: state.cid,
scope: state.scope,
hint: state.user.email,
callback: (response) => {
if (!response.access_token) {
return rej('authorization-failed');
}
res();
}
});
state.tok_client.requestAccessToken({prompt: ''});
});
}
/**
* Load, AND configure, Google's libraries.
*/
function _load_libaries() {
let goog_ready = false;
let gapi_ready = false;
let pass;
let fail;
let ready = new Promise((res, rej) => {
pass = res;
fail = rej;
});
function _all_ready() {
if (goog_ready && gapi_ready) {
pass();
_notify('loaded');
}
}
function _gapi_setup() {
gapi = window.gapi;
gapi.load('client', async() => {
await gapi.client.init({
apiKey: state.key,
discoveryDocs: Array.isArray(state.discovery) ? state.discovery : [ state.discovery ],
});
gapi_ready = true;
_all_ready();
});
}
function _goog_ready() {
google = window.google;
google.accounts.id.initialize({
client_id: state.cid,
auto_select: true,
callback: _on_response
});
goog_ready = true;
_all_ready();
}
// Identity Library
const googscr = document.createElement('script');
googscr.type = 'text/javascript';
googscr.src = 'https://accounts.google.com/gsi/client';
googscr.defer = true;
googscr.onload = _goog_ready;
googscr.onerror = fail;
document.getElementsByTagName('head')[0].appendChild(googscr);
const gapiscr = document.createElement('script');
gapiscr.type = 'text/javascript';
gapiscr.src = 'https://apis.google.com/js/api.js';
gapiscr.defer = true;
gapiscr.onload = _gapi_setup;
gapiscr.onerror = fail;
document.getElementsByTagName('head')[0].appendChild(gapiscr);
return ready;
}
function _notify(type, user = null, token = null) {
obs.forEach((fn) => { fn(type,user,token); });
}
async function _on_response(r) {
state.user = null;
let event_type = 'unknown';
let token = null;
if (r && r.credential) {
try {
token = r.credential;
let rawdata = jwt_decode(token);
state.user = (({ email, family_name, given_name, picture, name, sub }) => ({ email, family_name, given_name, picture, name, sub }))(rawdata);
await _authorize();
window.localStorage.setItem('gothic-id', 'loaded');
event_type = 'signin';
} catch (err) {
if (err === 'auth-failed') {
event_type = 'auth-failed';
} else {
console.log(err);
event_type = 'error';
}
}
}
_notify(event_type, state.user, token);
}