Почему я не могу связать вход в систему с паролем электронной почты Firebase для входа в Google? - PullRequest
0 голосов
/ 11 июля 2019

Я успешно внедрил Firebase Google Sign-In в моем приложении для Android, и он отлично работает. Но я хочу, чтобы пользователи также входили в приложение, используя электронную почту и пароль. Итак, я следовал этому учебнику, чтобы связать вход в Google с входом по электронной почте и паролем. Но, когда я пытаюсь войти с помощью email-пароля, введите следующий код:

firebaseAuth.signInWithEmailAndPassword(email, password)
   .addOnCompleteListener(new OnCompleteListener<AuthResult>()
   {
      @Override
      public void onComplete(@NonNull Task<AuthResult> task)
      {
         if (task.isSuccessful())
         {
             //code to link accounts
         }
         else
         {
             Toast.makeText(context, "SIgn In Error", Toast.LENGTH_SHORT).show();
             System.out.println("SIGN IN: " +  task.getException());
         }
      }
  });

Показывает исключение:

com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The password is invalid or the user does not have a password.

Что не так с кодом?

Ответы [ 2 ]

1 голос
/ 11 июля 2019

Из сообщения об ошибке кажется, что вы звоните signInWithEmailAndPassword для пользователя, который еще не был создан.

Вы можете вызвать signInWithEmailAndPassword(email, password) только для входа в систему пользователя, который был ранее создан с помощью createUserWithEmailAndPassword(email, password).Вы явно не можете использовать его для входа в систему пользователя, который ранее входил в систему или создавался только с другим провайдером идентификации, таким как вход в Google.

Если вы хотите, чтобы тот же пользователь, который выполнил вход через Google, также мог войти в систему с паролем, характерным для вашего приложения, вам нужно будет также создать эти дополнительные учетные данные, а затем ссылку два поставщика (Google + электронная почта / пароль).

0 голосов
/ 11 июля 2019

Та же проблема возникает со мной, но я изменяю какой-то кусок кода, и он работает правильно.

мой код здесь ...

/*This is th Example of google Sign in*/
import React from 'react';
import { StyleSheet, Text, View, Alert } from 'react-native';
import {
  GoogleSignin,
  GoogleSigninButton,
  statusCodes,
} from 'react-native-google-signin';
export default class GmailLogin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userInfo: '',
    };
  }
  componentDidMount() {
    GoogleSignin.configure({
      //It is mandatory to call this method before attempting to call signIn()
      scopes: ['https://www.googleapis.com/auth/drive.readonly'],
      // Repleace with your webClientId generated from Firebase console
      webClientId:
        'Replace Your Web Client Id here',
    });
  }
  _signIn = async () => {
    //Prompts a modal to let the user sign in into your application.
    try {
      await GoogleSignin.hasPlayServices({
        //Check if device has Google Play Services installed.
        //Always resolves to true on iOS.
        showPlayServicesUpdateDialog: true,
      });
      const userInfo = GoogleSignin.signIn();
      console.log('User Info --> ', userInfo);
      this.setState({ userInfo: userInfo });

    } catch (error) {
      console.log('Message', error.message);
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        console.log('User Cancelled the Login Flow');
      } else if (error.code === statusCodes.IN_PROGRESS) {
        console.log('Signing In');
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        console.log('Play Services Not Available or Outdated');
      } else {
        console.log('Some Other Error Happened');
      }
    }

    this.props.navigation.navigate('Login')
  };
  _getCurrentUser = async () => {
    //May be called eg. in the componentDidMount of your main component.
    //This method returns the current user
    //if they already signed in and null otherwise.
    try {
      const userInfo = await GoogleSignin.signInSilently();
      this.setState({ userInfo });
    } catch (error) {
      console.error(error);
    }
  };
  _signOut = async () => {
    //Remove user session from the device.
    try {
      await GoogleSignin.revokeAccess();
      await GoogleSignin.signOut();
      this.setState({ user: null }); // Remove the user from your app's state as well
    } catch (error) {
      console.error(error);
    }
  };
  _revokeAccess = async () => {
    //Remove your application from the user authorized applications.
    try {
      await GoogleSignin.revokeAccess();
      console.log('deleted');
    } catch (error) {
      console.error(error);
    }
  };
  render() {
    return (
      <View style={styles.container}>
        <GoogleSigninButton
          style={{ width: 312, height: 48 }}
          size={GoogleSigninButton.Size.Wide}
          color={GoogleSigninButton.Color.Light}
          onPress={this._signIn}
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Добавить этот файл в setting.gradle

include ':react-native-google-signin'
project(':react-native-google-signin').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-google-signin/android')

И мой код MainApplication.jav ..

package com.uiapp;

import android.app.Application;

import co.apptailor.googlesignin.RNGoogleSigninPackage;

import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.auth.RNFirebaseAuthPackage;

import com.facebook.react.ReactApplication;
// import io.invertase.firebase.RNFirebaseAdMobPackage;
import com.smarkets.paypal.RNPaypalPackage;
import com.inprogress.reactnativeyoutube.ReactNativeYouTube;
import co.apptailor.googlesignin.RNGoogleSigninPackage;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.imagepicker.ImagePickerPackage;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import com.inprogress.reactnativeyoutube.ReactNativeYouTube;

import com.smarkets.paypal.RNPaypalPackage;

import com.facebook.FacebookSdk;
import com.facebook.CallbackManager;
import com.facebook.appevents.AppEventsLogger;
import android.content.Intent;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

    private static CallbackManager mCallbackManager = CallbackManager.Factory.create();
    protected static CallbackManager getCallbackManager() {
      return mCallbackManager;
    }

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
            // new RNFirebaseAdMobPackage(),
            new RNPaypalPackage(),
            new ReactNativeYouTube(),
            new RNGoogleSigninPackage(),
            new FBSDKPackage(mCallbackManager), 
            new ImagePickerPackage(),
            new RNGestureHandlerPackage(),
            new RNFirebasePackage(),
           new RNFirebaseAuthPackage()


      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
//   @Override
// public void onActivityResult(int requestCode, int resultCode, Intent data) {
//     super.onActivityResult(requestCode, resultCode, data);
//     MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data);
// }

}

пожалуйста, не кодируйте, так как некоторые изменения кода MainApplication.java требуют только места.

и вставьте код в свое приложение / android / build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.4.0")
        classpath 'com.google.gms:google-services:4.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

Если вы выполните эти шаги, это решит вашу проблему ..

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...