使用护照并在用户或密码不正确时传递错误消息

时间:2017-06-13 18:25:59

标签: passport-local passport.js

我查看了文档,但我没有收到任何编码错误,但我也没有收到回复信息。如果我输错了电子邮件和密码,我得到的所有内容都是未经授权的。 Here is a image of the response

以下是代码:

const passport = require('passport');
const User = require('../models/user');
const config = require('../config');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const LocalStrategy = require('passport-local');

//creat local Strategy
const localOptions = {usernameField: 'email'}
const localLogin = new LocalStrategy(localOptions, function(email, password, done) {
  User.findOne({email: email}, function(err, user) {
    if(err) {return done(err);}
    if(!user) {
      return done(null, false, {message: 'Incorrect email'});
    }

    //compare passwords - is `password` equal to user.password?
    user.comparePassword(password, function(err, isMatch) {
      if(err) {return done(err);}
      if(!isMatch) {
        return done(null, false, {message: 'Incorrect password'});
      }
      return done(null, user);
    });
  });
});
//Setup options for JWT Strategy
const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromHeader('authorization'),
  secretOrKey: config.secret
};

 //Create JWT Strategy
const jwtLogin = new JwtStrategy(jwtOptions, function(payload, done) {
  //See if the user ID in the payload exists in our database
  // if it does, call 'done' with that user, otherwise
  // call done without a user object
  User.findById(payload.sub, function(err, user) {
    if (err) { return done(err, false); }

    if (user) {
      done(null, user);
    } else {
      done(null, false);
    }
  });
});
 //Tell passport to use this Strategy
 passport.use(jwtLogin);
 passport.use(localLogin);

1 个答案:

答案 0 :(得分:0)

您必须从route.js

中删除该行
authRoutes.post('/login', requireLogin, AuthenticationController.login);

authRoutes.post('/login', AuthenticationController.login);

并在控制器中添加以下代码。

var employeeEmail = req.body.username;
var employeePassword = req.body.password;

User.findOne({ username: employeeEmail }, function(err, employee)
{

if (err) { return next(err); } 

if (!employee) { return res.status(401).json("Incorrect email or password1"); }

employee.comparePassword(employeePassword, function(err, isMatch) {

if (err) { return next(err); } 

if (!isMatch) { return res.status(401).json("Incorrect email or password"); }
    return res.status(200).json(employee);
});