@thzero/library_client_firebase 0.16.2 → 0.16.4

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/README.md CHANGED
@@ -1,113 +1,113 @@
1
- ![GitHub package.json version](https://img.shields.io/github/package-json/v/thzero/library_client_firebase)
2
- ![David](https://img.shields.io/david/thzero/library_client_firebase)
3
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
-
5
- # library_client_firebase
6
-
7
- ## Installation
8
-
9
- [![NPM](https://nodei.co/npm/@thzero/library_client_firebase.png?compact=true)](https://npmjs.org/package/@thzero/library_client_firebase)
10
-
11
- ## Requirements
12
-
13
- ### Firebase
14
-
15
- Google Firebase (https://firebase.google.com) provides the social based authentication; currently only Google social accounts are supported.
16
-
17
- * Add a new project
18
- * If not already completed when setting up the server application
19
- * Setup **Authentication**, enabled Google in the **Sign-in method**.
20
- * If not already completed when setting up the server application
21
- * Get the Firebase SDK configuration
22
- * Go to Project Overview->Settings->General
23
- * Click **Add App** and select **Web**
24
- * Click *Firebase SDK snippet*, select **Config*
25
- * Select the JSON object and store it
26
- * The contents of the JSON object will be stored as key/value pairs in the external/firebase confib object (below)
27
- * Supports Firebase Analytics.
28
- * Go to Project Overview->Settings->Integrations
29
- * Enable the Google Analytics.
30
- * Copy the 'measurementId' key//value pair into the external/firebase config object (below)
31
-
32
- ## Configuration
33
-
34
- ### Application Configuration
35
-
36
- * In the configuration files (development.json and production.json) of the application
37
- * Add the following onfiguration block to contain the firebase key.
38
-
39
- ```
40
- ,
41
- "external": {
42
- "firebase": <firebase key JSON object from above goes here>
43
- }
44
- ```
45
-
46
- ### Locales
47
-
48
- Merge the following to the 'src/locals/en/index.json' file:
49
-
50
- ```
51
- {
52
- "admin": {
53
- "users": "Users"
54
- },
55
- "forms": {
56
- "externalId": "External Id",
57
- "news": {
58
- "requiresAuth": "Requires Authentication",
59
- },
60
- "role": "Role",
61
- "roles": "Roles",
62
- },
63
- "news": {
64
- "requiresAuth": "Authenticated",
65
- },
66
- "users": {
67
- "actions": "Actions",
68
- "externalId": "External Id",
69
- "id": "Id",
70
- "name": "Name",
71
- "role": "Role",
72
- "roles": "Roles"
73
- }
74
- }
75
- ```
76
-
77
- ### Main.js
78
-
79
- * Add the following import statement to the 'main.js' file.
80
-
81
- ```
82
- import bootStarter from '@thzero/library_client_firebase/boot/starter';
83
- ```
84
-
85
- * Adjust the start method of the 'main.js' file to iclude 'bootAuth' as the last parameter.
86
-
87
- ```
88
- start(app, router, store, vuetify, [ ... ], bootStarter);
89
- ```
90
-
91
- ### Route.js
92
-
93
- Routes can be denoted as not requiring authentication. To do so, tag on the route the following in the 'meta node'.
94
-
95
- ```
96
- requiresAuth: false
97
- ```
98
-
99
- It is advised that the following routes should have authentication turned off.
100
-
101
- * Home
102
- * About
103
- * Open Source
104
- * Auth
105
- * Not Found
106
- * Blank
107
-
108
- It is advised that the following routes should have authentication turned on.
109
-
110
- * Admin
111
- * Settings
112
- * Support
113
- * Any application routes that require authenticated users.
1
+ ![GitHub package.json version](https://img.shields.io/github/package-json/v/thzero/library_client_firebase)
2
+ ![David](https://img.shields.io/david/thzero/library_client_firebase)
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
+
5
+ # library_client_firebase
6
+
7
+ ## Installation
8
+
9
+ [![NPM](https://nodei.co/npm/@thzero/library_client_firebase.png?compact=true)](https://npmjs.org/package/@thzero/library_client_firebase)
10
+
11
+ ## Requirements
12
+
13
+ ### Firebase
14
+
15
+ Google Firebase (https://firebase.google.com) provides the social based authentication; currently only Google social accounts are supported.
16
+
17
+ * Add a new project
18
+ * If not already completed when setting up the server application
19
+ * Setup **Authentication**, enabled Google in the **Sign-in method**.
20
+ * If not already completed when setting up the server application
21
+ * Get the Firebase SDK configuration
22
+ * Go to Project Overview->Settings->General
23
+ * Click **Add App** and select **Web**
24
+ * Click *Firebase SDK snippet*, select **Config*
25
+ * Select the JSON object and store it
26
+ * The contents of the JSON object will be stored as key/value pairs in the external/firebase confib object (below)
27
+ * Supports Firebase Analytics.
28
+ * Go to Project Overview->Settings->Integrations
29
+ * Enable the Google Analytics.
30
+ * Copy the 'measurementId' key//value pair into the external/firebase config object (below)
31
+
32
+ ## Configuration
33
+
34
+ ### Application Configuration
35
+
36
+ * In the configuration files (development.json and production.json) of the application
37
+ * Add the following onfiguration block to contain the firebase key.
38
+
39
+ ```
40
+ ,
41
+ "external": {
42
+ "firebase": <firebase key JSON object from above goes here>
43
+ }
44
+ ```
45
+
46
+ ### Locales
47
+
48
+ Merge the following to the 'src/locals/en/index.json' file:
49
+
50
+ ```
51
+ {
52
+ "admin": {
53
+ "users": "Users"
54
+ },
55
+ "forms": {
56
+ "externalId": "External Id",
57
+ "news": {
58
+ "requiresAuth": "Requires Authentication",
59
+ },
60
+ "role": "Role",
61
+ "roles": "Roles",
62
+ },
63
+ "news": {
64
+ "requiresAuth": "Authenticated",
65
+ },
66
+ "users": {
67
+ "actions": "Actions",
68
+ "externalId": "External Id",
69
+ "id": "Id",
70
+ "name": "Name",
71
+ "role": "Role",
72
+ "roles": "Roles"
73
+ }
74
+ }
75
+ ```
76
+
77
+ ### Main.js
78
+
79
+ * Add the following import statement to the 'main.js' file.
80
+
81
+ ```
82
+ import bootStarter from '@thzero/library_client_firebase/boot/starter';
83
+ ```
84
+
85
+ * Adjust the start method of the 'main.js' file to iclude 'bootAuth' as the last parameter.
86
+
87
+ ```
88
+ start(app, router, store, vuetify, [ ... ], bootStarter);
89
+ ```
90
+
91
+ ### Route.js
92
+
93
+ Routes can be denoted as not requiring authentication. To do so, tag on the route the following in the 'meta node'.
94
+
95
+ ```
96
+ requiresAuth: false
97
+ ```
98
+
99
+ It is advised that the following routes should have authentication turned off.
100
+
101
+ * Home
102
+ * About
103
+ * Open Source
104
+ * Auth
105
+ * Not Found
106
+ * Blank
107
+
108
+ It is advised that the following routes should have authentication turned on.
109
+
110
+ * Admin
111
+ * Settings
112
+ * Support
113
+ * Any application routes that require authenticated users.
package/boot/starter.js CHANGED
@@ -1,160 +1,156 @@
1
- import { initializeApp } from 'firebase/app';
2
- import { getAuth } from "firebase/auth";
3
- import { getAnalytics } from "firebase/analytics";
4
-
5
- import LibraryConstants from '@thzero/library_client/constants';
6
-
7
- import GlobalUtility from '@thzero/library_client/utility/global';
8
-
9
- import config from 'local-config';
10
-
11
- // export default async ({
12
- export default ({
13
- // eslint-disable-next-line
14
- framework,
15
- // eslint-disable-next-line
16
- app,
17
- router
18
- }) => {
19
- const configExternal = config.external;
20
- if (!configExternal)
21
- throw Error('Invalid external config.');
22
- const configFirebase = configExternal.firebase;
23
- if (!configFirebase)
24
- throw Error('Invalid firebase config.');
25
- const firebaseApp = initializeApp(configFirebase);
26
- if (configFirebase.measurementId)
27
- getAnalytics();
28
-
29
- let outsideResolve;
30
- let outsideReject;
31
- const promiseAuth = new Promise(function(resolve, reject) {
32
- outsideResolve = resolve;
33
- outsideReject = reject;
34
- });
35
-
36
- const firebaseAuth = getAuth();
37
- // if (firebaseAuth.currentUser) {
38
- // const timer = setInterval(async () => {
39
- // clearInterval(timer)
40
- // const auth = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_AUTH)
41
- // await auth.onAuthStateChanged(null)
42
- // }, 50)
43
- // }
44
- // eslint-disable-next-line
45
- let init = false;
46
- firebaseAuth.onAuthStateChanged(async function(user) {
47
- // if (user == null) {
48
- // // GlobalUtility.$navRouter.push('/auth')
49
- // return
50
- // }
51
-
52
- const auth = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_AUTH);
53
- // await auth.onAuthStateChanged(user)
54
- // const timer = setInterval(async () => {
55
- // clearInterval(timer)
56
- // await auth.onAuthStateChanged(user)
57
- // }, 50)
58
- await auth.onAuthStateChanged(user);
59
- // if (test)
60
- if (!init) {
61
- init = true;
62
- outsideResolve(true);
63
- return;
64
- }
65
-
66
- outsideReject();
67
- });
68
-
69
- // setInterval(async () => {
70
- // const logger = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_LOGGER)
71
- // const auth = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_AUTH)
72
- // try {
73
- // await auth.refreshToken(correlationId, auth.externalUser, true).then()
74
- // }
75
- // catch (err) {
76
- // logger.error(err)
77
- // }
78
- // }, 60 * 1000)
79
-
80
- // firebase.auth().onIdTokenChanged(async function(user) {
81
- // const logger = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_LOGGER)
82
- // try {
83
- // const auth = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_AUTH)
84
-
85
- // // const interval = 500 // 10 * 1000
86
- // // const timer = setInterval(async () => {
87
- // // await auth.onRefresh(user)
88
- // // clearInterval(timer)
89
- // // }, interval)
90
- // await auth.onRefresh(user)
91
- // }
92
- // catch (err) {
93
- // logger.error(err)
94
- // }
95
- // })
96
-
97
- router.beforeResolve((to, from, next) => {
98
- const auth = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_AUTH);
99
- const logger = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_LOGGER);
100
- logger.debug('router.beforeResolve', to);
101
- if (to.matched.some(record => record.meta.requiresAuth)) {
102
- const isLoggedIn = auth.isAuthenticated;
103
- if (!isLoggedIn) {
104
- // GlobalUtility.$EventBus.on('auth-refresh', (user) => {
105
- // logger.debug('auth-refresh', user)
106
- // next()
107
- // })
108
- // return
109
- GlobalUtility.$navRouter.push('/', null, () => {
110
- // GlobalUtility.$navRouter.push('/')
111
- // window.location.href = '/'
112
- });
113
- return;
114
- }
115
-
116
- next();
117
-
118
- // eslint-disable-next-line no-unused-vars
119
- // auth.isAuthenticated().then(async (data) => {
120
- // logger.debug('router.beforeResolve.matched')
121
-
122
- // //const isLoggedIn = GlobalUtility.$store.state.user.isLoggedIn
123
- // const isLoggedIn = await auth.isAuthenticated()
124
- // if (!isLoggedIn) {
125
- // GlobalUtility.$EventBus.on('auth-refresh', (user) => {
126
- // logger.debug('auth-refresh', user)
127
- // next()
128
- // })
129
- // return
130
- // }
131
-
132
- // // if (GlobalUtility.$store.state.user.token) {
133
- // // next()
134
- // // return
135
- // // }
136
-
137
- // // GlobalUtility.$EventBus.on('auth-refresh', (user) => {
138
- // // logger.debug('auth-refresh', user)
139
- // // next()
140
- // // })
141
-
142
- // next()
143
- // }).catch((e) => {
144
- // logger.error('router.beforeResolve.error', e)
145
- // logger.error('to', to)
146
- // logger.error('from', from)
147
- // if (to.name == 'auth') {
148
- // next()
149
- // return
150
- // }
151
- // next({ path: '/auth' })
152
- // })
153
-
154
- return;
155
- }
156
- next();
157
- });
158
-
159
- return promiseAuth;
160
- };
1
+ import { initializeApp } from 'firebase/app';
2
+ import { getAuth } from "firebase/auth";
3
+ import { getAnalytics } from "firebase/analytics";
4
+
5
+ import LibraryConstants from '@thzero/library_client/constants';
6
+
7
+ import GlobalUtility from '@thzero/library_client/utility/global';
8
+
9
+ import config from 'local-config';
10
+
11
+ // export default async ({
12
+ export default ({
13
+ router
14
+ }) => {
15
+ const configExternal = config.external;
16
+ if (!configExternal)
17
+ throw Error('Invalid external config.');
18
+ const configFirebase = configExternal.firebase;
19
+ if (!configFirebase)
20
+ throw Error('Invalid firebase config.');
21
+ const firebaseApp = initializeApp(configFirebase);
22
+ if (configFirebase.measurementId)
23
+ getAnalytics();
24
+
25
+ let outsideResolve;
26
+ let outsideReject;
27
+ const promiseAuth = new Promise(function(resolve, reject) {
28
+ outsideResolve = resolve;
29
+ outsideReject = reject;
30
+ });
31
+
32
+ const firebaseAuth = getAuth();
33
+ // if (firebaseAuth.currentUser) {
34
+ // const timer = setInterval(async () => {
35
+ // clearInterval(timer)
36
+ // const auth = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_AUTH)
37
+ // await auth.onAuthStateChanged(null)
38
+ // }, 50)
39
+ // }
40
+ // eslint-disable-next-line
41
+ let init = false;
42
+ firebaseAuth.onAuthStateChanged(async function(user) {
43
+ // if (user == null) {
44
+ // // GlobalUtility.$navRouter.push('/auth')
45
+ // return
46
+ // }
47
+
48
+ const auth = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_AUTH);
49
+ // await auth.onAuthStateChanged(user)
50
+ // const timer = setInterval(async () => {
51
+ // clearInterval(timer)
52
+ // await auth.onAuthStateChanged(user)
53
+ // }, 50)
54
+ await auth.onAuthStateChanged(user);
55
+ // if (test)
56
+ if (!init) {
57
+ init = true;
58
+ outsideResolve(true);
59
+ return;
60
+ }
61
+
62
+ outsideReject();
63
+ });
64
+
65
+ // setInterval(async () => {
66
+ // const logger = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_LOGGER)
67
+ // const auth = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_AUTH)
68
+ // try {
69
+ // await auth.refreshToken(correlationId, auth.externalUser, true).then()
70
+ // }
71
+ // catch (err) {
72
+ // logger.error(err)
73
+ // }
74
+ // }, 60 * 1000)
75
+
76
+ // firebase.auth().onIdTokenChanged(async function(user) {
77
+ // const logger = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_LOGGER)
78
+ // try {
79
+ // const auth = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_AUTH)
80
+
81
+ // // const interval = 500 // 10 * 1000
82
+ // // const timer = setInterval(async () => {
83
+ // // await auth.onRefresh(user)
84
+ // // clearInterval(timer)
85
+ // // }, interval)
86
+ // await auth.onRefresh(user)
87
+ // }
88
+ // catch (err) {
89
+ // logger.error(err)
90
+ // }
91
+ // })
92
+
93
+ router.beforeResolve((to, from, next) => {
94
+ const auth = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_AUTH);
95
+ const logger = GlobalUtility.$injector.getService(LibraryConstants.InjectorKeys.SERVICE_LOGGER);
96
+ logger.debug('router.beforeResolve', to);
97
+ if (to.matched.some(record => record.meta.requiresAuth)) {
98
+ const isLoggedIn = auth.isAuthenticated;
99
+ if (!isLoggedIn) {
100
+ // GlobalUtility.$EventBus.on('auth-refresh', (user) => {
101
+ // logger.debug('auth-refresh', user)
102
+ // next()
103
+ // })
104
+ // return
105
+ GlobalUtility.$navRouter.push('/', null, () => {
106
+ // GlobalUtility.$navRouter.push('/')
107
+ // window.location.href = '/'
108
+ });
109
+ return;
110
+ }
111
+
112
+ next();
113
+
114
+ // eslint-disable-next-line no-unused-vars
115
+ // auth.isAuthenticated().then(async (data) => {
116
+ // logger.debug('router.beforeResolve.matched')
117
+
118
+ // //const isLoggedIn = GlobalUtility.$store.state.user.isLoggedIn
119
+ // const isLoggedIn = await auth.isAuthenticated()
120
+ // if (!isLoggedIn) {
121
+ // GlobalUtility.$EventBus.on('auth-refresh', (user) => {
122
+ // logger.debug('auth-refresh', user)
123
+ // next()
124
+ // })
125
+ // return
126
+ // }
127
+
128
+ // // if (GlobalUtility.$store.state.user.token) {
129
+ // // next()
130
+ // // return
131
+ // // }
132
+
133
+ // // GlobalUtility.$EventBus.on('auth-refresh', (user) => {
134
+ // // logger.debug('auth-refresh', user)
135
+ // // next()
136
+ // // })
137
+
138
+ // next()
139
+ // }).catch((e) => {
140
+ // logger.error('router.beforeResolve.error', e)
141
+ // logger.error('to', to)
142
+ // logger.error('from', from)
143
+ // if (to.name == 'auth') {
144
+ // next()
145
+ // return
146
+ // }
147
+ // next({ path: '/auth' })
148
+ // })
149
+
150
+ return;
151
+ }
152
+ next();
153
+ });
154
+
155
+ return promiseAuth;
156
+ };
package/license.md CHANGED
@@ -1,9 +1,9 @@
1
- MIT License
2
-
3
- Copyright (c) 2020-2022 thZero.com
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
-
7
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
-
1
+ MIT License
2
+
3
+ Copyright (c) 2020-2022 thZero.com
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
9
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json CHANGED
@@ -1,29 +1,29 @@
1
- {
2
- "name": "@thzero/library_client_firebase",
3
- "version": "0.16.2",
4
- "version_major": 0,
5
- "version_minor": 16,
6
- "version_patch": 2,
7
- "version_date": "08/29/2022",
8
- "author": "thZero",
9
- "license": "MIT",
10
- "repository": {
11
- "type": "git",
12
- "url": "git+https://github.com/thzero/library_client_firebase.git"
13
- },
14
- "bugs": {
15
- "url": "https://github.com/thzero/library_client_firebase/issues"
16
- },
17
- "homepage": "https://github.com/thzero/library_client_firebase#readme",
18
- "scripts": {
19
- "cli-update": "library-cli --updateversion --pi",
20
- "test": "echo \"Error: no test specified\" && exit 1"
21
- },
22
- "dependencies": {
23
- "firebase": "^9.9.3"
24
- },
25
- "peerDependencies": {
26
- "@thzero/library_client": "^0.16",
27
- "@thzero/library_common": "^0.16"
28
- }
1
+ {
2
+ "name": "@thzero/library_client_firebase",
3
+ "version": "0.16.4",
4
+ "version_major": 0,
5
+ "version_minor": 16,
6
+ "version_patch": 4,
7
+ "version_date": "11/23/2022",
8
+ "author": "thZero",
9
+ "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/thzero/library_client_firebase.git"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/thzero/library_client_firebase/issues"
16
+ },
17
+ "homepage": "https://github.com/thzero/library_client_firebase#readme",
18
+ "scripts": {
19
+ "cli-update": "library-cli --updateversion --pi",
20
+ "test": "echo \"Error: no test specified\" && exit 1"
21
+ },
22
+ "dependencies": {
23
+ "firebase": "^9.14.0"
24
+ },
25
+ "peerDependencies": {
26
+ "@thzero/library_client": "^0.16",
27
+ "@thzero/library_common": "^0.16"
28
+ }
29
29
  }
package/service/index.js CHANGED
@@ -1,289 +1,289 @@
1
- // import firebase from 'firebase/app';
2
- // import 'firebase/auth';
3
- import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
4
-
5
- import LibraryConstants from '@thzero/library_client/constants';
6
-
7
- import LibraryUtility from '@thzero/library_common/utility';
8
-
9
- import UserAuthService from '@thzero/library_client/service/auth/user';
10
-
11
- class FirebaseAuthService extends UserAuthService {
12
- constructor() {
13
- super();
14
-
15
- // this._lock = false
16
- this._polling = null;
17
-
18
- this._serviceRouter = null;
19
- }
20
-
21
- async deleteUser(correlationId) {
22
- try {
23
- const user = await getAuth().currentUser;
24
- if (!user)
25
- return;
26
-
27
- await user.delete();
28
- await this._serviceUser.resetUser(correlationId);
29
- }
30
- catch (err) {
31
- this._logger.exception('FirebaseAuthService', 'deleteUser', err, correlationId);
32
- throw err;
33
- }
34
- }
35
-
36
- async init(injector) {
37
- await super.init(injector);
38
-
39
- this._serviceRouter = this._injector.getService(LibraryConstants.InjectorKeys.SERVICE_ROUTER);
40
- }
41
-
42
- get externalUser() {
43
- const user = getAuth().currentUser;
44
- this._logger.debug('FirebaseAuthService', 'tokenUser', 'user', user, LibraryUtility.generateId());
45
- return user;
46
- }
47
-
48
- get isAuthenticated() {
49
- const user = getAuth().currentUser;
50
- this._logger.debug('FirebaseAuthService', 'isAuthenticated', 'user', user);
51
- return user != null;
52
- }
53
-
54
- async onAuthStateChanged(user) {
55
- const correlationId = LibraryUtility.generateId();
56
- try {
57
- await this.updateExternalUser(correlationId, user, true);
58
- // if (!user)
59
- // return
60
-
61
- await this._serviceUser.setAuthCompleted(correlationId, true);
62
- this._serviceEvent.emit(LibraryConstants.EventKeys.Auth.Refresh, user);
63
- }
64
- catch (err) {
65
- this._logger.exception('FirebaseAuthService', 'onAuthStateChanged', err, correlationId);
66
- }
67
-
68
- // try {
69
- // if (!user) {
70
- // if (this._polling)
71
- // clearInterval(this._polling)
72
- // return
73
- // }
74
-
75
- // const self = this
76
- // this._polling = setInterval(async () => {
77
- // await self.refreshToken(self.user, true).then()
78
- // }, 60 * 1000)
79
- // }
80
- // catch (err) {
81
- // this._logger.exception('FirebaseAuthService', 'onAuthStateChanged', err, correlationId)
82
- // }
83
- }
84
-
85
- async signIn(correlationId) {
86
- if (this.isAuthenticated)
87
- return false;
88
-
89
- try {
90
- const provider = new GoogleAuthProvider();
91
- const result = await signInWithPopup(getAuth(), provider);
92
- if (result && result.user) {
93
- //const credential = GoogleAuthProvider.credentialFromResult(result);
94
- // const token = credential.accessToken;
95
- this.updateExternalUser(correlationId, result.user);
96
- // this._serviceRouter.route('/')
97
- window.location.href = '/';
98
- return true;
99
- }
100
-
101
- this.updateExternalUser(correlationId, null);
102
- }
103
- catch (err) {
104
- this._logger.exception('FirebaseAuthService', 'signIn', err, correlationId);
105
- this.updateExternalUser(correlationId, null);
106
- }
107
-
108
- return true;
109
- }
110
-
111
- async signInCompleted(correlationId) {
112
- // if (await auth.isAuthenticated())
113
- // return
114
- // getAuth().getRedirectResult().then(function (result) {
115
- // if (result.credential) {
116
- // // This gives you a Google Access Token. You can use it to access the Google API.
117
- // // eslint-disable-next-line
118
- // var token = result.credential.accessToken
119
- // // ...
120
- // }
121
- // // The signed-in user info.
122
- // // eslint-disable-next-line
123
- // var user = result.user
124
- // }).catch(function (error) {
125
- // // Handle Errors here.
126
- // // eslint-disable-next-line
127
- // var errorCode = error.code
128
- // // eslint-disable-next-line
129
- // var errorMessage = error.message
130
- // // The email of the user's account used.
131
- // // eslint-disable-next-line
132
- // var email = error.email
133
- // // The firebase.auth.AuthCredential type that was used.
134
- // // eslint-disable-next-line
135
- // var credential = error.credential
136
- // // ...
137
- // })
138
- }
139
-
140
- async signOut(correlationId) {
141
- try {
142
- // await getAuth().signOut()
143
- // await this._serviceUser.dispatcher.user.setTokenResult(correlationId, null)
144
- // await this._serviceUser.dispatcher.user.setClaims(correlationId, null)
145
- // await this._serviceUser.dispatcher.user.setUser(correlationId, null)
146
- // await this._serviceUser.dispatcher.user.setLoggedIn(correlationId, false)
147
-
148
- const list = [];
149
- list.push(getAuth().signOut());
150
- // list.push(this._serviceUser.dispatcher.user.setTokenResult(correlationId, null))
151
- // list.push(this._serviceUser.dispatcher.user.setClaims(correlationId, null))
152
- // list.push(this._serviceUser.dispatcher.user.setUser(correlationId, null))
153
- // list.push(this._serviceUser.dispatcher.user.setLoggedIn(correlationId, false))
154
- list.push(this._serviceUser.resetUser(correlationId));
155
- list.push(this._serviceUser.setAuthCompleted(correlationId, false));
156
-
157
- await Promise.all(list);
158
-
159
- // this._serviceRouter.route('/')
160
- window.location.href = '/';
161
- }
162
- catch (err) {
163
- this._logger.exception('FirebaseAuthService', 'signOut', err, correlationId);
164
- }
165
- }
166
-
167
- // async token(forceRefresh) {
168
- // if (!forceRefresh)
169
- // forceRefresh = false
170
-
171
- // const user = this.user
172
- // this._logger.debug('FirebaseAuthService', 'token', 'user', user, correlationId);
173
- // if (!user)
174
- // return null
175
-
176
- // this._logger.debug('FirebaseAuthService', 'token', 'forceRefresh', forceRefresh, correlationId)
177
- // return this.refreshToken'FirebaseAuthService', 'token', user, forceRefresh)
178
- // }
179
-
180
- async refreshToken(correlationId, user, forceRefresh) {
181
- forceRefresh = forceRefresh !== null ? forceRefresh : false;
182
-
183
- try {
184
- this._logger.debug('FirebaseAuthService', 'refreshToken', 'user', user, correlationId);
185
- if (!user) {
186
- await this._serviceUser.setTokenResult(correlationId, null);
187
- await this._serviceUser.setClaims(correlationId, null);
188
- this.announceToken(correlationId, user, null);
189
-
190
- return;
191
- }
192
-
193
- this._logger.debug('FirebaseAuthService', 'refreshToken', 'forceRefresh', forceRefresh, correlationId);
194
- const currentUser = await getAuth().currentUser;
195
- this._logger.debug('FirebaseAuthService', 'refreshToken', 'currentUser', currentUser, correlationId);
196
- if (!currentUser)
197
- return;
198
-
199
- const tokenResult = await currentUser.getIdTokenResult(forceRefresh);
200
- if (tokenResult) {
201
- await this._serviceUser.setTokenResult(correlationId, tokenResult);
202
- const token = tokenResult.token;
203
- let claims = token != null ? tokenResult.claims : null;
204
- this._logger.debug('FirebaseAuthService', 'refreshToken', 'claims', claims, correlationId);
205
- claims = claims != null ? claims.custom : null;
206
- this._logger.debug('FirebaseAuthService', 'refreshToken', 'claims.custom', claims, correlationId);
207
- await this._serviceUser.setClaims(correlationId, claims);
208
-
209
- this.announceToken(correlationId, user, token);
210
-
211
- const expired = LibraryUtility.getDateParse(tokenResult.expirationTime);
212
- const now = LibraryUtility.getDate();
213
- const diff = expired.diff(now);
214
- const min = 5 * 60 * 1000;
215
- if (diff <= min) {
216
- await this.refreshToken(correlationId, getAuth().currentUser, true).then();
217
- return;
218
- }
219
-
220
- if (this._polling)
221
- clearInterval(this._polling);
222
-
223
- const self = this;
224
- this._polling = setInterval(async () => {
225
- await self.refreshToken(correlationId, self.user, true).then();
226
- }, diff); // 60 * 1000)
227
- }
228
- else {
229
- await this._serviceUser.setTokenResult(correlationId, null);
230
- await this._serviceUser.setClaims(correlationId, null);
231
-
232
- this.announceToken(correlationId, user, token);
233
-
234
- if (this._polling)
235
- clearInterval(this._polling);
236
- }
237
- }
238
- catch (err) {
239
- this._logger.exception('FirebaseAuthService', 'refreshToken', err, correlationId);
240
- throw err;
241
- }
242
- }
243
-
244
- async updateExternalUser(correlationId, user) {
245
- // if (this._lock)
246
- // return
247
-
248
- try {
249
- // if (this._lock)
250
- // return
251
-
252
- // this._lock = true
253
-
254
- user = this._convert(correlationId, user);
255
-
256
- await this._serviceUser.setUser(correlationId, null);
257
- await this._serviceUser.setLoggedIn(correlationId, false);
258
-
259
- if (!user)
260
- return;
261
-
262
- await this.refreshToken(correlationId, user);
263
- const service = this._injector.getService(LibraryConstants.InjectorKeys.SERVICE_USER);
264
- const response = await service.updateExternal(correlationId, user);
265
- if (this._hasSucceeded(response)) {
266
- await this._serviceUser.setUser(correlationId, response.results);
267
- await this._serviceUser.setLoggedIn(correlationId, true);
268
- }
269
- }
270
- finally {
271
- // this._lock = false
272
- }
273
- }
274
-
275
- _convert(correlationId, requestedUser) {
276
- if (requestedUser) {
277
- const user = {};
278
- user.id = requestedUser.uid;
279
- user.name = requestedUser.displayName;
280
- user.picture = requestedUser.photoURL;
281
- user.email = requestedUser.email;
282
- return user;
283
- }
284
-
285
- return null;
286
- }
287
- }
288
-
289
- export default FirebaseAuthService;
1
+ // import firebase from 'firebase/app';
2
+ // import 'firebase/auth';
3
+ import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
4
+
5
+ import LibraryConstants from '@thzero/library_client/constants';
6
+
7
+ import LibraryUtility from '@thzero/library_common/utility';
8
+
9
+ import UserAuthService from '@thzero/library_client/service/auth/user';
10
+
11
+ class FirebaseAuthService extends UserAuthService {
12
+ constructor() {
13
+ super();
14
+
15
+ // this._lock = false
16
+ this._polling = null;
17
+
18
+ this._serviceRouter = null;
19
+ }
20
+
21
+ async deleteUser(correlationId) {
22
+ try {
23
+ const user = await getAuth().currentUser;
24
+ if (!user)
25
+ return;
26
+
27
+ await user.delete();
28
+ await this._serviceUser.resetUser(correlationId);
29
+ }
30
+ catch (err) {
31
+ this._logger.exception('FirebaseAuthService', 'deleteUser', err, correlationId);
32
+ throw err;
33
+ }
34
+ }
35
+
36
+ async init(injector) {
37
+ await super.init(injector);
38
+
39
+ this._serviceRouter = this._injector.getService(LibraryConstants.InjectorKeys.SERVICE_ROUTER);
40
+ }
41
+
42
+ get externalUser() {
43
+ const user = getAuth().currentUser;
44
+ this._logger.debug('FirebaseAuthService', 'tokenUser', 'user', user, LibraryUtility.generateId());
45
+ return user;
46
+ }
47
+
48
+ get isAuthenticated() {
49
+ const user = getAuth().currentUser;
50
+ this._logger.debug('FirebaseAuthService', 'isAuthenticated', 'user', user);
51
+ return user != null;
52
+ }
53
+
54
+ async onAuthStateChanged(user) {
55
+ const correlationId = LibraryUtility.generateId();
56
+ try {
57
+ await this.updateExternalUser(correlationId, user, true);
58
+ // if (!user)
59
+ // return
60
+
61
+ await this._serviceUser.setAuthCompleted(correlationId, true);
62
+ this._serviceEvent.emit(LibraryConstants.EventKeys.Auth.Refresh, user);
63
+ }
64
+ catch (err) {
65
+ this._logger.exception('FirebaseAuthService', 'onAuthStateChanged', err, correlationId);
66
+ }
67
+
68
+ // try {
69
+ // if (!user) {
70
+ // if (this._polling)
71
+ // clearInterval(this._polling)
72
+ // return
73
+ // }
74
+
75
+ // const self = this
76
+ // this._polling = setInterval(async () => {
77
+ // await self.refreshToken(self.user, true).then()
78
+ // }, 60 * 1000)
79
+ // }
80
+ // catch (err) {
81
+ // this._logger.exception('FirebaseAuthService', 'onAuthStateChanged', err, correlationId)
82
+ // }
83
+ }
84
+
85
+ async signIn(correlationId) {
86
+ if (this.isAuthenticated)
87
+ return false;
88
+
89
+ try {
90
+ const provider = new GoogleAuthProvider();
91
+ const result = await signInWithPopup(getAuth(), provider);
92
+ if (result && result.user) {
93
+ //const credential = GoogleAuthProvider.credentialFromResult(result);
94
+ // const token = credential.accessToken;
95
+ this.updateExternalUser(correlationId, result.user);
96
+ // this._serviceRouter.route('/')
97
+ window.location.href = '/';
98
+ return true;
99
+ }
100
+
101
+ this.updateExternalUser(correlationId, null);
102
+ }
103
+ catch (err) {
104
+ this._logger.exception('FirebaseAuthService', 'signIn', err, correlationId);
105
+ this.updateExternalUser(correlationId, null);
106
+ }
107
+
108
+ return true;
109
+ }
110
+
111
+ async signInCompleted(correlationId) {
112
+ // if (await auth.isAuthenticated())
113
+ // return
114
+ // getAuth().getRedirectResult().then(function (result) {
115
+ // if (result.credential) {
116
+ // // This gives you a Google Access Token. You can use it to access the Google API.
117
+ // // eslint-disable-next-line
118
+ // var token = result.credential.accessToken
119
+ // // ...
120
+ // }
121
+ // // The signed-in user info.
122
+ // // eslint-disable-next-line
123
+ // var user = result.user
124
+ // }).catch(function (error) {
125
+ // // Handle Errors here.
126
+ // // eslint-disable-next-line
127
+ // var errorCode = error.code
128
+ // // eslint-disable-next-line
129
+ // var errorMessage = error.message
130
+ // // The email of the user's account used.
131
+ // // eslint-disable-next-line
132
+ // var email = error.email
133
+ // // The firebase.auth.AuthCredential type that was used.
134
+ // // eslint-disable-next-line
135
+ // var credential = error.credential
136
+ // // ...
137
+ // })
138
+ }
139
+
140
+ async signOut(correlationId) {
141
+ try {
142
+ // await getAuth().signOut()
143
+ // await this._serviceUser.dispatcher.user.setTokenResult(correlationId, null)
144
+ // await this._serviceUser.dispatcher.user.setClaims(correlationId, null)
145
+ // await this._serviceUser.dispatcher.user.setUser(correlationId, null)
146
+ // await this._serviceUser.dispatcher.user.setLoggedIn(correlationId, false)
147
+
148
+ const list = [];
149
+ list.push(getAuth().signOut());
150
+ // list.push(this._serviceUser.dispatcher.user.setTokenResult(correlationId, null))
151
+ // list.push(this._serviceUser.dispatcher.user.setClaims(correlationId, null))
152
+ // list.push(this._serviceUser.dispatcher.user.setUser(correlationId, null))
153
+ // list.push(this._serviceUser.dispatcher.user.setLoggedIn(correlationId, false))
154
+ list.push(this._serviceUser.resetUser(correlationId));
155
+ list.push(this._serviceUser.setAuthCompleted(correlationId, false));
156
+
157
+ await Promise.all(list);
158
+
159
+ // this._serviceRouter.route('/')
160
+ window.location.href = '/';
161
+ }
162
+ catch (err) {
163
+ this._logger.exception('FirebaseAuthService', 'signOut', err, correlationId);
164
+ }
165
+ }
166
+
167
+ // async token(forceRefresh) {
168
+ // if (!forceRefresh)
169
+ // forceRefresh = false
170
+
171
+ // const user = this.user
172
+ // this._logger.debug('FirebaseAuthService', 'token', 'user', user, correlationId);
173
+ // if (!user)
174
+ // return null
175
+
176
+ // this._logger.debug('FirebaseAuthService', 'token', 'forceRefresh', forceRefresh, correlationId)
177
+ // return this.refreshToken'FirebaseAuthService', 'token', user, forceRefresh)
178
+ // }
179
+
180
+ async refreshToken(correlationId, user, forceRefresh) {
181
+ forceRefresh = forceRefresh !== null ? forceRefresh : false;
182
+
183
+ try {
184
+ this._logger.debug('FirebaseAuthService', 'refreshToken', 'user', user, correlationId);
185
+ if (!user) {
186
+ await this._serviceUser.setTokenResult(correlationId, null);
187
+ await this._serviceUser.setClaims(correlationId, null);
188
+ this.announceToken(correlationId, user, null);
189
+
190
+ return;
191
+ }
192
+
193
+ this._logger.debug('FirebaseAuthService', 'refreshToken', 'forceRefresh', forceRefresh, correlationId);
194
+ const currentUser = await getAuth().currentUser;
195
+ this._logger.debug('FirebaseAuthService', 'refreshToken', 'currentUser', currentUser, correlationId);
196
+ if (!currentUser)
197
+ return;
198
+
199
+ const tokenResult = await currentUser.getIdTokenResult(forceRefresh);
200
+ if (tokenResult) {
201
+ await this._serviceUser.setTokenResult(correlationId, tokenResult);
202
+ const token = tokenResult.token;
203
+ let claims = token != null ? tokenResult.claims : null;
204
+ this._logger.debug('FirebaseAuthService', 'refreshToken', 'claims', claims, correlationId);
205
+ claims = claims != null ? claims.custom : null;
206
+ this._logger.debug('FirebaseAuthService', 'refreshToken', 'claims.custom', claims, correlationId);
207
+ await this._serviceUser.setClaims(correlationId, claims);
208
+
209
+ this.announceToken(correlationId, user, token);
210
+
211
+ const expired = LibraryUtility.getDateParse(tokenResult.expirationTime);
212
+ const now = LibraryUtility.getDate();
213
+ const diff = expired.diff(now);
214
+ const min = 5 * 60 * 1000;
215
+ if (diff <= min) {
216
+ await this.refreshToken(correlationId, getAuth().currentUser, true).then();
217
+ return;
218
+ }
219
+
220
+ if (this._polling)
221
+ clearInterval(this._polling);
222
+
223
+ const self = this;
224
+ this._polling = setInterval(async () => {
225
+ await self.refreshToken(correlationId, self.user, true).then();
226
+ }, diff); // 60 * 1000)
227
+ }
228
+ else {
229
+ await this._serviceUser.setTokenResult(correlationId, null);
230
+ await this._serviceUser.setClaims(correlationId, null);
231
+
232
+ this.announceToken(correlationId, user, token);
233
+
234
+ if (this._polling)
235
+ clearInterval(this._polling);
236
+ }
237
+ }
238
+ catch (err) {
239
+ this._logger.exception('FirebaseAuthService', 'refreshToken', err, correlationId);
240
+ throw err;
241
+ }
242
+ }
243
+
244
+ async updateExternalUser(correlationId, user) {
245
+ // if (this._lock)
246
+ // return
247
+
248
+ try {
249
+ // if (this._lock)
250
+ // return
251
+
252
+ // this._lock = true
253
+
254
+ user = this._convert(correlationId, user);
255
+
256
+ await this._serviceUser.setUser(correlationId, null);
257
+ await this._serviceUser.setLoggedIn(correlationId, false);
258
+
259
+ if (!user)
260
+ return;
261
+
262
+ await this.refreshToken(correlationId, user);
263
+ const service = this._injector.getService(LibraryConstants.InjectorKeys.SERVICE_USER);
264
+ const response = await service.updateExternal(correlationId, user);
265
+ if (this._hasSucceeded(response)) {
266
+ await this._serviceUser.setUser(correlationId, response.results);
267
+ await this._serviceUser.setLoggedIn(correlationId, true);
268
+ }
269
+ }
270
+ finally {
271
+ // this._lock = false
272
+ }
273
+ }
274
+
275
+ _convert(correlationId, requestedUser) {
276
+ if (requestedUser) {
277
+ const user = {};
278
+ user.id = requestedUser.uid;
279
+ user.name = requestedUser.displayName;
280
+ user.picture = requestedUser.photoURL;
281
+ user.email = requestedUser.email;
282
+ return user;
283
+ }
284
+
285
+ return null;
286
+ }
287
+ }
288
+
289
+ export default FirebaseAuthService;