【问题标题】:How to use email and phone to authentication in Firebase?如何在 Firebase 中使用电子邮件和电话进行身份验证?
【发布时间】:2020-03-24 01:33:00
【问题描述】:

我正在寻找一种 react-native 方法,让用户使用他的电话号码注册,然后添加他的电子邮件和密码。 但是当用户登录时,他只使用电子邮件和密码登录。

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

我在用户验证他的号码后执行 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');
    }
  };

【问题讨论】:

  • 嘿伙计@Dupocas 为什么要删除 firebase-auth 标签?我的问题与他们有关
  • 只删除了 react-native 因为它与它没有直接关系。感谢警告

标签: javascript reactjs firebase react-native firebase-authentication


【解决方案1】:

如果您想为同一用户使用多个身份验证提供程序,则需要链接它们以防止创建单独的用户。要链接它们,您可以使用 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

【讨论】:

  • 太好了,但我会说这个场景以确保这是否有帮助,我在初始屏幕中有 3 个屏幕(“启动画面,注册,主页”),如果我在 AuthStateChanged 上创建一个监听器登录后我将下摆导航到其他主页进行注册,现在在注册时我使用 createUserWithEmailAndPassword() 和 then() 语句我使用验证电话号码但 onAuthStateChange() 不允许我这样做,因为它直接导航我到主页所以你怎么看?
  • 在注册时添加电话号码和电子邮件并链接它们。然后,如果用户已经登录,他们将直接进入主屏幕。因此,当您注册时,请同时使用电话和电子邮件
  • "但是 onAuthStateChange() 不允许我这样做,因为它直接将我导航到主页,所以你怎么看?"是的,因为用户已经登录......当你第一次注册时添加电话和电子邮件并链接它们,那么应该没有问题
  • 您可以编辑您的答案以实现电话和电子邮件吗?
猜你喜欢
  • 2018-09-03
  • 1970-01-01
  • 2019-06-11
  • 2021-08-07
  • 2017-10-18
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多