Passport本地身份验证无效

时间:2016-06-27 05:22:17

标签: node.js passport.js mean-stack passport-local mean.io

我正在使用MEAN STACK构建应用程序。我想在登录表单中使用护照本地身份验证。但是表单提交的时间我正在获得POST http://localhost/login 404(未找到)请看下面我的代码这是我的控制器:

lyfee.controller('loginCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.user = {};
    $scope.login = function() {
        //  var data = {User: $scope.user }
        //console.log($scope.user);
        console.log("login function call");
        $http.post('/login', $scope.user);
        console.log("login request send");


    }
}]);

这是我的server.js:

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
    function(username, password, done) {
        User.getUserByusername(username, function(err, user) {

            if (err) throw err;
            if (!user) {
                return done(null, false, {
                    message: 'Unknown USER'
                });

            }

            User.comparePassword(password, user.password, function(err, isMatch) {
                if () throw err;
                if (isMatch) {
                    return done(null, user);
                } else {
                    return done(null, false, {
                        message: 'Invalid password'
                    });
                }
            });
        });

    }));

app.post('/login',
    passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/login',
        failureFlash: true
    }),
    function(req, res) {
        res.redirect('/');

    });

我应该在哪个文件中写入getUserByusername和comparePassword函数?我正在做的错误请纠正它并给我一些建议。

1 个答案:

答案 0 :(得分:0)

在您的模型中假设User.js编写如下函数:

/**
 * Check the user's password
 */
dbSchema.methods.comparePassword = function(candidatePassword, cb) {
    var status = this.password.localeCompare(candidatePassword.trim());
    if (status != 0) {
        return cb(err); 
    }
    cb(null, true);
};

然后使用像这样的函数

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({
      username: username
    }, function(err, user) {
      if (err) throw err;
      if (!user) {
        return done(null, false, {
          message: 'Unknown USER'
        });

      }
      /**
      * Check the user's password
      */
      User.comparePassword(password, user.password, function(err, isMatch) {
        if (err) throw err;
        if (isMatch) {
          return done(null, user);
        } else {
          return done(null, false, {
            message: 'Invalid password'
          });
        }
      });
    });
}));