BitWrecker
BitWrecker

Reputation: 184

How to read a value from Firebase document and compare with variable, then change document's value

I am trying have a user confirm their account using a verification code. I want to get the user document from the firestore db, check to ensure the authentication code matches the value provided, and then changed the hasVerfied field of the document to True.

This is for a mobile application (on device, not server-side) so I can not use firebase-admin... I have a screen appearing but once I fill out the authentication field click the button no action occurs, but I can confirm that the function is definitely being reached, just not executing the code within because of some error.

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

  }

on submission of form (onPress of button in app) handleConfirmation is executed and the auth_code is compared to user_auth_code (which is the value of the authCode field from the firebase firestore document), if these values match, the hasVerified field of user is changed to True and saved in firebase.

Please help! FYI this is my first ever post on StackOverFlow so let me know if I followed the proper guidelines.

//EDIT: showing how I initialize users upon creation.

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

Upvotes: 1

Views: 946

Answers (1)

Ron Astle Lobo
Ron Astle Lobo

Reputation: 1314

Checkout the below code,

You have to store the doc-ID of the document inside the document to updateUser in later stages. I have given an example of how to do it as well in the last.

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

As per my understanding you are looking for a way to, 1) find a user who exists. 2) If exists grab their hasVerified and authCode information. 3) Compare and Update the their Document inside the Collection.

I hope I could help you

Upvotes: 0

Related Questions