快递认证密码500内部错误

时间:2018-03-24 07:02:55

标签: node.js express mongoose postman

作为开始copypasteprogrammer我开始向我的应用添加一些salting and hashing。新用户的创建工作正常。但是Postman中的用户/密码验证给我带来了困难。我一直在收到错误。现在有500个内部服务错误。谁可以给我一些建议?

这里的架构:



const userSchema = new Schema({
    
    userName: { //email
        type: String,
        required: true, 
        unique: true,
        trim: true
    },
       password: {
        type: String,
        required: true
    }
  
});


// hashing and salting before saving
userSchema.pre('save', function (next) {
    let user = this;
    // only hash the password if it has been modified (or is new)
    if (!user.isModified('password')) return next();

    //generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
        if (err) return next(err);

        // hash the password using our new salt
        bcrypt.hash(user.password, salt, function (err, hash) {
            if (err) return next(err);

            // override the cleartext password with the hashed one
            user.password = hash;
            next();
        });
    });
});
    


mongoose.model('User', userSchema);



 路线:



const express = require('express');
const router = express.Router();

const ctrlAuthFiles = require('../controllers/authFiles');

router
    .route('/login')
    .post(ctrlAuthFiles.userLogin);

module.exports = router;



 控制器在这里:



const mongoose = require('mongoose'),
    Schema = mongoose.Schema;
const User1 = mongoose.model('User');

//fetch user and test password verification
const userLogin = function (req, res) {
    if (req.body) {
        User1
            .findOne({ userName: req.body.username })
            .exec((err, user) => {
                if (!user) {
                    res
                        .status(404)
                        .json({
                            "message": "username or password not found"
                        });
                    return;
                } else if (err) {
                    res
                        .status(404)
                        .json(err);
                    return;
                }
            });

        User1.comparePassword(req.body.password, function (err, isMatch) {
            if (err) throw err;
            console.log(isMatch);
        });

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


    } else {
        res
            .status(404)
            .json({
                "message": "no username or password"
            });
    }
        
}; 




0 个答案:

没有答案