簡體   English   中英

嘗試登錄時出現錯誤 [ERR_INVALID_ARG_TYPE]

[英]Getting error [ERR_INVALID_ARG_TYPE] while trying to login

我已經為我的頁面提供了login/register系統,但是在嘗試login時遇到了一個我一直在努力解決的錯誤:

TypeError [ERR_INVALID_ARG_TYPE]: The "salt" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
at check (internal/crypto/pbkdf2.js:59:10)
at Object.pbkdf2 (internal/crypto/pbkdf2.js:25:5)
at validPassword (/Users/krzysztofbialk/TO.DO/config/passwordUtils.js:14:29)
at /Users/krzysztofbialk/TO.DO/config/passport_log.js:21:33
at processTicksAndRejections (internal/process/task_queues.js:93:5)

看起來這里有問題:

密碼Utils.js

const crypto = require('crypto');
function genPassword(password) {
    let salt = crypto.randomBytes(32).toString('hex');
    let genHash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
    return {
      salt: salt,
      hash: genHash
    };
};
function validPassword(password, hash, salt) {
    let hashVerify = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
    return hash === hashVerify;
};
module.exports.validPassword = validPassword;
module.exports.genPassword = genPassword;

passport_log.js

const customFields = {
    usernameField: 'email',
    passwordField: 'password'
    };
    const verifyCallback = (username, password, done) => {
            LogUser.findOne({username: username})
                .then((user) => {
                console.log(user)
                    if (!user) {return done(null, false)}
                    const isValid = validPassword(password, user.hash, user.salt);
                    if (isValid) {
                        return done(null, user);
                    } else {
                        return done(null, false);
                    }
                })
                .catch((err) => {
                    done(err);
                });
        };
// LOCAL STRATEGY; it looks good, doesn't it?
    passport.use(new LocalStrategy(customFields, verifyCallback));

登錄發帖路徑

router.post('/login', passport.authenticate('local', { successRedirect: '/private', failureRedirect: '/login' }));

當我 console.log(user) 它返回

{
  _id: 60cbb580ef0690505762a581,
  username: 'qw@wp.pl',
  createdAt: 2021-06-17T20:50:08.570Z,
  __v: 0
}

但是register成功后會返回

{
  _id: 60cbb580ef0690505762a581,
  username: 'qw@wp.pl',
  hash: 'b762ebbafb266dab12f71eeabbdae6d53e62e91937c51d99fe1816e6d401379b91495b7db0f56b8143e8607bf72ce2a565c38eeeb1f916cc9c0a85d8e6d3c9fe',
  salt: '0536b806ac052e5628c74e7ec9fd6b94fb0d1bd4bc0e93fdfdf51ed5b964c581',
  createdAt: 2021-06-17T20:50:08.570Z
}

DB中:

   _id:ObjectId("60cbb580ef0690505762a581")
    username:"qw@wp.pl"
   hash:"b762ebbafb266dab12f71eeabbdae6d53e62e91937c51d99fe1816e6d401379b91495b..."
   salt:"0536b806ac052e5628c74e7ec9fd6b94fb0d1bd4bc0e93fdfdf51ed5b964c581"
    createdAt:2021-06-17T20:50:08.570+00:00
    __v:0

為什么register后用戶數據中有hash和salt,但嘗試login時卻沒有?

LogUser架構:

const LogUserSchema = new mongoose.Schema({
name: {
    type: String    
},
email: {
    type: String,
    // required: true,
    // unique: true
},
password: {
    type: String,
    // required: true
},
image: {
    type: String
},
createdAt: {
    type: Date,
    default: Date.now
},
hash: {
    type: String
},
salt: {
    type: String
}});

我已經沒有想法出了什么問題。 很高興收到任何答案!

我已經為我的頁面提供了login/register系統,但是我在嘗試login時遇到了一個錯誤:

TypeError [ERR_INVALID_ARG_TYPE]: The "salt" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
at check (internal/crypto/pbkdf2.js:59:10)
at Object.pbkdf2 (internal/crypto/pbkdf2.js:25:5)
at validPassword (/Users/krzysztofbialk/TO.DO/config/passwordUtils.js:14:29)
at /Users/krzysztofbialk/TO.DO/config/passport_log.js:21:33
at processTicksAndRejections (internal/process/task_queues.js:93:5)

