Friday, 25 November 2022

How to Update User With JWT Token When he Tries To Login in Nodejs and Reactjs with MongoDB

I am trying to create a login functionality for my Reactjs Webiste using Nodejs express backend.

I want to set a JWT token when the user tries to log in and update that token in my mongoDB database and then verify the token on the frontend and save it to localStorage.

However, when the user tries to log in after registration, it returns back the result without the token, and thus not allowing the user to log in, unless he clicks the login button again, then my code would generate and update the user with the JWT token.

Why is this behavior happening? Why is the first response only returning the found user from the findOne() operation when i am resolving the result from the findOneAndUpdate operation?

Here is my code:

User Model:

login(params) {
  

    params.email = params.email.toLowerCase();

    return new Promise((resolve, reject) => {
      db.collection("Users").findOne({ email: params.email }).then((response) => {

          console.log(response)
          if(response) {
            bcrypt.compare(params.password, response.password, (err, success) => {
              if(success) {
                let token = jwt.sign({
                  name: response.name,
                  id: response._id
                }, proccess.env.JWT_SECRET);

                db.collection("Users").findOneAndUpdate({
                  email: params.email
                }, {
                  $set: { token: token, lastLogin: new Date() },
                }, function (e, s) {
                  if(e) {
                    console.log(e)
                    reject(e)
                  } else {
                    console.log("updated")
                    resolve(s)
                  }
                })
              } else {
                reject({msg: 'Incorrect email or password.'})
              }
            })
          } else {
  
            reject({msg: 'cannot log in user'});
          }

      })
    })
  }

UserController:

router.post('/login', (req, res) => {

    let User = new models.User()
    let processes = [];
    processes.push(function (callback) {
        User.login(req.body).then(function (response) {
           
                callback(null, response);
        }, function (error) {
            console.log(error)
            callback(error);
        });
    });

    async.waterfall(processes, function (error, data) {
        if (!error) {
            return res.json({
                statusCode: 200,
                msg: 'User logged in successfully.',
                result: data
            });
        } else {
            return res.json({
                statusCode: 401,
                msg: 'Cannot login user.',
                error: error
            });
        }
    });

})

React Login.js:

const login = () => {
    axios.post('/login', data).then(async (response) => {
      console.log(response)
      if(response && response.data.result.value.token ) {
        localStorage.setItem("authUser", JSON.stringify(response.data.result.value.token))
        history.push("/")
        console.log(response.data.result)
      } else {
        console.log("ERROR")
      }
    })
  }


from How to Update User With JWT Token When he Tries To Login in Nodejs and Reactjs with MongoDB

Query influxdb with special character

I am trying to perform. simple get on influxdb using python. The connection works great and I am able to query several values. However, I have one of them which is reported as homeassistant.autogen.°C. When I try to query it, I always get

influxdb.exceptions.InfluxDBClientError: 400: {"error":"error parsing query: found \u00b0, expected identifier at line 1, char 43"}

The code that is use is:

client = InfluxDBClient(host='192.168.1.x', port=8086, username='user', password='password')
results = client.query(r'SELECT "value" FROM homeassistant.autogen."°C" WHERE entity_id = sensor.x_temperature')

I already tried to escape and pass it through quotes but nothing seems to work.

I cannot change how the value is inserted in influxdb.



from Query influxdb with special character

Thursday, 24 November 2022

How can I handle the code purchase.sku when I upgrade Google Play Billing Library 3 to 4?

I use Google Play in-app in my app based the official sample project.

The Code A is to handle non-consumable products, it works well when I launch it using com.android.billingclient:billing-ktx:3.0.3 .

After I upgrade the project from Google Play Billing Library 3 to 4, I find the code purchase.sku doesn't work, so I have to replace it with purchase.skus.

The code of purchase.skus can be compiled in com.android.billingclient:billing-ktx:4.0.0, but I can't get the correct order, the test purchase is refunded after 3 minutes, it seems that Google Play doesn't acknowledge the purchase.

How can I fix the Code A when I upgrade Google Play Billing Library 3 to 4 ?

Code A

private fun processPurchases(purchasesResult: Set<Purchase>) {
        val validPurchases = HashSet<Purchase>(purchasesResult.size)
        purchasesResult.forEach { purchase ->
            if (purchase.purchaseState == Purchase.PurchaseState.PURCHASED) {
                if (purchase.sku.equals(purchaseItem)) {
                //if (purchase.skus.equals(purchaseItem)) {     //sku -> skus  in 4.0
                    if (isSignatureValid(purchase)) {
                        validPurchases.add(purchase)
                    }
                }
            } else if (purchase.purchaseState == Purchase.PurchaseState.PENDING) {
                Log.d(LOG_TAG, "Received a pending purchase of SKU: ${purchase.sku}")
                // handle pending purchases, e.g. confirm with users about the pending
                // purchases, prompt them to complete it, etc.
                mContext.toast(R.string.msgOrderPending)

            } else {
                mContext.toast(R.string.msgOrderError)
            }
        }

        acknowledgeNonConsumablePurchasesAsync(validPurchases.toList())
    }


from How can I handle the code purchase.sku when I upgrade Google Play Billing Library 3 to 4?