【问题标题】:Firebase Detecting if user existsFirebase检测用户是否存在
【发布时间】:2017-11-20 19:10:29
【问题描述】:

如何通过本机反应检查 Signup 按钮中的 Firebase 身份验证中的用户是否存在?

这是我的登录页面代码:

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

【问题讨论】:

  • 您想只使用一个按钮进行注册和登录吗?如果是这样,您可以执行 signInWithEmailAndPassword 并且如果错误显示用户不存在,您可以提供注册。处理捕获的异常
  • 我有 2 个按钮,一个登录按钮和一个注册按钮,但我想当用户想要注册时告诉用户这封电子邮件是否被占用
  • 只需调用 createUserWithEmailAndPassword 并查找 auth/email-already-in-use 错误代码 - 请参阅 docs
  • 谢谢,我是 firebase 新手,你能更新我的代码吗?

标签: javascript firebase react-native firebase-authentication


【解决方案1】:

到目前为止,旧方法不再适用。以下代码对我有用

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

【讨论】:

    【解决方案2】:

    对我而言,fetchSignInMethodsForEmail() 仅适用于使用电子邮件/密码注册的电子邮件,不适用于通过 Apple、LinkedIn 或其他提供商注册的电子邮件。

    为了解决这个问题,我想出了以下解决方法:

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

    我确信有一个合适的解决方案,当我找到它时我会更新这个答案。

    希望这会对某人有所帮助?

    【讨论】:

      【解决方案3】:

      以下是使用fetchSignInMethodsForEmail API 的方法。它返回一个数组。如果数组为空,则表示用户从未使用您在应用中使用的登录方法注册/登录到您的应用。

      这是一个使用 Google 登录的示例。

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

      【讨论】:

      • signInWithPopup(provider) 将创建用户,因此“then”响应始终为“google.com”
      【解决方案4】:

      您需要使用 fetchSignInMethodsForEmail API。它接受一封电子邮件并返回一个承诺,如果该电子邮件已注册,则该承诺将通过链接到该电子邮件的提供商列表进行解析: https://firebase.google.com/docs/reference/js/firebase.auth.Auth.html#fetchsigninmethodsforemail

      【讨论】:

      • 谢谢。我是firebase的新手,我应该在哪里添加该代码?请给我一个例子好吗?
      • 您将首先要求用户提供电子邮件,您调用此 API,如果数组为空,则显示您调用 createUserWithEmailAndPassword 的注册页面。否则,如果返回的数组包含字符串“密码”,则显示登录屏幕并要求用户提供密码。
      • 在不提供电子邮件的情况下使用 Apple 登录会怎样?您如何检查该类型的帐户? (在 iOS 平台上必须使用 Apple 登录)
      【解决方案5】:

      这很简单。 在 signUp 函数中将 then() 和 catch() 添加到您的 firebase 方法。

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

      有关不同错误代码的信息:

      • 身份验证/电子邮件已在使用中

        如果已存在具有给定电子邮件地址的帐户,则抛出此错误。

      • 身份验证/无效电子邮件

        如果电子邮件地址无效则抛出。

      • 授权/不允许操作

        如果未启用电子邮件/密码帐户,则引发。在 Firebase 控制台的“身份验证”选项卡下启用电子邮件/密码帐户。

      • 身份验证/弱密码

        如果密码不够强则抛出。

      【讨论】:

      • 这个解决方案的问题是,如果没有,就会创建帐户。如果电子邮件已在使用中,则如果您想向用户提供有关输入模糊的即时反馈,这些将不起作用。
      • auth/email-already-in-use 如果您有 FB 帐户并使用 Apple 帐户创建新登录,则不会触发。 Facebook 帐户将被删除或链接(如果其电子邮件已通过验证):groups.google.com/forum/#!searchin/firebase-talk/liu/…
      猜你喜欢
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 2016-11-06
      • 2016-10-18
      • 2018-11-27
      相关资源
      最近更新 更多