2017-06-18 103 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