@thzero/library_client_firebase 0.18.21 → 0.18.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/service/index.js CHANGED
@@ -1,455 +1,455 @@
1
- import { initializeApp } from 'firebase/app';
2
- // import { getAuth } from "firebase/auth";
3
- import { getAnalytics } from "firebase/analytics";
4
- import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
5
-
6
- import LibraryClientConstants from '@thzero/library_client/constants';
7
-
8
- import LibraryClientUtility from '@thzero/library_client/utility/index';
9
- import LibraryCommonUtility from '@thzero/library_common/utility/index';
10
- import LibraryMomentUtility from '@thzero/library_common/utility/moment';
11
-
12
- import UserAuthService from '@thzero/library_client/service/auth/user';
13
-
14
- class FirebaseAuthService extends UserAuthService {
15
- constructor() {
16
- super();
17
-
18
- this._auth = null;
19
-
20
- // this._lock = false
21
- this._polling = null;
22
-
23
- this._serviceRouter = null;
24
- }
25
-
26
- async init(injector) {
27
- await super.init(injector);
28
-
29
- this._serviceRouter = this._injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_ROUTER);
30
- }
31
-
32
- async deleteUser(correlationId) {
33
- try {
34
- const user = await this.getExternalUser();
35
- if (!user)
36
- return;
37
-
38
- await user.delete();
39
- await this._serviceUser.resetUser(correlationId);
40
- }
41
- catch (err) {
42
- this._logger.exception('FirebaseAuthService', 'deleteUser', err, correlationId);
43
- throw err;
44
- }
45
- }
46
-
47
- async getExternalUser() {
48
- if (this._auth) {
49
- this._logger.debug('FirebaseAuthService', 'getExternalUser', 'user', this._auth.currentUser);
50
- return this._auth.currentUser;
51
- }
52
- return null;
53
- }
54
-
55
- async initialize(correlationId, router) {
56
- const configExternal = this._config.getExternal();
57
- if (!configExternal)
58
- throw Error('Invalid external config.');
59
- const configFirebase = configExternal.firebase;
60
- if (!configFirebase)
61
- throw Error('Invalid firebase config.');
62
- // initializeApp(configFirebase);
63
- // if (configFirebase.measurementId)
64
- // getAnalytics();
65
- this._initializeFirebase(correlationId, configExternal, configFirebase);
66
-
67
- let outsideResolve;
68
- let outsideReject;
69
- const promiseAuth = new Promise(function(resolve, reject) {
70
- outsideResolve = resolve;
71
- outsideReject = reject;
72
- });
73
-
74
- this._initializeAuth(correlationId, configExternal, configFirebase, outsideResolve, outsideReject);
75
-
76
- this._initializeAnalytics(correlationId, configExternal, configFirebase);
77
-
78
- return promiseAuth;
79
- }
80
-
81
- async isAuthenticated() {
82
- const user = await this.getExternalUser();
83
- this._logger.debug('FirebaseAuthService', 'isAuthenticated', 'user', user);
84
- return LibraryCommonUtility.isNotNull(user);
85
- }
86
-
87
- async onAuthStateChanged(user) {
88
- const correlationId = LibraryCommonUtility.correlationId();
89
- try {
90
- await this.updateExternalUser(correlationId, user, true);
91
- // if (!user)
92
- // return
93
-
94
- await this._serviceUser.setAuthCompleted(correlationId, true);
95
- this._serviceEvent.emit(LibraryClientConstants.EventKeys.Auth.Refresh, user);
96
- }
97
- catch (err) {
98
- this._logger.exception('FirebaseAuthService', 'onAuthStateChanged', err, correlationId);
99
- }
100
-
101
- // try {
102
- // if (!user) {
103
- // if (this._polling)
104
- // clearInterval(this._polling)
105
- // return
106
- // }
107
-
108
- // const self = this
109
- // this._polling = setInterval(async () => {
110
- // await self.refreshToken(self.user, true).then()
111
- // }, 60 * 1000)
112
- // }
113
- // catch (err) {
114
- // this._logger.exception('FirebaseAuthService', 'onAuthStateChanged', err, correlationId)
115
- // }
116
- }
117
-
118
- async refreshToken(correlationId, user, forceRefresh) {
119
- forceRefresh = forceRefresh !== null ? forceRefresh : false;
120
- this._logger.debug('FirebaseAuthService', 'refreshToken', 'forceRefresh', forceRefresh, correlationId);
121
-
122
- try {
123
- this._logger.debug('FirebaseAuthService', 'refreshToken', 'user', user, correlationId);
124
- if (!user) {
125
- await this._serviceUser.setTokenResult(correlationId, null);
126
- await this._serviceUser.setClaims(correlationId, null);
127
- this.announceToken(correlationId, user, null);
128
-
129
- return;
130
- }
131
-
132
- this._logger.debug('FirebaseAuthService', 'refreshToken', 'forceRefresh', forceRefresh, correlationId);
133
- const currentUser = await this.getExternalUser();
134
- this._logger.debug('FirebaseAuthService', 'refreshToken', 'currentUser', currentUser, correlationId);
135
- if (!currentUser)
136
- return;
137
-
138
- if (this._polling)
139
- clearInterval(this._polling);
140
-
141
- let token = null;
142
-
143
- const tokenResult = await this.refreshTokenResult(correlationId, forceRefresh);
144
- if (tokenResult) {
145
- await this._serviceUser.setTokenResult(correlationId, tokenResult);
146
- token = tokenResult.token;
147
- let claims = token != null ? tokenResult.claims : null;
148
- this._logger.debug('FirebaseAuthService', 'refreshToken', 'claims', claims, correlationId);
149
- claims = claims != null ? claims.custom : null;
150
- this._logger.debug('FirebaseAuthService', 'refreshToken', 'claims.custom', claims, correlationId);
151
- await this._serviceUser.setClaims(correlationId, claims);
152
-
153
- this.refreshTokenExpiration(correlationId, tokenResult, user);
154
- }
155
- else {
156
- await this._serviceUser.setTokenResult(correlationId, null);
157
- await this._serviceUser.setClaims(correlationId, null);
158
- }
159
-
160
- await this.announceToken(correlationId, user, token);
161
- }
162
- catch (err) {
163
- this._logger.exception('FirebaseAuthService', 'refreshToken', err, correlationId);
164
- throw err;
165
- }
166
- }
167
-
168
- async refreshTokenExpiration(correlationId, tokenResult, user) {
169
- const expired = LibraryMomentUtility.getDateParse(tokenResult.expirationTime);
170
- const now = LibraryMomentUtility.getDate();
171
- const diff = expired.diff(now);
172
- const min = 5 * 60 * 1000;
173
- if (diff <= min) {
174
- await this.refreshToken(correlationId, await this.getExternalUser(), true).then();
175
- return;
176
- }
177
-
178
- if (this._polling)
179
- clearInterval(this._polling);
180
-
181
- const self = this;
182
- this._polling = setInterval(async () => {
183
- await self.refreshToken(correlationId, user, true).then();
184
- }, diff); // 60 * 1000);
185
- }
186
-
187
- async refreshTokenResult(correlationId, forceRefresh) {
188
- const currentUser = await this.getExternalUser();
189
- if (!currentUser)
190
- return null;
191
- return await currentUser.getIdTokenResult(forceRefresh);
192
- }
193
-
194
- async resolveAuthorization(correlationId, requiresAuthRoles, requiresAuthLogical) {
195
- // const serviceAuth = LibraryClientUtility.$injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_AUTH);
196
- // const serviceLogger = LibraryClientUtility.$injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_LOGGER);
197
- // const serviceSecurity = LibraryClientUtility.$injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_SECURITY);
198
- // const serviceStore = LibraryClientUtility.$injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_STORE);
199
- this._logger.info2('requiresAuth');
200
- let isLoggedIn = await this.isAuthenticated();
201
- this._logger.info2('authorization.isLoggedIn', isLoggedIn);
202
- // console.log('authorization.isLoggedIn', isLoggedIn);
203
- if (!isLoggedIn) {
204
- // Briefly wait for authentication to settle...
205
- let i = 0;
206
- while (await this.sleep(150)) {
207
- if (this._serviceStore.userAuthCompleted) {
208
- this._logger.info2('authorization.userAuthCompleted', userAuthCompleted);
209
- // console.log('authorization.userAuthCompleted', userAuthCompleted);
210
- break;
211
- }
212
- i++;
213
- this._logger.info2('waiting... ' + i);
214
- if (i > 5) {
215
- this._logger.warn2('authorization.userAuthCompleted failed');
216
- break;
217
- }
218
- }
219
- const isLoggedInAuthCompleted = await this.isAuthenticated();
220
- this._logger.info2('authorization.isLoggedIn.userAuthCompleted', isLoggedInAuthCompleted);
221
- // console.log('authorization.isLoggedIn.userAuthCompleted', isLoggedInAuthCompleted);
222
- isLoggedIn = isLoggedInAuthCompleted;
223
- }
224
- this._logger.info2('authorization.isLoggedIn.final', isLoggedIn);
225
- // console.log('authorization.isLoggedIn.final', isLoggedIn);
226
- if (!isLoggedIn) {
227
- this._logger.warn2('authorization.isLoggedIn - failed');
228
- // console.log('authorization.isLoggedIn - failed');
229
- // LibraryClientUtility.$EventBus.on('auth-refresh', (user) => {
230
- // this._logger.debug('auth-refresh', user)
231
- // this._logger.debug('middleware', 'auth-refresh', null, user, correlationId);
232
- // next()
233
- // })
234
- // return
235
- return false;
236
- }
237
-
238
- this._logger.info2('authorization.isLoggedIn - success');
239
- // console.log('authorization.isLoggedIn - success');
240
-
241
- const user = this._serviceUser.user;
242
- let success = true;
243
- // console.log('authorization.requiresAuthRoles', requiresAuthRoles);
244
- this._logger.debug('FirebaseAuthService', 'resolveAuthorization', 'requiresAuthRoles', requiresAuthRoles);
245
- // console.log('authorization.requiresAuthLogical', requiresAuthLogical);
246
- this._logger.debug('FirebaseAuthService', 'resolveAuthorization', 'requiresAuthLogical', requiresAuthLogical);
247
-
248
- if (requiresAuthRoles) {
249
- success = await this._serviceSecurity.authorizationCheckRoles(correlationId, user, requiresAuthRoles, requiresAuthLogical);
250
- this._logger.info2('authorization.roles.success', success);
251
- // console.log('authorization.roles.success', success);
252
- }
253
-
254
- this._logger.debug('FirebaseAuthService', 'resolveAuthorization', 'success', success, correlationId);
255
- // console.log('authorization.roles.success', success);
256
- this._logger.info2('authorization.roles.success', success);
257
- if (!success) {
258
- this._logger.warn2('authorization.roles - failed');
259
- // console.log('authorization.roles - failed');
260
- LibraryClientUtility.$navRouter.push('/', null, () => {
261
- // LibraryClientUtility.$navRouter.push('/')
262
- // window.location.href = '/'
263
- });
264
- return false;
265
- }
266
-
267
- this._logger.debug('FirebaseAuthService', 'resolveAuthorization', 'roles.success', true, correlationId);
268
- // console.log('authorization.roles - success');
269
-
270
- return true;
271
- }
272
-
273
- async signIn(correlationId) {
274
- if (await this.isAuthenticated())
275
- return false;
276
-
277
- try {
278
- const provider = new GoogleAuthProvider();
279
- const result = await signInWithPopup(this._auth, provider);
280
- if (result && result.user) {
281
- //const credential = GoogleAuthProvider.credentialFromResult(result);
282
- // const token = credential.accessToken;
283
- this.updateExternalUser(correlationId, result.user);
284
- // this._serviceRouter.route('/')
285
- window.location.href = '/';
286
- return true;
287
- }
288
-
289
- this.updateExternalUser(correlationId, null);
290
- }
291
- catch (err) {
292
- this._logger.exception('FirebaseAuthService', 'signIn', err, correlationId);
293
- this.updateExternalUser(correlationId, null);
294
- }
295
-
296
- return true;
297
- }
298
-
299
- async signInCompleted(correlationId) {
300
- // if (await auth.isAuthenticated())
301
- // return
302
- // this._auth.getRedirectResult().then(function (result) {
303
- // if (result.credential) {
304
- // // This gives you a Google Access Token. You can use it to access the Google API.
305
- // // eslint-disable-next-line
306
- // var token = result.credential.accessToken
307
- // // ...
308
- // }
309
- // // The signed-in user info.
310
- // // eslint-disable-next-line
311
- // var user = result.user
312
- // }).catch(function (error) {
313
- // // Handle Errors here.
314
- // // eslint-disable-next-line
315
- // var errorCode = error.code
316
- // // eslint-disable-next-line
317
- // var errorMessage = error.message
318
- // // The email of the user's account used.
319
- // // eslint-disable-next-line
320
- // var email = error.email
321
- // // The firebase.auth.AuthCredential type that was used.
322
- // // eslint-disable-next-line
323
- // var credential = error.credential
324
- // // ...
325
- // })
326
- }
327
-
328
- async signOut(correlationId) {
329
- try {
330
- // await this._auth.signOut()
331
- // await this._serviceUser.dispatcher.user.setTokenResult(correlationId, null)
332
- // await this._serviceUser.dispatcher.user.setClaims(correlationId, null)
333
- // await this._serviceUser.dispatcher.user.setUser(correlationId, null)
334
- // await this._serviceUser.dispatcher.user.setLoggedIn(correlationId, false)
335
-
336
- const list = [];
337
- list.push(this._auth.signOut());
338
- // list.push(this._serviceUser.dispatcher.user.setTokenResult(correlationId, null))
339
- // list.push(this._serviceUser.dispatcher.user.setClaims(correlationId, null))
340
- // list.push(this._serviceUser.dispatcher.user.setUser(correlationId, null))
341
- // list.push(this._serviceUser.dispatcher.user.setLoggedIn(correlationId, false))
342
- list.push(this._serviceUser.resetUser(correlationId));
343
- list.push(this._serviceUser.setAuthCompleted(correlationId, false));
344
-
345
- await Promise.all(list);
346
-
347
- // this._serviceRouter.route('/')
348
- window.location.href = '/';
349
- }
350
- catch (err) {
351
- this._logger.exception('FirebaseAuthService', 'signOut', err, correlationId);
352
- }
353
- }
354
-
355
- sleep(ms) {
356
- return new Promise((resolve) => {
357
- setTimeout(resolve, ms);
358
- });
359
- }
360
-
361
- get token() {
362
- return this._serviceUser.token;
363
- }
364
-
365
- get user() {
366
- return this._serviceUser.user;
367
- }
368
-
369
- // async token(forceRefresh) {
370
- // if (!forceRefresh)
371
- // forceRefresh = false
372
-
373
- // const user = this.user
374
- // this._logger.debug('FirebaseAuthService', 'token', 'user', user, correlationId);
375
- // if (!user)
376
- // return null
377
-
378
- // this._logger.debug('FirebaseAuthService', 'token', 'forceRefresh', forceRefresh, correlationId)
379
- // return this.refreshToken'FirebaseAuthService', 'token', user, forceRefresh)
380
- // }
381
-
382
- async updateExternalUser(correlationId, user) {
383
- // if (this._lock)
384
- // return
385
-
386
- try {
387
- // if (this._lock)
388
- // return
389
-
390
- // this._lock = true
391
-
392
- user = this._convert(correlationId, user);
393
- if (!user) {
394
- await this._serviceUser.setUser(correlationId, null);
395
- await this._serviceUser.setLoggedIn(correlationId, false);
396
- return;
397
- }
398
-
399
- await this.refreshToken(correlationId, user);
400
- const response = await this._serviceUser.updateExternal(correlationId, user);
401
- if (this._hasSucceeded(response)) {
402
- await this._serviceUser.setUser(correlationId, response.results);
403
- await this._serviceUser.setLoggedIn(correlationId, true);
404
- }
405
- }
406
- finally {
407
- // this._lock = false
408
- }
409
- }
410
-
411
- _convert(correlationId, requestedUser) {
412
- if (requestedUser) {
413
- const user = {};
414
- user.id = requestedUser.uid;
415
- user.name = requestedUser.displayName;
416
- user.picture = requestedUser.photoURL;
417
- user.email = requestedUser.email;
418
- return user;
419
- }
420
-
421
- return null;
422
- }
423
-
424
- _initializeAnalytics(correlationId, configExternal, configFirebase) {
425
- if (configFirebase.measurementId)
426
- getAnalytics();
427
- }
428
-
429
- _initializeAuth(correlationId, configExternal, configFirebase, outsideResolve, outsideReject) {
430
- this._auth = getAuth();
431
-
432
- const self = this;
433
- const firebaseAuth = this._auth;
434
- // eslint-disable-next-line
435
- let init = false;
436
- firebaseAuth.onAuthStateChanged(async function(user) {
437
- // const auth = LibraryClientUtility.$injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_AUTH);
438
- // await auth.onAuthStateChanged(user);
439
- await self.onAuthStateChanged(user);
440
- if (!init) {
441
- init = true;
442
- outsideResolve(true);
443
- return;
444
- }
445
-
446
- outsideReject();
447
- });
448
- }
449
-
450
- _initializeFirebase(correlationId, configExternal, configFirebase) {
451
- initializeApp(configFirebase);
452
- }
453
- }
454
-
455
- export default FirebaseAuthService;
1
+ import { initializeApp } from 'firebase/app';
2
+ // import { getAuth } from "firebase/auth";
3
+ import { getAnalytics } from "firebase/analytics";
4
+ import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
5
+
6
+ import LibraryClientConstants from '@thzero/library_client/constants';
7
+
8
+ import LibraryClientUtility from '@thzero/library_client/utility/index';
9
+ import LibraryCommonUtility from '@thzero/library_common/utility/index';
10
+ import LibraryMomentUtility from '@thzero/library_common/utility/moment';
11
+
12
+ import UserAuthService from '@thzero/library_client/service/auth/user';
13
+
14
+ class FirebaseAuthService extends UserAuthService {
15
+ constructor() {
16
+ super();
17
+
18
+ this._auth = null;
19
+
20
+ // this._lock = false
21
+ this._polling = null;
22
+
23
+ this._serviceRouter = null;
24
+ }
25
+
26
+ async init(injector) {
27
+ await super.init(injector);
28
+
29
+ this._serviceRouter = this._injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_ROUTER);
30
+ }
31
+
32
+ async deleteUser(correlationId) {
33
+ try {
34
+ const user = await this.getExternalUser();
35
+ if (!user)
36
+ return;
37
+
38
+ await user.delete();
39
+ await this._serviceUser.resetUser(correlationId);
40
+ }
41
+ catch (err) {
42
+ this._logger.exception('FirebaseAuthService', 'deleteUser', err, correlationId);
43
+ throw err;
44
+ }
45
+ }
46
+
47
+ async getExternalUser() {
48
+ if (this._auth) {
49
+ this._logger.debug('FirebaseAuthService', 'getExternalUser', 'user', this._auth.currentUser);
50
+ return this._auth.currentUser;
51
+ }
52
+ return null;
53
+ }
54
+
55
+ async initialize(correlationId, router) {
56
+ const configExternal = this._config.getExternal();
57
+ if (!configExternal)
58
+ throw Error('Invalid external config.');
59
+ const configFirebase = configExternal.firebase;
60
+ if (!configFirebase)
61
+ throw Error('Invalid firebase config.');
62
+ // initializeApp(configFirebase);
63
+ // if (configFirebase.measurementId)
64
+ // getAnalytics();
65
+ this._initializeFirebase(correlationId, configExternal, configFirebase);
66
+
67
+ let outsideResolve;
68
+ let outsideReject;
69
+ const promiseAuth = new Promise(function(resolve, reject) {
70
+ outsideResolve = resolve;
71
+ outsideReject = reject;
72
+ });
73
+
74
+ this._initializeAuth(correlationId, configExternal, configFirebase, outsideResolve, outsideReject);
75
+
76
+ this._initializeAnalytics(correlationId, configExternal, configFirebase);
77
+
78
+ return promiseAuth;
79
+ }
80
+
81
+ async isAuthenticated() {
82
+ const user = await this.getExternalUser();
83
+ this._logger.debug('FirebaseAuthService', 'isAuthenticated', 'user', user);
84
+ return LibraryCommonUtility.isNotNull(user);
85
+ }
86
+
87
+ async onAuthStateChanged(user) {
88
+ const correlationId = LibraryCommonUtility.correlationId();
89
+ try {
90
+ await this.updateExternalUser(correlationId, user, true);
91
+ // if (!user)
92
+ // return
93
+
94
+ await this._serviceUser.setAuthCompleted(correlationId, true);
95
+ this._serviceEvent.emit(LibraryClientConstants.EventKeys.Auth.Refresh, user);
96
+ }
97
+ catch (err) {
98
+ this._logger.exception('FirebaseAuthService', 'onAuthStateChanged', err, correlationId);
99
+ }
100
+
101
+ // try {
102
+ // if (!user) {
103
+ // if (this._polling)
104
+ // clearInterval(this._polling)
105
+ // return
106
+ // }
107
+
108
+ // const self = this
109
+ // this._polling = setInterval(async () => {
110
+ // await self.refreshToken(self.user, true).then()
111
+ // }, 60 * 1000)
112
+ // }
113
+ // catch (err) {
114
+ // this._logger.exception('FirebaseAuthService', 'onAuthStateChanged', err, correlationId)
115
+ // }
116
+ }
117
+
118
+ async refreshToken(correlationId, user, forceRefresh) {
119
+ forceRefresh = forceRefresh !== null ? forceRefresh : false;
120
+ this._logger.debug('FirebaseAuthService', 'refreshToken', 'forceRefresh', forceRefresh, correlationId);
121
+
122
+ try {
123
+ this._logger.debug('FirebaseAuthService', 'refreshToken', 'user', user, correlationId);
124
+ if (!user) {
125
+ await this._serviceUser.setTokenResult(correlationId, null);
126
+ await this._serviceUser.setClaims(correlationId, null);
127
+ this.announceToken(correlationId, user, null);
128
+
129
+ return;
130
+ }
131
+
132
+ this._logger.debug('FirebaseAuthService', 'refreshToken', 'forceRefresh', forceRefresh, correlationId);
133
+ const currentUser = await this.getExternalUser();
134
+ this._logger.debug('FirebaseAuthService', 'refreshToken', 'currentUser', currentUser, correlationId);
135
+ if (!currentUser)
136
+ return;
137
+
138
+ if (this._polling)
139
+ clearInterval(this._polling);
140
+
141
+ let token = null;
142
+
143
+ const tokenResult = await this.refreshTokenResult(correlationId, forceRefresh);
144
+ if (tokenResult) {
145
+ await this._serviceUser.setTokenResult(correlationId, tokenResult);
146
+ token = tokenResult.token;
147
+ let claims = token != null ? tokenResult.claims : null;
148
+ this._logger.debug('FirebaseAuthService', 'refreshToken', 'claims', claims, correlationId);
149
+ claims = claims != null ? claims.custom : null;
150
+ this._logger.debug('FirebaseAuthService', 'refreshToken', 'claims.custom', claims, correlationId);
151
+ await this._serviceUser.setClaims(correlationId, claims);
152
+
153
+ this.refreshTokenExpiration(correlationId, tokenResult, user);
154
+ }
155
+ else {
156
+ await this._serviceUser.setTokenResult(correlationId, null);
157
+ await this._serviceUser.setClaims(correlationId, null);
158
+ }
159
+
160
+ await this.announceToken(correlationId, user, token);
161
+ }
162
+ catch (err) {
163
+ this._logger.exception('FirebaseAuthService', 'refreshToken', err, correlationId);
164
+ throw err;
165
+ }
166
+ }
167
+
168
+ async refreshTokenExpiration(correlationId, tokenResult, user) {
169
+ const expired = LibraryMomentUtility.getDateParse(tokenResult.expirationTime);
170
+ const now = LibraryMomentUtility.getDate();
171
+ const diff = expired.diff(now);
172
+ const min = 5 * 60 * 1000;
173
+ if (diff <= min) {
174
+ await this.refreshToken(correlationId, await this.getExternalUser(), true).then();
175
+ return;
176
+ }
177
+
178
+ if (this._polling)
179
+ clearInterval(this._polling);
180
+
181
+ const self = this;
182
+ this._polling = setInterval(async () => {
183
+ await self.refreshToken(correlationId, user, true).then();
184
+ }, diff); // 60 * 1000);
185
+ }
186
+
187
+ async refreshTokenResult(correlationId, forceRefresh) {
188
+ const currentUser = await this.getExternalUser();
189
+ if (!currentUser)
190
+ return null;
191
+ return await currentUser.getIdTokenResult(forceRefresh);
192
+ }
193
+
194
+ async resolveAuthorization(correlationId, requiresAuthRoles, requiresAuthLogical) {
195
+ // const serviceAuth = LibraryClientUtility.$injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_AUTH);
196
+ // const serviceLogger = LibraryClientUtility.$injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_LOGGER);
197
+ // const serviceSecurity = LibraryClientUtility.$injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_SECURITY);
198
+ // const serviceStore = LibraryClientUtility.$injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_STORE);
199
+ this._logger.info2('requiresAuth');
200
+ let isLoggedIn = await this.isAuthenticated();
201
+ this._logger.info2('authorization.isLoggedIn', isLoggedIn);
202
+ // console.log('authorization.isLoggedIn', isLoggedIn);
203
+ if (!isLoggedIn) {
204
+ // Briefly wait for authentication to settle...
205
+ let i = 0;
206
+ while (await this.sleep(150)) {
207
+ if (this._serviceStore.userAuthCompleted) {
208
+ this._logger.info2('authorization.userAuthCompleted', userAuthCompleted);
209
+ // console.log('authorization.userAuthCompleted', userAuthCompleted);
210
+ break;
211
+ }
212
+ i++;
213
+ this._logger.info2('waiting... ' + i);
214
+ if (i > 5) {
215
+ this._logger.warn2('authorization.userAuthCompleted failed');
216
+ break;
217
+ }
218
+ }
219
+ const isLoggedInAuthCompleted = await this.isAuthenticated();
220
+ this._logger.info2('authorization.isLoggedIn.userAuthCompleted', isLoggedInAuthCompleted);
221
+ // console.log('authorization.isLoggedIn.userAuthCompleted', isLoggedInAuthCompleted);
222
+ isLoggedIn = isLoggedInAuthCompleted;
223
+ }
224
+ this._logger.info2('authorization.isLoggedIn.final', isLoggedIn);
225
+ // console.log('authorization.isLoggedIn.final', isLoggedIn);
226
+ if (!isLoggedIn) {
227
+ this._logger.warn2('authorization.isLoggedIn - failed');
228
+ // console.log('authorization.isLoggedIn - failed');
229
+ // LibraryClientUtility.$EventBus.on('auth-refresh', (user) => {
230
+ // this._logger.debug('auth-refresh', user)
231
+ // this._logger.debug('middleware', 'auth-refresh', null, user, correlationId);
232
+ // next()
233
+ // })
234
+ // return
235
+ return false;
236
+ }
237
+
238
+ this._logger.info2('authorization.isLoggedIn - success');
239
+ // console.log('authorization.isLoggedIn - success');
240
+
241
+ const user = this._serviceUser.user;
242
+ let success = true;
243
+ // console.log('authorization.requiresAuthRoles', requiresAuthRoles);
244
+ this._logger.debug('FirebaseAuthService', 'resolveAuthorization', 'requiresAuthRoles', requiresAuthRoles);
245
+ // console.log('authorization.requiresAuthLogical', requiresAuthLogical);
246
+ this._logger.debug('FirebaseAuthService', 'resolveAuthorization', 'requiresAuthLogical', requiresAuthLogical);
247
+
248
+ if (requiresAuthRoles) {
249
+ success = await this._serviceSecurity.authorizationCheckRoles(correlationId, user, requiresAuthRoles, requiresAuthLogical);
250
+ this._logger.info2('authorization.roles.success', success);
251
+ // console.log('authorization.roles.success', success);
252
+ }
253
+
254
+ this._logger.debug('FirebaseAuthService', 'resolveAuthorization', 'success', success, correlationId);
255
+ // console.log('authorization.roles.success', success);
256
+ this._logger.info2('authorization.roles.success', success);
257
+ if (!success) {
258
+ this._logger.warn2('authorization.roles - failed');
259
+ // console.log('authorization.roles - failed');
260
+ LibraryClientUtility.$navRouter.push('/', null, () => {
261
+ // LibraryClientUtility.$navRouter.push('/')
262
+ // window.location.href = '/'
263
+ });
264
+ return false;
265
+ }
266
+
267
+ this._logger.debug('FirebaseAuthService', 'resolveAuthorization', 'roles.success', true, correlationId);
268
+ // console.log('authorization.roles - success');
269
+
270
+ return true;
271
+ }
272
+
273
+ async signIn(correlationId) {
274
+ if (await this.isAuthenticated())
275
+ return false;
276
+
277
+ try {
278
+ const provider = new GoogleAuthProvider();
279
+ const result = await signInWithPopup(this._auth, provider);
280
+ if (result && result.user) {
281
+ //const credential = GoogleAuthProvider.credentialFromResult(result);
282
+ // const token = credential.accessToken;
283
+ this.updateExternalUser(correlationId, result.user);
284
+ // this._serviceRouter.route('/')
285
+ window.location.href = '/';
286
+ return true;
287
+ }
288
+
289
+ this.updateExternalUser(correlationId, null);
290
+ }
291
+ catch (err) {
292
+ this._logger.exception('FirebaseAuthService', 'signIn', err, correlationId);
293
+ this.updateExternalUser(correlationId, null);
294
+ }
295
+
296
+ return true;
297
+ }
298
+
299
+ async signInCompleted(correlationId) {
300
+ // if (await auth.isAuthenticated())
301
+ // return
302
+ // this._auth.getRedirectResult().then(function (result) {
303
+ // if (result.credential) {
304
+ // // This gives you a Google Access Token. You can use it to access the Google API.
305
+ // // eslint-disable-next-line
306
+ // var token = result.credential.accessToken
307
+ // // ...
308
+ // }
309
+ // // The signed-in user info.
310
+ // // eslint-disable-next-line
311
+ // var user = result.user
312
+ // }).catch(function (error) {
313
+ // // Handle Errors here.
314
+ // // eslint-disable-next-line
315
+ // var errorCode = error.code
316
+ // // eslint-disable-next-line
317
+ // var errorMessage = error.message
318
+ // // The email of the user's account used.
319
+ // // eslint-disable-next-line
320
+ // var email = error.email
321
+ // // The firebase.auth.AuthCredential type that was used.
322
+ // // eslint-disable-next-line
323
+ // var credential = error.credential
324
+ // // ...
325
+ // })
326
+ }
327
+
328
+ async signOut(correlationId) {
329
+ try {
330
+ // await this._auth.signOut()
331
+ // await this._serviceUser.dispatcher.user.setTokenResult(correlationId, null)
332
+ // await this._serviceUser.dispatcher.user.setClaims(correlationId, null)
333
+ // await this._serviceUser.dispatcher.user.setUser(correlationId, null)
334
+ // await this._serviceUser.dispatcher.user.setLoggedIn(correlationId, false)
335
+
336
+ const list = [];
337
+ list.push(this._auth.signOut());
338
+ // list.push(this._serviceUser.dispatcher.user.setTokenResult(correlationId, null))
339
+ // list.push(this._serviceUser.dispatcher.user.setClaims(correlationId, null))
340
+ // list.push(this._serviceUser.dispatcher.user.setUser(correlationId, null))
341
+ // list.push(this._serviceUser.dispatcher.user.setLoggedIn(correlationId, false))
342
+ list.push(this._serviceUser.resetUser(correlationId));
343
+ list.push(this._serviceUser.setAuthCompleted(correlationId, false));
344
+
345
+ await Promise.all(list);
346
+
347
+ // this._serviceRouter.route('/')
348
+ window.location.href = '/';
349
+ }
350
+ catch (err) {
351
+ this._logger.exception('FirebaseAuthService', 'signOut', err, correlationId);
352
+ }
353
+ }
354
+
355
+ sleep(ms) {
356
+ return new Promise((resolve) => {
357
+ setTimeout(resolve, ms);
358
+ });
359
+ }
360
+
361
+ get token() {
362
+ return this._serviceUser.token;
363
+ }
364
+
365
+ get user() {
366
+ return this._serviceUser.user;
367
+ }
368
+
369
+ // async token(forceRefresh) {
370
+ // if (!forceRefresh)
371
+ // forceRefresh = false
372
+
373
+ // const user = this.user
374
+ // this._logger.debug('FirebaseAuthService', 'token', 'user', user, correlationId);
375
+ // if (!user)
376
+ // return null
377
+
378
+ // this._logger.debug('FirebaseAuthService', 'token', 'forceRefresh', forceRefresh, correlationId)
379
+ // return this.refreshToken'FirebaseAuthService', 'token', user, forceRefresh)
380
+ // }
381
+
382
+ async updateExternalUser(correlationId, user) {
383
+ // if (this._lock)
384
+ // return
385
+
386
+ try {
387
+ // if (this._lock)
388
+ // return
389
+
390
+ // this._lock = true
391
+
392
+ user = this._convert(correlationId, user);
393
+ if (!user) {
394
+ await this._serviceUser.setUser(correlationId, null);
395
+ await this._serviceUser.setLoggedIn(correlationId, false);
396
+ return;
397
+ }
398
+
399
+ await this.refreshToken(correlationId, user);
400
+ const response = await this._serviceUser.updateExternal(correlationId, user);
401
+ if (this._hasSucceeded(response)) {
402
+ await this._serviceUser.setUser(correlationId, response.results);
403
+ await this._serviceUser.setLoggedIn(correlationId, true);
404
+ }
405
+ }
406
+ finally {
407
+ // this._lock = false
408
+ }
409
+ }
410
+
411
+ _convert(correlationId, requestedUser) {
412
+ if (requestedUser) {
413
+ const user = {};
414
+ user.id = requestedUser.uid;
415
+ user.name = requestedUser.displayName;
416
+ user.picture = requestedUser.photoURL;
417
+ user.email = requestedUser.email;
418
+ return user;
419
+ }
420
+
421
+ return null;
422
+ }
423
+
424
+ _initializeAnalytics(correlationId, configExternal, configFirebase) {
425
+ if (configFirebase.measurementId)
426
+ getAnalytics();
427
+ }
428
+
429
+ _initializeAuth(correlationId, configExternal, configFirebase, outsideResolve, outsideReject) {
430
+ this._auth = getAuth();
431
+
432
+ const self = this;
433
+ const firebaseAuth = this._auth;
434
+ // eslint-disable-next-line
435
+ let init = false;
436
+ firebaseAuth.onAuthStateChanged(async function(user) {
437
+ // const auth = LibraryClientUtility.$injector.getService(LibraryClientConstants.InjectorKeys.SERVICE_AUTH);
438
+ // await auth.onAuthStateChanged(user);
439
+ await self.onAuthStateChanged(user);
440
+ if (!init) {
441
+ init = true;
442
+ outsideResolve(true);
443
+ return;
444
+ }
445
+
446
+ outsideReject();
447
+ });
448
+ }
449
+
450
+ _initializeFirebase(correlationId, configExternal, configFirebase) {
451
+ initializeApp(configFirebase);
452
+ }
453
+ }
454
+
455
+ export default FirebaseAuthService;