#firebase #react-native #firebase-authentication #facebook-authentication
#firebase #react-native #firebase-аутентификация #facebook-аутентификация
Вопрос:
Я пытаюсь пройти аутентификацию с использованием fb-auth в firebase, в проекте react-native.
используя 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
Он возвращает токен, который выводится на терминал.
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
мой проект на Github.
Редактировать-1:
из-за проблем с безопасностью api-ключей я делаю Github-repo закрытым, потому что по ошибке я ввел свои api-ключи, и он уязвим.
Ответ №1:
удалите круглые скобки () после firebase.auth()
перед
const credentials = f.auth().FacebookAuthProvider.credential(token);
после
const credentials = f.auth.FacebookAuthProvider.credential(token);
нет необходимости ()
из-за config.js экспорт по умолчанию
export const f = firebase;
export const database = firebase.database();
export const auth = firebase.auth();
export const storage = firebase.storage();
итак, мы можем использовать auth()
, используя auth
только.