File tree 1 file changed +23
-24
lines changed
1 file changed +23
-24
lines changed Original file line number Diff line number Diff line change 1
- import admin from 'firebase-admin' ;
1
+ import { initializeApp , applicationDefault } from 'firebase-admin/app' ;
2
+ import { getAuth } from 'firebase-admin/auth' ;
2
3
3
- import { getConfig } from '../config' ;
4
-
5
- const googleApplicationCredentials = JSON . parse ( getConfig ( 'GOOGLE_APPLICATION_CREDENTIALS' ) ) ;
6
- let firebaseApp : admin . app . App ;
7
-
8
- const getFirebaseApp = ( ) : admin . app . App => {
9
- if ( firebaseApp ) {
10
- return firebaseApp ;
11
- }
12
-
13
- return admin . initializeApp ( {
14
- credential : admin . credential . cert ( googleApplicationCredentials ) ,
15
- } ) ;
16
- } ;
4
+ initializeApp ( {
5
+ credential : applicationDefault ( ) ,
6
+ } ) ;
17
7
18
8
export const createUserInFirebase = async ( email : string , displayName : string ) => {
19
- const firebaseUser = await getFirebaseApp ( ) . auth ( ) . getUserByEmail ( email ) ;
20
-
21
- if ( ! firebaseUser ) {
22
- return await firebaseApp . auth ( ) . createUser ( {
23
- email,
24
- displayName,
25
- } ) ;
9
+ try {
10
+ const firebaseUser = await getAuth ( ) . getUserByEmail ( email ) ;
11
+ return firebaseUser ;
12
+ } catch ( error : any ) {
13
+ // If the user is not found, an error is thrown, and the user is created
14
+ if ( error . code === 'auth/user-not-found' ) {
15
+ try {
16
+ const createdUser = await getAuth ( ) . createUser ( {
17
+ email,
18
+ displayName,
19
+ } ) ;
20
+ return createdUser ;
21
+ } catch ( e ) {
22
+ console . error ( e ) ;
23
+ throw new Error ( 'Error creating user in firebase' ) ;
24
+ }
25
+ }
26
+ throw new Error ( 'Error creating firebase user ' , error ) ;
26
27
}
27
-
28
- return firebaseUser ;
29
28
} ;
You can’t perform that action at this time.
0 commit comments