forked from twiegan/ScrapeGoats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
55 lines (51 loc) · 1.77 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import {
GoogleAuthProvider,
onAuthStateChanged,
signInWithCredential,
getAuth,
signOut,
} from "firebase/auth";
import { auth } from "./firebase";
export const onSignInGoogle = googleUser => {
console.log('Google Auth Response from util.js', googleUser);
// We need to register an Observer on Firebase Auth to make sure auth is initialized.
const unsubscribe = onAuthStateChanged(auth, (firebaseUser) => {
unsubscribe();
// Check if we are already signed-in Firebase with the correct user.
if (!isUserEqualGoogle(googleUser, firebaseUser)) {
// Build Firebase credential with the Google ID token.
const credential = GoogleAuthProvider.credential(
googleUser.idToken,
googleUser.accessToken
);
// Sign in with credential from the Google user.
signInWithCredential(auth, credential).then(() => {
console.log('user signed in')
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The credential that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
} else {
console.log('User is already signed-in Firebase.');
}
});
}
const isUserEqualGoogle = (googleUser, firebaseUser) => {
if (firebaseUser) {
const providerData = firebaseUser.providerData;
for (let i = 0; i < providerData.length; i++) {
if (providerData[i].providerId === GoogleAuthProvider.PROVIDER_ID &&
providerData[i].uid === googleUser.getBasicProfile().getId()) {
// We don't need to reauth the Firebase connection.
return true;
}
}
}
return false;
}