Firebase failure in React Native - reactjs

what's wrong with this picture ?
import firebase from 'firebase';
onButtonPress() {
const { email, password } = this.state;
firebase.auth().signInWithEmailAndPassword(email, password)
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch(() => {
this.setState({ error: 'Authentication Failed' });
});
});
}
And so that we're clear:
Yes it's installed in the framework when I built the app. And yes I'm calling it on the same page where this is being executed. And yes the app runs fine without this section of code. there are no coding errors, nor logic errors.
If I wanted to a.) debug this bit of code how would I do that ? and b.) where would I add the console.log statement ? I know it has to live somewhere....like here >
firebase.auth().signInWithEmailAndPassword(console.log(email, password)) ??
Shouldn't a call like these to firebase work like this ?
Thanks ahead of time.
Miles.

Oy! When I called the function to press the button I had set up. I had written onButtonPress instead of onPress....grrrrrrrrr! Sorry to bother everyone. All is well now.

You need to add firebase to your application, there are specific steps mentioned on their site. The site has information no how to call firebase for email authentication.

Related

React-Native unable to store state getting null

I'm new to React-native so if there is a misunderstanding please be super clear and treat me as if I have never seen React-native before.
I have the app so that when you press on a button it will send you into an Auth0 flow where you can log in to the app. This seems working. If I log out the access token directly in the callback I am successful in getting it at the credentials.accessToken variable/location. However, when I am trying to set the state of the accessToken variable I get back null when I try to log it out to the screen via an alert or even via console.log. What am I doing wrong to cause this? I tried searching SO and google but both seem to show this as the right way of doing it.
Code:
const [accessToken, setAccessToken] = useState(null)
const onLogin = () => {
auth0.webAuth
.authorize({
scope: 'openid profile email'
})
.then(credentials => {
setAccessToken(credentials.accessToken)
Alert.alert('Access token: ', accessToken)
})
.catch(error => console.log(error)) // Eventually send this to backend for crash reporting
}
This is probably a case of a state not updating immediately. Try to use a useRef() instead of a useState(https://www.w3schools.com/react/react_useref.asp). If the problem is solved the issue was with the fact that states are updated asynchronously and hence it was not set to its most recent value (the value you expected) when you console logged it.

setPersistence function is not working properly (Firebase + React)

I want to make a functionality where I persist the user while the window is open or to be precise in the current session. To make this I've researched the Firebase documentation, and I found out about this: Authentication State Persistence.
After researching it, I decided to put it inside my app, here's how my code looks like:
function logIn(email, password) {
setPersistence(auth, browserLocalPersistence)
.then(() => {
return signInWithEmailAndPassword(auth, email, password);
})
.catch((error) => {
console.log(error);
});
}
This function is inside my UserAuthContext file where I keep all functionalities regarding user. Now some may say that there is nothing wrong with the way this function is made, but whenever email and password are empty the user can still Login without being stopped by Firebase errors like it happens without setPersistence function.
Does anyone know why does my Login go through even though email and password are empty?

How can I provide my react-native app with google sign in?

I`ve tried to register my app as Web application, generate the user id and implement it in my code but get an error when I press my button for log in with google:
[Unhandled promise rejection: Error: Please provide the appropriate client ID.
enter image description here
If you're using expo, you have to configure the google sign-in like this. This is my configuration. You have to create androidClientId and iosClientId from your account and use it here.
Disclaimer: This is a standalone function only for signingin/signingup a Google user and fetching details. To configure it with firebase you have to add other functions too.
Also, make sure that you're importing this package. I faced a similar problem when I used another package.
import * as Google from 'expo-google-app-auth'
Additionally, are you using the latest version of expo SDK?
async signInWithGoogleAsync() {
try {
const result = await Google.logInAsync({
androidClientId:
'your-id',
iosClientId:
'your-id',
scopes: ['profile', 'email'],
permissions: ['public_profile', 'email', 'gender', 'location']
})
if (result.type === 'success') {
/*put your logic here, I set some states and navigate to home screen
after successful signin.*/
const googleUser = result.user
this.setState({
email: googleUser.email,
name: googleUser.name,
})
this.navigateToLoadingScreen()
return result.accessToken
} else {
return { cancelled: true }
}
} catch (e) {
return { error: true }
}
}

This email already exists validation

I am making a React application where i submit the username, password and email to the mongo database.
Now I am trying to figure out how I could check inside of React whether the user or email already exists. Meaning so I could show an error-box telling the user to choose something else as an username.
I do know how to do it when I use Node.js and Handlebars. I know how to check my database with the Find() method of mongoose.
But I just don't understand how to think now that I am using React.
When I check if the user already exists in the back-end and it shows that it does exist, how could I inform my front-end (React) that it does?
When I use node.js and handlebars I use flash messages, and it works fine.
I guess my question could be summarized to, how should I do to get my React front-end to cooperate with my Node/Express back-end to share info about a username inside of the database already existing?
I have no code to show, this is more of asking for advice on what tools or methods I should use. I just can't figure it out.
Thank you in advance!
You'll need to have your back-end inform your front-end about whether or not an email has already been used since the front-end has no way of knowing without the back-end.
Basically, when a user tries to register, you should send your registration request from the front-end to the back-end without worrying about duplicate emails. The response from the server should indicate whether or not registration was successful, and if not, why not.
For example the registration component in your React code might look something like this:
class RegistrationComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
error: "",
}
}
handleSubmit = async event => {
event.preventDefault();
const { email, password } = this.state;
const response = await sendRegisterRequest(email, password);
const responseJson = await response.json();
if (response.status !== 200) {
this.setState({error: reponseJson.error});
} else {
// handle successful registration
}
}
render() {
const { error } = this.state;
return (
<form onSubmit={ this.handleSubmit }>
<span>{ error }</span>
{ /* rest of the form */ }
</form>
)
}
}
Where sendRegisterRequest is some module that handles sending registration requests to the server.
Note that this front-end logic expects the server to respond with status 200 on successful registration and with something else (status 400) if there is an error. Also if there is an error, the server should respond with a payload body that looks like: {"error": "That email is already in use"}.
You mention that you know how to check for existing email addresses on the server, so just check in that manner before creating a new account, and if the email address is already in use send the error payload with a status of 400.
You can respond with a 400 status if it occurs then send the error message to the frontend that way. e.g. return res.status(400).json(errors).
catch((err) => {
console.log(err);
if(err.status=404){
alert("email already used");
}

Ionic Firebase Login with Facebook taking too much time on Android device

I am trying to implement a login with Facebook in my Ionic app. I built an apk and run it on my Android phone, and when I press the login button it takes about one minute to login and sometimes does not even work. Here is the function:
facebookLogin(){
if(this.platform.is('cordova')){
Facebook.login(['email', 'public_profile']).then((res) => {
const facebookCred = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
firebase.auth().signInWithCredential(facebookCred).then((res) => {
let currentUser = firebase.auth().currentUser;
window.localStorage.setItem('currentUser', JSON.stringify(currentUser));
this.navCtrl.pop();
},(err) => {
alert('Login not successful: ' + err);
});
});
}}
I hope someone can tell me why that is happening and suggest a fix for it. Thank you for your time!

Resources