PassportJS本地策略

时间:2017-11-24 17:03:57

标签: javascript angularjs mongodb mongoose passport.js

这是我第一次实施护照策略(使用本教程https://scotch.io/tutorials/easy-node-authentication-setup-and-local),我认为我犯了一个小错误导致了一个奇怪的问题。首次使用电子邮件和密码登录,没有问题(数据库连接,用户登录成功)第二次使用相同的电子邮件和密码我得到 rangeError:无效状态代码:1 并崩溃nodemon。

我试图找到有关此错误的更多信息,但确实没有任何信息。我确实遇到过类似问题的其他人,但自10月以来没有人回答他的问题。有人在乎这个问题吗?

routes.js

app.post('/login', passport.authenticate('local'), function (req, res {
console.log("passport user" + req.user);
res.status(200).json({
  user: req.user
});

  });

  app.get('/user/auth', auth.isAuthenticated, function (req, res) {
if (req.user) {
  res.status(200).json({
    user: req.user
  });
} else {
  res.sendStatus(401);
}
  });

app.post("/api/user", function (req, res) {
const user = req.body;
console.log(user);

User.findOne({ 'local.email': user.email },
  function (err, result) {
    if (err) {
      console.log(err);
      handleError(err, res);
      return;
    }
    if (result) {
      res.status(500).send("Email already exists in database");
    } else {
      var newUser = new User();
      newUser.local.password = createHash(user.password);
      newUser.local.email = user.email;
      newUser.local.name = user.name;
      newUser.local.mobile = user.mobile;
      newUser.save(function (err, result) {
        res.status(201).send("User added to database");
      });
    }

  });
  });

auth.js

passport.use(new LocalStrategy({ // redefine the field names the strategy (passport-local) expects
  usernameField: 'username',
  passwordField: 'password',
  passReqToCallback : true
}, function(req, email, password, done) {

// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {

// 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({ 'local.email' :  email }, function(err, user) {
// if there are any errors, return the error
  if (err)
  return done(err);

// check to see if theres already a user with that email
if (user) {
   return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
        } else {

 // if there is no user with that email
 // create the user
var newUser= new User();

// set the user's local credentials
newUser.local.email= email;
newUser.local.password = newUser.generateHash(password);

// save the user
newUser.save(function(err) {
 if (err)
  throw err;
   return done(null, newUser);
     });
        }

 });    
 });

}

var isAuthenticated = function(req, res, next) {
//console.log("isAuthenticated(): ", req.user);
if (req.isAuthenticated()) {
  next(); //good moves to the next one 
}
else {
  res.sendStatus(401);
}
  }

return {
    isAuthenticated: isAuthenticated,
  }
};

user.js的

var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');

// define the schema for our user model
var userSchema = mongoose.Schema({

local: {
    id: String,
    email: String,
    password: String,
    name: String,
    mobile: String
},

google: {
    id: String,
    token: String,
    email: String,
    name: String
}

});

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

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

// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);

HTML

<div class="panel panel-default">
<div class="panel-body">
<form name='loginForm' ng-submit='ctrl.login()' novalidate>
<div class="form-group">
<input class="form-control" type="text" name="username" placeholder="EMAIL" id="username" ng-model='ctrl.user.username'></div>

<div class="form-group">
<input class="form-control" type="password" name="password" placeholder="PASSWORD" id="password" ng-model='ctrl.user.password'></div>

<div class="form-group">
<input id="submit" name="submit" type="submit" class="btn btn-full btn-block" value="Log In"></div>

0 个答案:

没有答案
相关问题