使用护照注册和使用Sequelize保存无效(意外的'')

时间:2018-08-07 09:28:26

标签: node.js sequelize.js passport.js postman

我的护照有问题,并在Node.js项目中进行了续集。 实际上,当我想注册时,我使用邮递员来调用/ users / signup路由,它显示了:Unexpected''和:

::1 - - [07/Aug/2018:09:20:19 +0000] "POST /users/signup HTTP/1.1" - - "-" "PostmanRuntime/7.2.0"
Executing (default): SELECT "user_id", "username", "name", "firstname", "email", "type", "location", "password", "createdAt", "updatedAt" FROM "users" AS "users" LIMIT 1;

有代码:

/* CREATE an account */
  app.post('/users/signup', (req, res) => {

      db.users.find({ $or: [{ email: req.body.email }, { username: req.body.username }] }).then(user => {

  if (err) {
    return res.send(err);
  }
  if (user) {
    if (user.email == req.body.email) {
      return res.send("This email is already taken.")
    }
    return res.send("This username is already taken.")
  }
  else {

    const data = {
      username: req.body.username,
      name: req.body.name,
      firstname: req.body.firstname,
      email: req.body.email,
      location: req.body.location,
      type: req.body.type,
      password: req.body.password
    };

    db.users.create({
      username: data.username,
      name: data.name,
      firstname: data.firstname,
      email: data.email,
      location: data.location,
      type: data.type,
      password: data.password

    }).then(newUser => {
      res.send("newUser saved to database")
      // `req.user` contains the authenticated user.
      //TODO : res.redirect('/profile/' + req.body.username);
    })
      .catch(err => {
        console.log(err);
        res.status(400).send("unable to save this newUser to database");
      })

  }

}).catch(err => {
  console.log(err);
  res.status(400).send("signup failed");
})

})

还有我的模型(db.users):

const bcrypt = require("bcrypt-nodejs");

module.exports = (sequelize, DataTypes) => {
  // TABLE USERS
  const Users = sequelize.define('users', {

      user_id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      username: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false
      },
      firstname: {
        type: DataTypes.STRING,
        allowNull: false
      },
      email: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
        validate: {
          isEmail: true
        }
      },
      type: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      location: {
        type: DataTypes.STRING
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false
      }
  });

  // methods ======================
  // generating a hash
  Users.generateHash = function (password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
  };

  // checking if password is valid
  Users.validPassword = function (password) {
    return bcrypt.compareSync(password, this.password);
  };

  //hashing a password before saving it to the database
  Users.beforeCreate('save', function (next) {
    var user = this;
    bcrypt.hash(user.password, 10, function (err, hash) {
      if (err) {
        return next(err);
      }
      user.password = hash;
      next();
    })
  });

  return Users;
};

我的 passport.js

// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
var db = require('../db')

// expose this function to our app using module.exports
module.exports = function (passport) {

    var User = db.users;
    // =========================================================================
    // passport session setup ==================================================
    // =========================================================================
    // required for persistent login sessions
    // passport needs ability to serialize and unserialize users out of session

    // used to serialize the user for the session
    passport.serializeUser(function (user, done) {
        done(null, user.id);
    });

// used to deserialize the user
passport.deserializeUser(function (id, done) {
    User.find({
        where: { user_id: user_id }
    })
        .then(function (user) {
            done(err, user);
        }).catch(function (err) {
            return done(err);
        })
});


    // =========================================================================
    // LOCAL LOGIN =============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use('local-login', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true // allows us to pass back the entire request to the callback
    },
        function (req, email, password, done) { // callback with email and password from our form

            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            User.findOne({ email : email }, function (err, user) {
                // if there are any errors, return the error before anything else
                if (err)
                    return done(err);

                // if no user is found, return the message
                if (!user)
                    return done(null, false, { message: 'User not found.' }); // req.flash is the way to set flashdata using connect-flash
                // if the user is found but the password is wrong
                if (!user.validPassword(password))
                    return done(null, false, { message: 'Incorrect password.' }); // create the loginMessage and save it to session as flashdata

                // all is well, return successful user
                return done(null, user);
            });

        }));

};

我找不到问题的根源。我是Node.js的新手,而且几个小时以来一直陷于困境。这里有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

经过讨论,我们发现第一个错误来自User db模型上的beforeSave钩子,在该钩子上使用了一个散列函数,其中缺少一个null参数作为第三个参数,因此bcrypt是引发“未通过回调”错误。还有其他一些错误,例如对promise和回调的滥用,我建议您对promise进行学习,并仔细检查文档和有关如何使用该库的示例,例如Sequelize和bcrypt(如何生成和使用)。例如盐)。


上一个答案

我认为问题出在您的“本地登录”策略:护照使用回调,但续集使用承诺,因此从未调用您的User.findOne回调。尝试类似的事情:

app.post("/users/signup", (req, res) => {
  return db.users
    .find({
      $or: [
        {
          email: req.body.email
        },
        {
          username: req.body.username
        }
      ]
    })
    .then(user => {
      if (user) {
        if (user.email == req.body.email) {
          return res.send("This email is already taken.");
        }
        return res.send("This username is already taken.");
      } else {
        return db.users
          .create({
            username: req.body.username,
            name: req.body.name,
            firstname: req.body.firstname,
            email: req.body.email,
            location: req.body.location,
            type: req.body.type,
            password: req.body.password
          })
          .then(newUser => {
            res.send("newUser saved to database");
          });
      }
    })
    .catch(err => {
      console.error(err);
      res.status(400).send("unable to save this newUser to database");
    });
});

路线相同,反序列化: app.post('/ users / signup',(req,res)=> {

db.users.find({ $or: [{ email: req.body.email }, { username: req.body.username }] })
    .then(user=>{})
    .catch(err=>{})