看起來這里有問題:

密碼實用程序.js

const crypto = require('crypto');
function genPassword(password) {
    let salt = crypto.randomBytes(32).toString('hex');
    let genHash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
    return {
      salt: salt,
      hash: genHash
    };
};
function validPassword(password, hash, salt) {
    let hashVerify = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
    return hash === hashVerify;
};
module.exports.validPassword = validPassword;
module.exports.genPassword = genPassword;

passport_log.js

const customFields = {
    usernameField: 'email',
    passwordField: 'password'
    };
    const verifyCallback = (username, password, done) => {
            LogUser.findOne({username: username})
                .then((user) => {
                console.log(user)
                    if (!user) {return done(null, false)}
                    const isValid = validPassword(password, user.hash, user.salt);
                    if (isValid) {
                        return done(null, user);
                    } else {
                        return done(null, false);
                    }
                })
                .catch((err) => {
                    done(err);
                });
        };
// LOCAL STRATEGY; it looks good, doesn't it?
    passport.use(new LocalStrategy(customFields, verifyCallback));

登錄后路由

router.post('/login', passport.authenticate('local', { successRedirect: '/private', failureRedirect: '/login' }));

當我 console.log(user) 它返回

{
  _id: 60cbb580ef0690505762a581,
  username: 'qw@wp.pl',
  createdAt: 2021-06-17T20:50:08.570Z,
  __v: 0
}

register成功后返回

{
  _id: 60cbb580ef0690505762a581,
  username: 'qw@wp.pl',
  hash: 'b762ebbafb266dab12f71eeabbdae6d53e62e91937c51d99fe1816e6d401379b91495b7db0f56b8143e8607bf72ce2a565c38eeeb1f916cc9c0a85d8e6d3c9fe',
  salt: '0536b806ac052e5628c74e7ec9fd6b94fb0d1bd4bc0e93fdfdf51ed5b964c581',
  createdAt: 2021-06-17T20:50:08.570Z
}

DB

   _id:ObjectId("60cbb580ef0690505762a581")
    username:"qw@wp.pl"
   hash:"b762ebbafb266dab12f71eeabbdae6d53e62e91937c51d99fe1816e6d401379b91495b..."
   salt:"0536b806ac052e5628c74e7ec9fd6b94fb0d1bd4bc0e93fdfdf51ed5b964c581"
    createdAt:2021-06-17T20:50:08.570+00:00
    __v:0

為什么register后用戶數據中有hash和salt,而嘗試login時卻沒有?

LogUser架構:

const LogUserSchema = new mongoose.Schema({
name: {
    type: String    
},
email: {
    type: String,
    // required: true,
    // unique: true
},
password: {
    type: String,
    // required: true
},
image: {
    type: String
},
createdAt: {
    type: Date,
    default: Date.now
},
hash: {
    type: String
},
salt: {
    type: String
}});

我已經沒有想法了。 很高興收到任何答案!

        solution for me as below

my User model
    
         const UserSchema = new mongoose.Schema({
       password: String,
      salt: String,
    });
    
    
    UserSchema.pre("save", function (next) {
      if (this.isModified("password") || this.isNew) {
      var salt = crypto.randomBytes(32).toString('hex');
      var genHash = crypto.pbkdf2Sync(this.password, salt, 10000, 64, 'sha512').toString('hex');
      this.salt = salt;
      this.password = genHash;
      next();
    
    
    module.exports = mongoose.model('User', UserSchema)
      } else {
        return next();
      }
    });
    
    
    
    my passport.js file
    
     passport.use(new LocalStrategy(
        {
          usernameField: 'email',
          passReqToCallback: true
        },
        function (req, email, password, done) {
          User.findOne({ email: email }, function (err, user) {
            if (err) { return done(err); }
            if (!user) {
              return done(null, false, req.flash('error', 'Incorrect email'));
            }
            const isPasswordMatched = user.validPassword(password);
            console.log('isPasswordMatched===',isPasswordMatched)
            if (!isPasswordMatched) {
              return done(null, false, req.flash('error', 'Incorrect password'));
            }
            return done(null, user);
          });
        }
      ));

暫無
暫無

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

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