如何在Firebase中使用电子邮件和电话进行身份验证? [英] How to use email and phone to authentication in Firebase?

查看:71
本文介绍了如何在Firebase中使用电子邮件和电话进行身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种本机响应的方法,以使用户使用他的电话号码进行注册,然后添加他的电子邮件和密码. 但是,当用户登录时,他只能使用电子邮件和密码登录.

电话号码仅出于安全原因.

我在用户验证其号码后执行signInWithPhoneNumber(),我调用了createUserWithEmailAndPassword(),但这是在控制台Auth中进行的两次同时进行的独立身份验证 电子邮件"和电话号码"

代码

// I just pass the result into separate screen then use it to confirm all stuff is work :D

...
auth()
        .signInWithPhoneNumber(phoneWithAreaCode, true)
        .then(confirmResult => {
          console.log('2', phoneWithAreaCode);
          console.log('confirmResult', confirmResult);
          this.setState({
            confirmResult,
            loading: false,
          });
        })
...

confirmCode = codeInput => {
    const {confirmResult, email, password} = this.state;
    console.log('codeInput Is:', codeInput.length);
    if (confirmResult && codeInput.length) {
      confirmResult
        .confirm(codeInput)
        .then(async () => {
          clearInterval(this.interval);
          const {params} = this.props.navigation.state;
          await auth()
            .createUserWithEmailAndPassword(email, password)
            .then(({user}) => {
              console.log('hey u');
              let uid = user.uid;
              params.createUser(uid);
            })
            .catch(error => {
              // Handle Errors here.
              var errorCode = error.code;
              switch (errorCode) {
                case 'auth/email-already-in-use':
                  this.setState({loading: false, password: ''});
                  break;
                case 'auth/invalid-email':
                  this.setState({loading: false, password: ''});
                  break;
                case 'auth/operation-not-allowed':
                  this.setState({loading: false, password: ''});
                  break;
                case 'auth/weak-password':
                  this.setState({loading: false, password: ''});
                  break;
                default:
                  this.setState({loading: false, password: ''});
                  break;
              }
            });
          //Check if any users exist
          // database()
          //   .ref(`users`)
          //   .limitToFirst(1)
          //   .once('value', async snapshot => {
          //     if (snapshot.exists()) {
          //       console.log('exists!');
          //       return true;
          //     } else {
          //       // params.createUser(user.uid);
          //       console.log('No user found Hah');
          //     }
          //   });
          this.setState({
            timer: 0,
            isValid: true,
          });
        })
        .catch(error => {
          let errorCode = error.code;
          let errorMessage = error.message;
          console.log(errorCode);
          switch (errorCode) {
            case 'auth/invalid-verification-code':
              this.setState({codeInput: ''});
              this.refs.codeInputRef2.clear();
              break;
            default:
              break;
          }
          console.log(errorMessage);
        });
    } else {
      console.log('Not here');
    }
  };

编辑

 confirmCode = codeInput => {
    const {confirmResult, password, email} = this.state;
    console.log('codeInput Is:', codeInput.length);
    if (confirmResult && codeInput.length) {
      confirmResult
        .confirm(codeInput)
        .then(user => {
          console.log(user);
          let userE = auth().currentUser;
          // userE.updateEmail(email); 

          auth().createUserWithEmailAndPassword(email, password);

          clearInterval(this.interval);
          const {params} = this.props.navigation.state;
          params.createUser(user.uid);
          this.setState({
            timer: 0,
            isValid: true,
          });
        })
        .catch(error => {
          let errorCode = error.code;
          let errorMessage = error.message;
          switch (errorCode) {
            case 'auth/invalid-verification-code':
              this.refs.codeInputRef2.clear();
              break;
            default:
              break;
          }
          console.log(errorMessage);
        });
    } else {
      console.log('Not here');
    }
  };

解决方案

如果要为同一用户使用多个身份验证提供程序,则需要链接它们以防止创建单独的用户.要链接它们,您可以使用linkWithCredential()例如:

var credential = firebase.auth.EmailAuthProvider.credential(email, password);

此处将电子邮件和密码传递给EmailAuthProvider.credential方法,然后可以将AuthCredential对象传递给已登录用户的linkWithCredential方法:

firebase.auth().currentUser.linkWithCredential(credential).then(function(usercred) {
  var user = usercred.user;
  console.log("Account linking success", user);
}, function(error) {
  console.log("Account linking error", error);
});

您可以在文档中查看链接多个提供程序的其他方式:

https://firebase.google.com/docs/auth/web /account-linking

