Реагируйте на Native, Google Authentication и хранение в Firebase - PullRequest
0 голосов
/ 16 марта 2020

Я пытаюсь разрешить пользователям входить в мое приложение с помощью входа в Google. Когда я нажимаю кнопку «Войти в систему с помощью учетной записи Google», я вижу всплывающее окно Google и могу успешно выбрать свою учетную запись. Тем не менее, после того, как я выбрал свой аккаунт, это не отправка в firebase. Вот мой код для лучшего понимания:

import React, {Component} from 'react';
import{View,Text,StyleSheet,Button} from 'react-native'
import * as Google from "expo-google-app-auth"
import firebase from 'firebase'



class LoginScreen extends Component{

    isUserEqual=(googleUser, firebaseUser) =>{
        if (firebaseUser) {
          var providerData = firebaseUser.providerData;
          for (var i = 0; i < providerData.length; i++) {
            if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
                providerData[i].uid === googleUser.getBasicProfile().getId()) {
              // We don't need to reauth the Firebase connection.
              return true; 
            }
          }
        }
        return false;
      }

    onSignIn = googleUser => {
        console.log('Google Auth Response', googleUser);
        // We need to register an Observer on Firebase Auth to make sure auth is initialized.
        var unsubscribe = firebase.auth().onAuthStateChanged(function(firebaseUser) {
          unsubscribe();
          // Check if we are already signed-in Firebase with the correct user.
          if (!this.isUserEqual(googleUser, firebaseUser)) {
              console.log("Successsss")
            // Build Firebase credential with the Google ID token.
            var credential = firebase.auth.GoogleAuthProvider.credential(


                //googleUser.getAuthResponse().id_token
                googleUser.idToken,
                googleUser.accessToken
                );console.log("Sucesssssss22")
            // Sign in with credential from the Google user.
            firebase.auth().signInWithCredential(credential).then(function(result){
                firebase.database().ref('/users/'+result.user.uid)
                .set({
                    gmail:result.user.email,
                    profile_picture: result.additionalUserInfo.profile.picture,
                    locale:result.additionalUserInfo.profile.locale,
                    first_name:result.additionalUserInfo.profile.given_name,
                    last_name: result.additionalUserInfo.profile.family_name
                })
                .then(function(snapshot){
                   console.log("Snapshot",snapshot)
                })

            }).
            catch(function(error) {
              // Handle Errors here.
              var errorCode = error.code;
              var errorMessage = error.message;
              // The email of the user's account used.
              var email = error.email;
              // The firebase.auth.AuthCredential type that was used.
              var credential = error.credential;
              // ...
            });
          } else {
            console.log('User already signed-in Firebase.');
          }
        }.bind(this));
      }





    signInWithGoogleAsync= async()=> {
        try {
        console.log("Hello")
          const result = await Google.logInAsync({
            behaviour:'web',
            //androidClientId: '438839046-m3rgh84v26571im2i2aicml079tndp1g.apps.googleusercontent.com',
            iosClientId: '438839046-muvd8mrrvptacbov93r5numfepbbpcmj.apps.googleusercontent.com',
            scopes: ['profile', 'email'],
          });

          if (result.type === 'success') { 
            console.log("Hello2")
            this.onSignIn(result) 
            return result.accessToken;  
          } else {
            return { cancelled: true };
          }
        } catch (e) {
            console.log("Hell3o")
          return { error: true };
        }
      }




    render(){
        return(
            <View style = {styles.container}>
                <Button
                title = 'Sign In with Google'
                onPress={ ()=> this.signInWithGoogleAsync()}/>
            </View>
        )
    }
}


const styles = StyleSheet.create({
    container: {
        flex:1,
        alignItems : 'center',
        justifyContent:'center'
    }
})
export default LoginScreen
...