Сбой сравнения пароля Bcrypt при входе - PullRequest
0 голосов
/ 25 мая 2019

, когда я пытаюсь войти в систему с определенным URL, в точке bcrypting сравните пароль, это терпит неудачу.

маршрут входа в систему: -

router.post('/:compId/administration/login' , (req, res, next) => {

    Admin.find({'admins.email': req.body.email},{ companyID: req.params.compId })
    .exec()
    .then(admin => {
        if(admin.admins.length < 1) {
            return res.status(401).json({
                message: "Auth failed. admin not found."
            })
        }
        bcryptt.compare(req.body.password, admin.admins.password, (err, result) =>{
            if (err) {
                return res.json({
                message: "Auth failed. Check email and password"
                });             
            }                   
            if (result && admin.admins.verified === "true"){
                const adminEmaill = "xyz@info.com";
                const role2 = admin.admins.email===adminEmaill? "superadmin" : "admin";
                const token = jwt.sign( 
                    {
                        email: admin.admins.email,
                        phoneNo: admin.admins.phoneNumber,
                        role2,
                        comID: admin.admins.companyID
                    },
                    process.env.JWT_KEY,
                    {
                        expiresIn : "1h"
                    });
                    return res.status(200).json({
                    message: "Auth Successful",
                    token : token
                    }); 
            }
            else{
                console.log("admin is not verified");   
                return res.json({
                message: "Admin is not verified"
                }); 
            }
        });
    })
    .catch(err =>{
        if (err.code == 500)
                    res.status(500).send(["Something went wrong in login"]);
            else
            return next(err);
    }); 
});

В ответе он не проверяет моего пользователя и выдает message: "Auth failed. Check email and password" в ответ.

Я думаю, что у меня возникла ошибка при определении пути к паролю.

Моя модель: -

var adminSchema = new mongoose.Schema({
    companyName : {
                type: String,
                required: "Company  name can't be empty.",
                required: false
                },  
    companyID:  {
                type: String,
                },              
    admins:     {
                        email :     {
                                    type: String,
                                    required: "Email can't be empty.",
                                    unique: true
                                    },
                        password:   {
                                    type: String,
                                    required: "Password name can't be empty."
                                    },
                        firstName : {
                                    type: String,
                                    required: "First name can't be empty."
                                    },
                        lastName : {
                                    type: String,
                                    required: "Last name can't be empty."
                                    },  
                        phoneNumber :   {
                                    type: String,
                                    required: "Reqired for further contact. Can't be empty."
                                    },
                        verified: String,                               
                        role: String,
                        emailResetTokenn: String,
                        saltSecret: String,
                        users:[ userSchema ]    
    }           
});


adminSchema.pre('save', function (next){
    bcryptt.genSalt(10, (err, salt) => {
        bcryptt.hash(this.admins.password, salt, (err, hash) => {
            this.admins.password = hash ;
            this.admins.saltSecret = salt;
            next();
        });
    });
});

Я не понимаю, почему я получаю это? Является ли определение моего пароля правильным? Как я могу это сделать, если у меня есть пароль во вложенном объекте?

1 Ответ

1 голос
/ 25 мая 2019

Вам нужно вызвать метод findOne на модели мангуста.

 Admin.findOne({'admins.email': req.body.email, companyID: req.params.compId}) ...

Результатом метода find является массив

...