Firebase отклоняет адреса электронной почты некоторых пользователей на определенных устройствах

#javascript #firebase #react-native #firebase-authentication

#javascript #firebase #react-native #firebase-аутентификация

Вопрос:

У меня есть приложение, созданное с помощью React Native, в котором я вчера начал получать активных пользователей. Большинство пользователей могут зарегистрироваться в приложении.

Однако Firebase отклоняет адреса электронной почты двух из них. Оба они используют учетные записи электронной почты gmail, и оба они используют Samsungs.

Я смог создать учетную запись для них обоих, используя свое собственное устройство, без каких-либо проблем. Однако они по-прежнему даже не могут войти в систему при вводе своего адреса электронной почты.

Есть ли у вас какие-либо идеи, почему некоторые законные адреса электронной почты, которые выглядят как something@gmail.com будет ли отклонено, в то время как у большинства пользователей нет проблем?

Ниже приведен код, который я использую на экране регистрации:

 import React, { useState } from 'react';
import { Image, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import styles from './styles';
// import {firebase} from '../../firebase/config';
import firestore from '@react-native-firebase/firestore';
import auth from '@react-native-firebase/auth';

export default function RegistrationScreen({ navigation }) {
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  const onFooterLinkPress = () => {
    navigation.navigate('Login');
  };

  const onRegisterPress = async () => {
    if (password !== confirmPassword) {
      alert("Passwords don't match.");
      return;
    }
    if (email === '') {
      alert("Please enter an email.")
    }
    else if (password === '') {
      alert("Please enter a password.")
    }
    else if (confirmPassword === '') {
      alert("Please enter the same password in both password fields.")
    }
    else if (password.length < 6) {
      alert("Please enter a password with at least 6 characters.")
    }
    else {
      await auth()
        .createUserWithEmailAndPassword(email, password)
        .then(async response => {
          const uid = response.user.uid;
          const data = {
            id: uid,
            email,
            // fullName,
          };
          const usersRef = await firestore().collection('users');
          usersRef
            .doc(uid)
            .set(data)
            .then(() => {
              navigation.navigate('Languages Nav');
              // navigation.navigate('Spanish', {additionalUserInfo: data});
            })
            .catch(error => {
              alert("There was an error. Please ensure you have provided the correct details. If you have, send me an email at (email) and I'll fix it.");

              console.log(error.code);
            });
        })
        .catch(error => {
          switch (error.code) {
            case "auth/email-already-in-use":
              alert("That email has already been registered");
            case "auth/invalid-email":
              alert("Please provide a correct email address.");
            default:
              alert("There was an error. Please ensure you have provided the correct details. If you have, send me an email at (email) and I'll fix it.");
              console.log(error.code);
          }

        });
    }

  };

  return (
    <View style={styles.container}>
      <KeyboardAwareScrollView
        style={{ flex: 1, width: '100%' }}
        keyboardShouldPersistTaps="never">
        {/* <Image
          style={styles.logo}
          source={require('../../../assets/icon.png')}
        /> */}
        {/* <TextInput
          style={styles.input}
          placeholder="Full Name"
          placeholderTextColor="#969696"
          onChangeText={text => setFullName(text)}
          value={fullName}
          underlineColorAndroid="transparent"
          autoCapitalize="none"
        /> */}
        <TextInput
          style={styles.input}
          placeholder="E-mail"
          placeholderTextColor="#808080"
          onChangeText={text => setEmail(text)}
          value={email}
          underlineColorAndroid="transparent"
          autoCapitalize="none"
        />
        <TextInput
          style={styles.input}
          placeholderTextColor="#808080"
          secureTextEntry
          placeholder="Password"
          onChangeText={text => setPassword(text)}
          value={password}
          underlineColorAndroid="transparent"
          autoCapitalize="none"
        />
        <TextInput
          style={styles.input}
          placeholderTextColor="#808080"
          secureTextEntry
          placeholder="Confirm Password"
          onChangeText={text => setConfirmPassword(text)}
          value={confirmPassword}
          underlineColorAndroid="transparent"
          autoCapitalize="none"
        />
        <TouchableOpacity
          style={styles.button}
          onPress={() => onRegisterPress()}>
          <Text style={styles.buttonTitle}>Create account</Text>
        </TouchableOpacity>
        <View style={styles.footerView}>
          <Text style={styles.footerText}>
            Already got an account?{' '}
            <Text onPress={onFooterLinkPress} style={styles.footerLink}>
              Log in
            </Text>
          </Text>
        </View>
      </KeyboardAwareScrollView>
    </View>
  );
}

  

Ниже приведен экран входа в систему:

 import React, { useState } from 'react';
import { Image, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import styles from './styles';
// import {firebase} from '../../firebase/config';
import firestore from '@react-native-firebase/firestore';
import auth from '@react-native-firebase/auth';

export default function LoginScreen({ navigation }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const onFooterLinkPress = () => {
    navigation.navigate('Registration');
  };
  const onPasswordResetPress = () => {
    navigation.navigate('ResetPassword');
  };

  const onLoginPress = () => {
    if (email === '') {
      alert("Please enter an email.")
    }
    if (password === '') {
      alert("Please enter a password.")
    }
    else {
      auth()
        .signInWithEmailAndPassword(email, password)
        .then(response => {
          const uid = response.user.uid;
          const usersRef = firestore().collection('users');
          usersRef
            .doc(uid)
            .get()
            .then(firestoreDocument => {
              if (!firestoreDocument.exists) {
                alert('That email address and password combination did not match any users.');
                return;
              }
              const user = firestoreDocument.data();
              navigation.navigate('Languages Nav', {
                additionalUserInfo: user,
              });
            })
            .catch(error => {
              alert("That email address and password combination did not match any users.")
              console.log(error.code);
            });
        })
        .catch(error => {
          console.log(error.code);
          alert("That email address and password combination did not match any users.")
        });
    }

  };

  return (
    <View style={styles.container}>
      <KeyboardAwareScrollView
        style={{ flex: 1, width: '100%' }}
        keyboardShouldPersistTaps="never">
        {/* <Image
          style={styles.logo}
          source={require('../../../assets/icon.png')}
        /> */}
        <TextInput
          style={styles.input}
          placeholder="E-mail"
          placeholderTextColor="#808080"
          onChangeText={text => setEmail(text)}
          value={email}
          underlineColorAndroid="transparent"
          autoCapitalize="none"
        />
        <TextInput
          style={styles.input}
          placeholderTextColor="#808080"
          secureTextEntry
          placeholder="Password"
          onChangeText={text => setPassword(text)}
          value={password}
          underlineColorAndroid="transparent"
          autoCapitalize="none"
        />
        <TouchableOpacity style={styles.button} onPress={() => onLoginPress()}>
          <Text style={styles.buttonTitle}>Log in</Text>
        </TouchableOpacity>
        <View style={styles.footerView}>
          <Text style={styles.footerText}>
            Don't have an account?{' '}
            <Text onPress={onFooterLinkPress} style={styles.footerLink}>
              Sign up
            </Text>
          </Text>
        </View>
        <View style={styles.footerView}>
          <Text onPress={onPasswordResetPress} style={styles.footerLink}>
            Reset Password
          </Text>
        </View>
      </KeyboardAwareScrollView>
    </View>
  );
}
  

Комментарии:

1. Что здесь означает «получение отклонения»? Какие вызовы метода дают какое точное сообщение об ошибке для какого точного значения?

2. На экране регистрации пользователь видит ошибку «Произошла ошибка. Пожалуйста, убедитесь, что вы предоставили правильные данные. Если у вас есть, отправьте мне электронное письмо по адресу (email), и я это исправлю «. и на экране входа в систему они видят «»Этот адрес электронной почты и комбинация паролей не соответствовали ни одному пользователю «. Однако я не знаю, какой код ошибки вызывает это, поскольку адреса электронной почты работают отлично, когда я их тестирую. Я думаю, что это может быть проблемой с их устройствами.

3. Я думаю, что .createUserWithEmailAndPassword (электронная почта, пароль) и .signInWithEmailAndPassword (электронная почта, пароль) вызывают обе ошибки. У вас есть предложение о том, как я могу выяснить, каковы коды ошибок?

4. Вам нужно будет записать код ошибки / сообщение от Firebase и данные, которые его запускают, где-нибудь, где вы можете посмотреть его и добавить к своему вопросу. Без них будет сложно помочь помимо очевидного: похоже, что адрес электронной почты, который они используют для входа, не зарегистрирован.

5. Я продолжу и сделаю это. Спасибо.