2017-06-18 106 views
3

如何检查用户是否存在于Firebase身份验证中Signup Button via react native?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> 
     ) 
    } 
} 
+0

您是否只想使用一个按钮进行注册和登录?如果是这样,你可以做signInWithEmailAndPassword,如果错误显示用户不存在,你可以提供注册。处理异常的捕获 – cristianorbs

+0

我有2个按钮,一个登录按钮和一个注册按钮,但我想当用户想要注册告诉用户这封电子邮件被采取或不 –

+1

只需调用'createUserWithEmailAndPassword'并寻找'auth/email-already-in-use'错误代码 - 请参阅[文档](https://firebase.google.com/docs/reference/js/firebase.auth.Auth#createUserWithEmailAndPassword)。 – cartant

回答

7

您需要使用fetchProvidersForEmail API。它需要一封电子邮件并返回一个承诺,如果该电子邮件已被注册,则与该电子邮件链接的提供商列表一起解决: https://firebase.google.com/docs/reference/js/firebase.auth.Auth#fetchProvidersForEmail

+0

谢谢。我是firebase的新成员,我应该在哪里添加该代码?你能告诉我一个检查吗? –

+1

您首先会要求用户提供电子邮件,您可以调用此API,如果该数组为空,则显示您在其中调用createUserWithEmailAndPassword的注册页面。否则,如果返回的数组包含字符串“password”,则显示登录屏幕并要求用户提供密码。 – bojeil