Как прочитать значение из документа Firebase и сравнить с переменной, затем изменить значение документа - PullRequest
1 голос
/ 04 апреля 2019

Я пытаюсь, чтобы пользователь подтвердил свою учетную запись, используя код подтверждения.Я хочу получить пользовательский документ из базы данных firestore, проверить, чтобы код аутентификации соответствовал предоставленному значению, а затем изменил поле hasVerfied документа на True.

Это для мобильного приложения (на устройстве, а не на стороне сервера), поэтому я не могу использовать firebase-admin ... У меня появляется экран, но как только я заполняю поле аутентификации, нажмите кнопку без действияпроисходит, но я могу подтвердить, что функция определенно достигается, но не выполняет код из-за какой-то ошибки.

handleConfirmation = () => {
  const auth_code = this.state.authCode;
  let user = firebase.firestore().collection('users').where('uid', '==', firebase.auth().currentUser.uid);
  // ^ I am not sure if this is correct... could be a source of wrongness.
  if (user.exists === true) {
            console.log(user.data());
            let user_to_verify = user.data();
            const has_verified = user_to_verify.hasVerified;
            if (has_verified === false) {
                const user_auth_code = user.authCode;
                if (auth_code === user_auth_code) {
                    console.log("User verification code is correct");
                    this.setState({hasVerified: true});
                    this.updateUser();
                    // ^ this function should set the 
                   // value of user.hasVerified to True, and 
                  // save it in firestore (aka firebase firestore) 
                 //
                // Now the user can successfully login to app 

                }
  }else{
  // user doesnt exist... throw error and exit

  }

при отправке формы (onPress кнопки в приложении) выполняется handleConfirmation, и код auth_code сравнивается с user_auth_code (который является значением поля authCode из документа пожарной базы firebase), если эти значения совпадают, поле hasVerified пользователя изменяется на True и сохраняется в firebase.

Пожалуйста, помогите!К вашему сведению, это моя первая публикация на StackOverFlow, поэтому дайте мне знать, если я следовал соответствующим инструкциям.

// РЕДАКТИРОВАТЬ: показывает, как я инициализирую пользователей при создании.

constructor() {
        super();
        this.ref = firebase.firestore().collection('users');
        this.state =
            {
                firstname: '<first name>',
                lastname: '<last name>',
                email: '<email>',
                password: '<password>',
                errorMessage: '<none unless error occurs>',
                secureTextEntry: true,
                confirmPassword: '<password>',
                modalVisible: false,
                imageURI: '<some url>',
                authCode: '<authentication code>',
                hasVerified: false,

            };
        this._keyboardDidHide = this._keyboardDidHide.bind(this);
        this.setDate = this.setDate.bind(this);
    }
.
.  // SKIPPED SOME IN-BETWEEN LINES FOR BREVITY
.

updateUser() {
        let user_data = {
            uid: firebase.auth().currentUser.uid,
            firstname: this.state.firstname,
            lastname: this.state.lastname,
            email: this.state.email,
            imageURI: this.state.imageURI,
            authCode: this.state.authCode,
            hasVerified: this.state.hasVerified,
        };
        console.log(user_data);
        this.ref.doc(firebase.auth().currentUser.uid).set(user_data);
        this.props.navigation.navigate('homescreen');
    }

1 Ответ

0 голосов
/ 04 апреля 2019

Извлеките приведенный ниже код,

Необходимо сохранить doc-ID документа внутри документа, чтобы updateUser на последующих этапах.Я привел пример того, как это сделать и в прошлом.

handleConfirmation = () => {
const auth_code = this.state.authCode;
  var user = firebase
    .firestore()
    .collection("users")
    .where("uid", "==", firebase.auth().currentUser.uid)
    .get()
    .then(querySnapshot => {
      if (querySnapshot._docs.length > 0) { // User exists !!
        console.log(querySnapshot._docs);
        // You require the doc_Id of the document so that you can update it in the later stage.
        const has_verified = querySnapshot._docs[0]._data.hasVerified; //_docs is a array, considering there is only 1 unique user
        if (has_verified == false) {
          const user_auth_code = querySnapshot._docs[0]._data.authCode; // or use firebase.auth().currentUser.uid instead.
          if (auth_code === user_auth_code) {
            console.log("User verification code is correct");
            this.setState({ hasVerified: true });
            this.updateUser(querySnapshot._docs[0]._data.doc_Id); // As told above doc_ID is required
          }
        }
      }
    });
};

updateUser = doc_id => {
  var user = firebase
    .firestore()
    .collection("users")
    .doc(doc_id)
    .set({
      hasVerified: true
    });
};

//Example for adding doc_ID in document during document creation. Make sure you do this process during user creation.
//The below code is for your reference.

exampleDocCreate = () => {
  var user = firebase
    .firestore()
    .collection("users")
    .add({
      userName: "React Native User"
    })
    .then(data => {
      var user = firebase
        .firestore()
        .collection("users")
        .doc(data.id)
        .set({
          doc_id: data.id
        });
    });
};

Согласно моему пониманию, вы ищете способ: 1) найти пользователя, который существует.2) Если существует, захватите их hasVerified и authCode информацию.3) Сравните и обновите свой Документ внутри Коллекции.

Я надеюсь, что смогу вам помочь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...