如何验证护照js中的密码

时间:2019-06-10 20:20:19

标签: node.js validation express passport.js express-validator

我想防止密码少于6个字符的用户输入数据库,但是我当前的逻辑不允许这样做。我正在使用express-validator

尽管密码少于6个字符,但仍将用户输入数据库。我应如何防止密码少于6个字符的用户输入数据库?

我正在为数据库使用knex / bookshelf orm和postgress

routes / users.js

router.post('/register', [
    check('password').isLength({ min: 6 }).withMessage('must be at least 6 chars long'),
    check('username').custom( value => {
        return User.forge({ username: value}).fetch().then( user => {
            if(user){
                return Promise.reject('Username already in use');
            }
        })
    }),
    check('email').custom( value => {
        return User.forge({ email: value}).fetch().then( user => {
            if(user){
                return Promise.reject('Email already in use');
            }
        })
    })
],
 (req, res, next) => {
    passport.authenticate('register', (err, user, info) => {
        if(err){
            console.log(err)
        }
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
          return res.status(500).send({       
              error: errors.array()
          })

        }

        if(info !== undefined){
            console.log(info.message)
            res.status(403).send(info.message)
        }else{
            req.logIn(user, err  => {
                const data = {
                    username: req.body.username.trim(), 
                    password: req.body.password.trim(),
                    email: req.body.email.trim()
                }
                // console.log(data);
                // debugger;
                User.forge({
                    username: data.username
                }).fetch().then( user => {
                    const token = jwt.sign({ id: user.id  }, process.env.JWT_SECRET);
                    jwt.verify(token, process.env.JWT_SECRET, function(err, data){
                        console.log(err, data);
                    })
                    console.log('user created in db');
                    res.status(200).send({
                        message: 'user created', 
                        token: token, 
                        auth: true  
                    });

                });
            })
        }
    })(req, res, next);
});

passport.js

passport.use(
    'register',
    new Local(
      {
        usernameField: 'username',
        passwordField: 'password',
        passReqToCallback: true,
        session: false,
      },
      (req, username, password, done) => {
        try {
            User.forge({username: username}, {email: req.body.email}).fetch().then(user => {

              if (user != null) {
                console.log('username or email already taken');
                return done(null, false, {
                  message: 'username or email already taken',
                });
              } else {
                bcrypt.hash(password, 12).then(hashedPassword => {
                  const user = new User({
                      username: req.body.username,
                      password: hashedPassword,
                      email: req.body.email
                  })
                  user.save().then( () => {
                      return done(null, user);
                  })
                });
              }
          });
        } catch (err) {
            return done(err);
        }
      },
    ),
);

用户模型

import bookshelf from '../config/bookshelf';
import validator from 'validator';
/**
 * Example User Model.
 */


const User = bookshelf.Model.extend({
    tableName: 'users',
    timestamps: false,
});

export default User;

1 个答案:

答案 0 :(得分:2)

创建用户后,您的代码正在检查验证错误。

代码应为:

(req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).send({ error: errors.array() })
    }
    passport.authenticate('register', (err, user, info) => {
        if(err){
            console.log(err)
        }
...

还请注意,您应该使用400级别的错误代码(而不是500)进行响应。400是针对提出的请求不正确(即验证问题)的请求,而500是针对服务器正常运行的请求。