@thzero/library_client_firebase 0.17.9 → 0.17.11

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