https://firebase.google.com/docs/auth/web/account-linking#link-email-address-and-password-credentials-to-a-user-account

I am looking for a way in react-native to make user sign up with his phone number then add his email and password. But when a user logs in, he logs in only with email and password.

The phone number is only for security reasons.

I do a signInWithPhoneNumber() after user verify his number i call a createUserWithEmailAndPassword() but that's made in console Auth Two separate authentication in the same time "Email" & "Phone Number"

code

// I just pass the result into separate screen then use it to confirm all stuff is work :D

...
auth()
        .signInWithPhoneNumber(phoneWithAreaCode, true)
        .then(confirmResult => {
          console.log('2', phoneWithAreaCode);
          console.log('confirmResult', confirmResult);
          this.setState({
            confirmResult,
            loading: false,
          });
        })
...

confirmCode = codeInput => {
    const {confirmResult, email, password} = this.state;
    console.log('codeInput Is:', codeInput.length);
    if (confirmResult && codeInput.length) {
      confirmResult
        .confirm(codeInput)
        .then(async () => {
          clearInterval(this.interval);
          const {params} = this.props.navigation.state;
          await auth()
            .createUserWithEmailAndPassword(email, password)
            .then(({user}) => {
              console.log('hey u');
              let uid = user.uid;
              params.createUser(uid);
            })
            .catch(error => {
              // Handle Errors here.
              var errorCode = error.code;
              switch (errorCode) {
                case 'auth/email-already-in-use':
                  this.setState({loading: false, password: ''});
                  break;
                case 'auth/invalid-email':
                  this.setState({loading: false, password: ''});
                  break;
                case 'auth/operation-not-allowed':
                  this.setState({loading: false, password: ''});
                  break;
                case 'auth/weak-password':
                  this.setState({loading: false, password: ''});
                  break;
                default:
                  this.setState({loading: false, password: ''});
                  break;
              }
            });
          //Check if any users exist
          // database()
          //   .ref(`users`)
          //   .limitToFirst(1)
          //   .once('value', async snapshot => {
          //     if (snapshot.exists()) {
          //       console.log('exists!');
          //       return true;
          //     } else {
          //       // params.createUser(user.uid);
          //       console.log('No user found Hah');
          //     }
          //   });
          this.setState({
            timer: 0,
            isValid: true,
          });
        })
        .catch(error => {
          let errorCode = error.code;
          let errorMessage = error.message;
          console.log(errorCode);
          switch (errorCode) {
            case 'auth/invalid-verification-code':
              this.setState({codeInput: ''});
              this.refs.codeInputRef2.clear();
              break;
            default:
              break;
          }
          console.log(errorMessage);
        });
    } else {
      console.log('Not here');
    }
  };

EDIT

 confirmCode = codeInput => {
    const {confirmResult, password, email} = this.state;
    console.log('codeInput Is:', codeInput.length);
    if (confirmResult && codeInput.length) {
      confirmResult
        .confirm(codeInput)
        .then(user => {
          console.log(user);
          let userE = auth().currentUser;
          // userE.updateEmail(email); 

          auth().createUserWithEmailAndPassword(email, password);

          clearInterval(this.interval);
          const {params} = this.props.navigation.state;
          params.createUser(user.uid);
          this.setState({
            timer: 0,
            isValid: true,
          });
        })
        .catch(error => {
          let errorCode = error.code;
          let errorMessage = error.message;
          switch (errorCode) {
            case 'auth/invalid-verification-code':
              this.refs.codeInputRef2.clear();
              break;
            default:
              break;
          }
          console.log(errorMessage);
        });
    } else {
      console.log('Not here');
    }
  };

解决方案

If you want to use multiple auth providers for the same user, then you need to link them to prevent creating separate users. To link them you can use linkWithCredential() for example:

var credential = firebase.auth.EmailAuthProvider.credential(email, password);

Here you pass the email and password to the EmailAuthProvider.credential method, then you can pass the AuthCredential object to the signed-in user's linkWithCredential method:

firebase.auth().currentUser.linkWithCredential(credential).then(function(usercred) {
  var user = usercred.user;
  console.log("Account linking success", user);
}, function(error) {
  console.log("Account linking error", error);
});

You can check the docs for other ways to link multiple providers :

https://firebase.google.com/docs/auth/web/account-linking

https://firebase.google.com/docs/auth/web/account-linking#link-email-address-and-password-credentials-to-a-user-account

这篇关于如何在Firebase中使用电子邮件和电话进行身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