Saeed Heidarizarei
Saeed Heidarizarei

Reputation: 8916

Firebase Detecting if user exists

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>
        )
    }
}

Upvotes: 16

Views: 25428

Answers (5)

Tanishq Vyas
Tanishq Vyas

Reputation: 1689

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
}

Upvotes: 0

Ali Goher Shabir
Ali Goher Shabir

Reputation: 395

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 😎

Upvotes: 4

Adebola
Adebola

Reputation: 609

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.
        }

Upvotes: 6

bojeil
bojeil

Reputation: 30798

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

Upvotes: 29

AmanDeepSharma
AmanDeepSharma

Reputation: 2208

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.

Upvotes: 3

Related Questions