16

How Can I Check user exists in Firebase auth in Signup Button via react native?

This is my Login Page Code:

export default class Login extends Component {
    constructor(props) {
        super(props)
        this.state = {
            email: '',
            password: '',
            response: ''
        }
        this.signUp = this.signUp.bind(this)
        this.login = this.login.bind(this)
    }

    async signUp() {
        try {
            await firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
            this.setState({
                response: 'Account Created!'
            })
            setTimeout(() => {
                this.props.navigator.push({
                    id: 'App'
                })
            }, 500)
        } catch (error) {
            this.setState({
                response: error.toString()
            })
        }
    }
    async login() {
        try {
            await firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password)
            this.setState({
                response: 'user login in'
            })

            setTimeout(() => {
                this.props.navigator.push({
                    id: 'App'
                })
            })

        } catch (error) {
            this.setState({
                response: error.toString()
            })
        }
    }

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.containerInputes}>
                    <TextInput
                        placeholderTextColor="gray"
                        placeholder="Email"
                        style={styles.inputText}
                        onChangeText={(email) => this.setState({ email })}
                    />
                    <TextInput
                        placeholderTextColor="gray"
                        placeholder="Password"
                        style={styles.inputText}
                        password={true}
                        secureTextEntry={true}
                        onChangeText={(password) => this.setState({ password })}
                    />
                </View>
                <TouchableHighlight
                    onPress={this.login}
                    style={[styles.loginButton, styles.button]}
                >
                    <Text
                        style={styles.textButton}
                    >Login</Text>
                </TouchableHighlight>
                <TouchableHighlight
                    onPress={this.signUp}
                    style={[styles.loginButton, styles.button]}
                >
                    <Text
                        style={styles.textButton}
                    >Signup</Text>
                </TouchableHighlight>
            </View>
        )
    }
}
4
  • Do you want to use only one button for signup and login? If so, you could do the signInWithEmailAndPassword and if the error shows that the user does not exist, you can offer to signup. Treat the exception on the catch Commented Jun 18, 2017 at 14:13
  • I have 2 Buttons, a Login Button and a Signup Button, But I want When user want to signup it tell to user This email is taken or no Commented Jun 18, 2017 at 14:19
  • 1
    Just call createUserWithEmailAndPassword and look for the auth/email-already-in-use error code - see the docs. Commented Jun 19, 2017 at 4:39
  • Thanks, I'm new in firebase can you update my code? Commented Jun 19, 2017 at 6:02

5 Answers 5

29

You need to use the fetchSignInMethodsForEmail API. It takes an email and returns a promise that resolves with the list of providers linked to that email if it is already registered: https://firebase.google.com/docs/reference/js/firebase.auth.Auth.html#fetchsigninmethodsforemail

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I'm new in firebase, where should i add that code? Can you tell me an exampe please?
You would first ask the user to provide the email, you call this API, if the array is empty, show the sign up page where you call createUserWithEmailAndPassword. Otherwise if the array returned contains the string 'password', then show the sign in screen and ask the user to provide the password.
What about the Sign in with Apple without providing email? How do you check that type of account? (Sign in With Apple will be mandatory on the iOS platform)
6

Here's how to use the fetchSignInMethodsForEmail API. It returns an array. If the array is empty, it means the user has never signed up/signed in to your app with the sign in methods you have used in your app.

This is an example with Google signin.

firebase
    .auth()
    .signInWithPopup(provider)
    .then((result) => {
        let token = result.credential.accessToken;
        let user = result.user;

        firebase
            .auth()
            .fetchSignInMethodsForEmail(user.email)
            .then((result) => {
                console.log('result', result);
            });
        })
        .catch((error) => {
            // Handle Errors here.
        }

1 Comment

signInWithPopup(provider) will create user so in "then" response always will be "google.com"
4

For me fetchSignInMethodsForEmail() only works with an email that is registered with email/password and not working for emails registered with Apple, LinkedIn or other providers.

For solution to this, I came up with following work around:

auth().signInWithEmailAndPassword(email, 'some-random-password')  // Password should be really long to avoid actually logging in :)
.then((response) => {
    // TODO : Avoid this block
})
.catch((error) => {
    if(error.code === 'auth/wrong-password'){
        // TODO : If here then it means account already exists...
    }

    if(error.code === 'auth/user-not-found'){
        // TODO : If here then you guessed it... you can create a new account.
    }
})

I'm sure there is a proper solution for this and I will update this answer when I find it.

Hope this will help someone 😎

Comments

3

It is very simple. Add a then() and catch() to your firebase method in signUp function.

firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(()=>{
    console.log('Signup successful.');
    this.setState({
            response: 'Account Created!'
        })
   })
.catch((error)=> {
    console.log(error.code);
    console.log(error.message);
  });

Information on different Error Codes:

  • auth/email-already-in-use

    Thrown if there already exists an account with the given email address.

  • auth/invalid-email

    Thrown if the email address is not valid.

  • auth/operation-not-allowed

    Thrown if email/password accounts are not enabled. Enable email/password accounts in the Firebase Console, under the Auth tab.

  • auth/weak-password

    Thrown if the password is not strong enough.

2 Comments

The problem with this solution is that the account will be created if it's not. These won't work in cases wherein you want to give the user an instant feedback on input blur if the email is already in use.
auth/email-already-in-use not triggering if you have a FB account and create a new Sign in with Apple account. The Facebook account will be deleted, or linked (if its email was verified) as per: groups.google.com/forum/#!searchin/firebase-talk/liu/…
0

The old ways do not work anymore as of now. The following piece of code worked for me

if(res._tokenResponse.isNewUser){
 // New User signed up
} else {
 // Existing user signed in
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.