How to use bcrypt.compare in sails js schema?

214 Views Asked by At

I have a user model like this:

module.exports = {
  attributes: {
    email: {
      type: 'string',
      isEmail: true,
      unique: true,
      required: true
    },
    password: {
      type: 'string',
      required: true
    }
  },
  beforeCreate: (value, next) => {
    bcrypt.hash(value.password, 10, (err, hash) => {
      if (err){
        throw new Error(err);
      }
      value.password = hash;
      next();
    });
  },
};

Now when I want to match the password during login, how do I decrypt the password, if possible I would prefer to perform it in the user model file.

controller/ login.js

module.exports = {
  login: async (req, res) => {
    try{
      const user = await User.findOne({email: req.body.email});
      if (!user){
        throw new Error('Failed to find User');
      }

      // here I want to match the password by calling some compare 
      //function from userModel.js

      res.status(201).json({user: user});
    }catch(e){
      res.status(401).json({message: e.message});
    }
  },
};
1

There are 1 best solutions below

2
Amir Pasha Bagheri On

first try to find the user with the given username by user

const find = Users.find(user=>user.username===req.body.username)

if(!find){
    res.send('User Not Found')
}
else{
    if( await bcrypt.compare(req.body.password,find.password)){
        //now your user has been found 
    }
    else{
        //Password is Wrong
    }
}

You must use bcrypt.compare(a,b)

a = given password by user

b = original password if username exist

hope it solve your problem