node.jsauthenticationjwtfeathersjs

How to decode and verify password in feathers js


I am new to feathersJs and trying to learn how to perform authentication using hooks and services. I am using Couchdb database and cradle. This is the post method to encrypt password in hashPassword using "users" hooks service. The post method is as below:

app.post('/dev',function(req,res,next){
   var  username = req.body.username;
   var password = req.body.password;
   app.service('database').create({username,password}).then(user => {
     db.save(user, function (err, docs) {
      // Handle response
      res.json(docs);
         });
      console.log('User Created Successfully.', user);
    }).catch(console.error);
  })

and service is:

app.service('authentication').hooks({
  before: {
    create: [
      // You can chain multiple strategies
      auth.hooks.authenticate(['jwt', 'local'])
    ],
    remove: [
      auth.hooks.authenticate('jwt')
    ]
  }
});

app.service('database').hooks({
  before: {
    find: [
      auth.hooks.authenticate('jwt')
    ],
    create: [
      local.hooks.hashPassword({ passwordField: 'password' })
    ]
  }
});

now i am using this to retrive data :

app.post('/devget',function(req,res,next){

        var User = {
              username: req.body.username,
              password: req.body.password
            };
            app.service('dataget').find(User).then(user => {
            db.view('byuser/user',{key: User.username}, function (err, docs) {
                  // Handle response
                  res.json(docs);
              });
              console.log('User Get Successfully.', user);
            }).catch(console.error);
    })

this will give me data in response as:

Response [
  { id: '060ab48a4826da7125d8ae45350037ee',
    key: 'w',
    value: 
     { _id: '060ab48a4826da7125d8ae45350037ee',
       _rev: '1-ea9a18d3724ce4542019dc5752c1fd4d',
       username: 'w',
       password: '$2a$10$yBJVJTmVXfTk0V4CCiWkd.GvAZZB9dF2pckKJ9wb/lJcAK8Ou.v06',
       id: 0 } } ]

this works fine and password is encrypted but i am not getting how to decrypt password and authenticate user.

Note: i just want o do it with hooks and services or custom service or class but not using passport.


Solution

  • You do not decrypt the password; you compare the encrypted password to a function that will encrypt the password (after you've found the user to make a password comparison to).

    const bcrypt = require('bcryptjs');
    
    
    var hash = bcrypt.hashSync("bacon");
    
    bcrypt.compareSync("bacon", hash); // true
    bcrypt.compareSync("veggies", hash); // false