войти через фейсбук в firebase в реагировать на родной не работает, но токен получен - PullRequest
0 голосов
/ 11 марта 2019

Я пытаюсь пройти проверку подлинности с помощью fb-auth в firebase, в реактивном проекте.

с использованием async, я звоню в firebase, а затем в facebook.

async loginWithFacebook() {
    const { type, token } = await Expo.Facebook.logInWithReadPermissionsAsync(
      "830893840610100",
      {
        permissions: ["public_profile"]
      }
    );

    if (type === "success") {
      console.log("success \n", token);
      // if yes, then take credentials from fb_auth_provider and pass to firebase
      const credentials = f.auth().FacebookAuthProvider.credential(token);
      try {
        f.auth()
          .signInWithCredential(credentials)
          .catch(err => {
            console.log("error occured \n", err);
          });
      } catch {
        console.log("Can't login with facebook");
      }
    }

после входа в систему, нажав на кнопку, она вызывает вышеуказанную функцию как

<TouchableHighlight
          onPress={() => this.loginWithFacebook()}
          style={{ backgroundColor: "green" }}
        >
          <Text style={{ color: "white", padding: 10 }}>
            Login with Facebook
          </Text>
        </TouchableHighlight>

, но я получаю ошибку как

[23:31:05] [Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_config.f.auth().FacebookAuthProvider.credential')]
* App.js:30:56 in loginWithFacebook$
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:62:44 in tryCatch
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:288:30 in invoke

screenshot

Он возвращает токен, который выводится на терминал.

Файл App.js содержит

import React from "react";
import { StyleSheet, Text, View, TouchableHighlight } from "react-native";
import { f, auth, database, storage } from "./config/config";

export default class App extends React.Component {
  constructor(props) {
    super(props);

    // this.registerUser("testing@gmail.com", "password@123");

    f.auth().onAuthStateChanged(function(user) {
      if (user) {
        console.log("Logged In ", user);
      } else {
        console.log("Logged Out");
      }
    });
  }
  // Facebook-login
  async loginWithFacebook() {
    const { type, token } = await Expo.Facebook.logInWithReadPermissionsAsync(
      "830893840610100",
      {
        permissions: ["public_profile"]
      }
    );

    if (type === "success") {
      console.log("success \n", token);
      // if yes, then take credentials from fb_auth_provider and pass to firebase
      const credentials = f.auth().FacebookAuthProvider.credential(token);
      try {
        f.auth()
          .signInWithCredential(credentials)
          .catch(err => {
            console.log("error occured \n", err);
          });
      } catch {
        console.log("Can't login with facebook");
      }
    }
  }

  // to Sign-Out User
  //   auth
  //     .signOut()
  //     .then(() => {
  //       console.log("Signing Out User");
  //     })
  //     .catch(e => {
  //       console.log(e);
  //     });
  // }

  registerUser = (email, password) => {
    console.log(email, password);
    auth
      .createUserWithEmailAndPassword(email, password)
      .then(userObj => {
        console.log(email, password, userObj);
        alert(email, password, userObj);
      })
      .catch(error => {
        console.log("Error is occured", error);
      });
  };

  render() {
    return (
      <View style={styles.container}>
        <Text>App.js Component </Text>

        <TouchableHighlight
          onPress={() => this.loginWithFacebook()}
          style={{ backgroundColor: "green" }}
        >
          <Text style={{ color: "white", padding: 10 }}>
            Login with Facebook
          </Text>
        </TouchableHighlight>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

вывод консоли

Logged Out
[23:32:44] success 
[23:32:44]  EAALzsYw3MzQBAOLG5h46PqNsnuZCjokCdE4O5CVA8pQcrDI1ZCWKYySaYqHrSs1LcaTLlZBQXWZBjDl1RnoPzyFnsVxi1ZBIcPryIHeJlCzQrDgLWnOc3LGHmKzujphQDMI2X10bHFkPPNEN0bHEZCJEDXTrzD1GPKeJXWAzZAycOZA5eFt2ZAUq2b4RUDagIwkiNWChltv7eA5ZAF4y8TXIth

[23:32:48] [Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_config.f.auth().FacebookAuthProvider.credential')]
* App.js:31:56 in loginWithFacebook$
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:62:44 in tryCatch
- node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:288:30 in invoke
- ... 13 more stack frames from framework internals

[23:33:15] Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called when the app is in the foreground. See https://github.com/facebook/react-native/issues/12981 for more info.
(Saw setTimeout with duration 287771ms)
- node_modules/expo/build/environment/logging.js:25:23 in warn
- ... 10 more stack frames from framework internals

[23:38:48] Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called when the app is in the foreground. See https://github.com/facebook/react-native/issues/12981 for more info.
(Saw setTimeout with duration 238715ms)
- node_modules/expo/build/environment/logging.js:25:23 in warn
- ... 10 more stack frames from framework internals

[23:42:47] Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called when the app is in the foreground. See https://github.com/facebook/react-native/issues/12981 for more info.
(Saw setTimeout with duration 541868ms)
- node_modules/expo/build/environment/logging.js:25:23 in warn
- ... 10 more stack frames from framework internals

my Проект Github .

Edit-1:

из-за проблем безопасности api-ключей, я делаю Github-repo закрытым, потому что по ошибке я нажал свои api-ключии это уязвимо.

1 Ответ

0 голосов
/ 12 марта 2019

удалить скобки () после firebase.auth()

до

const credentials = f.auth().FacebookAuthProvider.credential(token);

после

const credentials = f.auth.FacebookAuthProvider.credential(token);

github-changes

не нужно () из-за экспорта по умолчанию в config.js

export const f = firebase;
export const database = firebase.database();
export const auth = firebase.auth();
export const storage = firebase.storage();

Итак, мы можем использовать auth(), используя только auth.

...