Reputation: 1081
I am using react native as frontEnd and Firebase as backEnd for my application. I have created an API 192.168.0.104:8080/api/user/loginUsingEmail
which contains the following code :
firebase.auth().signInWithEmailAndPassword(email,password)
.then(data => {
return data.user.getIdToken();
})
.then(token => {
return res.json({message: `Successfully logged in`,token: token});
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
return res.status(500).json({
error: errorCode, message : errorMessage
});
});
This is working perfectly fine using Postman.
Now the issue comes when I try to invoke the API using Axios to my react native project. The code is as follows :
JSX
:
<TouchableOpacity style={styles.button} onPress={this.handleLogin}>
<Text style={{ color: "#FFF", fontWeight: "500"}}>Sign In</Text>
</TouchableOpacity>
Handler
:
const {email, password} = this.state;
Axios.post('http://192.168.0.104:8080/api/user/loginUsingEmail', {
"email": email,
"password": password
})
.then(response => {
console.log(response.data);
})
.catch(error => {
this.setState({ errorMessage: error.response.data.message })
})
Here also all the errors and token comes perfectly fine. But in my LoadingScreen I have written as :
export default class LoadingScreen extends React.Component {
componentDidMount() {
firebase.auth().onAuthStateChanged(user => {
this.props.navigation.navigate(user ? "App" : "Auth");
})
}
render() {
return (
<View style={styles.container}>
<Text>Loading ...</Text>
<ActivityIndicator size="large"></ActivityIndicator>
</View>
)
}
}
Now firebase.auth().onAuthStateChanged
does not get the proper user
when we do an axios call. But if I change the handler to call firebase.auth().signInWithEmailAndPassword()
directly, it works perfectly fine.
What I am doing wrong over here ? Any help would be appreciated.
Upvotes: 0
Views: 936
Reputation: 600131
When you call Axios.post('http://192.168.0.104:8080/api/user/loginUsingEmail',
, the user is signed in to the service on 192.168.0.104:8080
. They are not signed in to the local Firebase instance that makes the call. Even if 192.168.0.104:8080
is you local machine, these two pieces of code run as two separate apps.
To sign in the user on the client, you will need to call one of the firebase.auth().signIn...
methods in the client - and not just on the server. I'm not sure what the purpose of your api/
handler is, but usually you should just have the call to sign in, inside your regular client-side code, as you did in:
But if I change the handler to call
firebase.auth().signInWithEmailAndPassword()
directly, it works perfectly fine.
If you want to implement a custom sign in on your server, have a look at creating custom tokens in the Firebase documentation, which describes the basic flow for that:
signInWithCustomToken
.Upvotes: 2