簡體   English   中英

比較密碼 BcryptJS

[英]Compare passwords BcryptJS

所以我正在嘗試建立一個非常基本的用戶登錄。 我正在嘗試創建一個用戶,然后使用這些憑據登錄並取回 JSON Web 令牌。 我卡住的地方是嘗試比較密碼然后發送響應。

腳步:

創建用戶:

  1. 輸入 email 和密碼
  2. 鹽/哈希用戶密碼
  3. 將用戶存入數據庫
  4. 返回成功

登錄

  1. 通過請求 email 值查找用戶
  2. 如果找到比較密碼
  3. 密碼好的發送 JSON Web Token

用戶 Model

email:{ 
  type: String,
  required: true,
  unique: true
},
password: {
  type: String,
  required: true
}

用戶路線

var express     = require('express');
var router      = express.Router();
var jwt         = require('jsonwebtoken');
var bcrypt      = require('bcryptjs');

// Create User
...
bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash("superSecret", salt, function(err, hash) {
      user.password = hash;
      user.save();
      res.json({success: true, message: 'Create user successful'});
    });
  });
...

// Login
...
bcrypt.compare(req.body.password, 'superSecret', function(err, res) {
  if(req.body.password != user.password){
    res.json({success: false, message: 'passwords do not match'});
  } else {
    // Send JWT
  }
});

所以這里的兩個問題是,我無法發送響應,也無法比較密碼。 完全堅持這一點,任何幫助將不勝感激。

文檔中所述,您應該像這樣使用bcrypt.compare

bcrypt.compare(req.body.password, user.password, function(err, res) {
  if (err){
    // handle error
  }
  if (res)
    // Send JWT
  } else {
    // response is OutgoingMessage object that server response http request
    return response.json({success: false, message: 'passwords do not match'});
  }
});

這是一篇關於使用 Mongoose 進行密碼驗證的好文章(第 1 部分):bcrypt

如果您在瀏覽器(HTML)中使用 bcryptjs,那么您可以添加 bcryptjs CDN 來執行此操作。

CDN - https://cdn.jsdelivr.net/npm/bcryptjs@2.4.3/dist/bcrypt.js

示例-

HTML - (在標簽中添加上面的 CDN)

JS-

    var bcrypt = dcodeIO.bcrypt;

    /** One way, can't decrypt but can compare */
    var salt = bcrypt.genSaltSync(10);

    /** Encrypt password */
    bcrypt.hash('anypassword', salt, (err, res) => {
        console.log('hash', res)
        hash = res
        compare(hash)
    });

    /** Compare stored password with new encrypted password */
    function compare(encrypted) {
        bcrypt.compare('aboveusedpassword', encrypted, (err, res) => {
            // res == true or res == false
            console.log('Compared result', res, hash) 
        })
    }

如果你想在 Nodejs 中做同樣的事情

/** 像下面這樣導入 lib 並使用與上面編寫的相同的功能 */

    var bcrypt = require('bcryptjs')
//required files
const express = require('express')
const router = express.Router();

//bcryptjs
const bcrypt = require('bcryptjs')

//User modal of mongoDB
const User = require('../../models/User')


//Post request for login
router.post('/', (req, res) => {
    //email and password
    const email = req.body.email
    const password = req.body.password

    //find user exist or not
    User.findOne({ email })
        .then(user => {
            //if user not exist than return status 400
            if (!user) return res.status(400).json({ msg: "User not exist" })

            //if user exist than compare password
            //password comes from the user
            //user.password comes from the database
            bcrypt.compare(password, user.password, (err, data) => {
                //if error than throw error
                if (err) throw err

                //if both match than you can do anything
                if (data) {
                    return res.status(200).json({ msg: "Login success" })
                } else {
                    return res.status(401).json({ msg: "Invalid credencial" })
                }

            })

        })

})

module.exports = router

從我可以看出你的邏輯是正確的。

如果您使用的是貓鼬,我建議您使用預“保存”鈎子。

用戶模式

userSchema.pre('save', function(next) {
  // only hash the password if it has been modified (or is new)
  if (!this.isModified('password')) {
    return next();
  }
  // generate a salt
  return bcrypt.genSalt(10, function(error, salt) {
    if (error) {
      return next(error);
    }

  // hash the password using the new salt
    return bcrypt.hash(this.password, salt, function(error, hash) {
      if (error) {
        return next(error);
      }
      // override the cleartext password with the hashed one
      this.password = hash;
      return next();
    });
  });
});


userSchema.methods.comparePassword = function(passw, cb) {
  bcrypt.compare(passw, this.password, function(err, isMatch) {
    if (err) {
      return cb(err, false);
    }
    return cb(null, isMatch);
  });
};

在您的路線中:

登錄

...
return user.comparePassword(password, function(error, isMatch) {
  var payload = {
  iat: Math.round(Date.now() / 1000),
  exp: Math.round((Date.now() / 1000) + 30 * 24 * 60),
  iss: 'Whatever the issuer is example: localhost:3000',
  email: user.email
  };

  var token = jwt.encode(payload, 'secret');
  if (isMatch && !error) {
    // if user is found and password is right create a token
    return res.json({
      success: true,
      token: `JWT ${token}`,
      user: user,
      msg: 'Authentication was succesful'
      });
    }
    return next({code: 401, msg: 'Password is incorrect'});
  });
});

創建用戶

// Pre hook will take care of password creation
return user.save()
.then(function(user) {
  var payload = {
  iat: Math.round(Date.now() / 1000),
  exp: Math.round((Date.now() / 1000) + 30 * 24 * 60),
  iss: 'Whatever the issuer is example: localhost:3000',
  email: user.email
  };

  var token = jwt.encode(payload, 'secret');
  return res.status(201).json({user, token: `JWT ${token}`, msg: 'User was succesfully created'});
})
.catch((err) => next(err));
bcrypt.compare(req.body.password, user.password, function(err, results){
                if(err){
                    throw new Error(err)
                 }
                 if (results) {
                    return res.status(200).json({ msg: "Login success" })
                } else {
                    return res.status(401).json({ msg: "Invalid credencial" })
                }
               })
const bcrypt = require("bcryptjs");
const salt = bcrypt.genSaltSync(10);

const hashPassword = (password) => bcrypt.hashSync(password, salt);
const comparePassword = (password, hashedPassword) =>
  bcrypt.compareSync(password, hashedPassword);


bcrypt.compare(req.body.password, user.password)
            .then(valid => {
                if (!valid) {
                    return res.status(401).json({ message: 'Paire login/mot de passe incorrecte' });
                }
                
                res.status(200).json({
                    userId: user._id,
                    token:jwt.sign(
                        {userId: user._id},
                        process.env.ACCESS_TOKEN_SECRET_KEY,
                         {expiresIn:'24h'}
                    ),
                    message: 'connected'
                });
            })
            .catch(error => res.status(500).json({ error }));



enter code here

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM