简体   繁体   中英

Decrypt data within a node/express.js Route

I have an app where I am trying to encrypt the userID before sending it to the client side. The reason for doing this is because I am using EJS as a tempting engine which means I have code where I am using the userID like so:

<body ng-init="getAllPosts('<%= user._id' %>)"></body>

The issue with this is that when someone does "inspect element" on any browser they can clearly see their userID . See image below for example:

在此处输入图片说明

To fix this issue I started Encrypting my userID before I sent to the client, like s0:

app.get('/profile',isLoggedIn,function(req, res) {

     var user = req.user;
     var uid = encrypt(JSON.stringify(user._id));

     res.render('profile.ejs', {
        userID: uid
    }); 
});

This Encrypts the ID successfully as you can see in the image below:

在此处输入图片说明

The Issue:

The issue is that I can successfully Decrypt the ID but even after decrypted it I can't get the data from the database. I have tried copy pasting the decrypted ID into my route and that gets the data successfully. Its like it does not read the decrypted ID from the variable but works when copy paste it myself.

Heres the code:

app.get('/user/posts/:id', isLoggedIn, function(req, res){

        var x = decrypt(req.params.id)

        Posts.findOne({userID:x}, function(err, post){
            if(err)
                console.log(err);
            else if(post){
                res.json(post);
            } else if(!post){
                res.json({message: "No Posts document exists for this user"});
            }    
        });
      });

Thing to note is that the variable x contains decrypted ID is text form!

Just for more info here are my Encrypting & Decrypting functions:

//Encrypt Data
 function encrypt(text){

  var cipher =  crypto.createCipher(algorithm,key)
  var crypted = cipher.update(text, 'utf8', 'base64')
  crypted += cipher.final('base64');

  console.log("CRYPTED " + crypted);
  return crypted;
 }

//Decrypt Data
function decrypt(text){

 var decipher = crypto.createDecipher(algorithm,key)
 var dec = decipher.update(text, 'base64', 'utf8')
 dec += decipher.final('utf8');

 console.log("DECRYPTED " + dec);
 return dec;
}

Output of Decrypt Function:

在此处输入图片说明

Found the problem, the problem was that I was being an idiot.

All I had to do to make is work was to change the following line from this:

Posts.findOne({userID:x})

to

Posts.findOne({userID: JSON.parse(x)})

The above solved the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM