Не могу войти в систему и без сообщений об ошибках, используя node / express & passport.js - PullRequest
0 голосов
/ 08 ноября 2018

У меня нет проблем с регистрацией, но при попытке войти в систему все, что происходит, - страница обновляется без сообщений об ошибках.

Вот форма входа (я использую ejs)

<form class="" action="/login" method="post">
      <h1>Login</h1>
      <div class="EmailAddress">
        <input type="text" name="email" placeholder="Email">
      </div>
      <div class="Password">
        <input type="password" name="password" placeholder="Password">
      </div>
      <div class="Login">
        <input type="submit" value="submit">
      </div>
    </form>  

Я создал две модели для двух разных типов пользователей, одна из которых является оператором, а другая - клиентом, и они практически идентичны и отлично работают при регистрации. На данный момент я только пытаюсь войти в систему Клиента , поэтому вот мой файл passport.js :

Редактировать: я обновил его в соответствии с тем, что было сказано ниже zerosand1s и, к сожалению, до сих пор не работает.

  module.exports = function(passport) {
  //LocalStrategy
  passport.use(
    new LocalStrategy(
      { passReqToCallback: true },
      {
        usernameField: "email",
        passwordField: "password"
      },
      function(req, email, password, done) {
        let query = { email: email };
        // checking the name in the database against the one submitted on the form
        Customer.findOne(query, function(err, customer) {
          if (err) throw err;
          if (!customer) {
            return done(null, false, {
              message: "No such password",
              type: "error"
            });
          }
          //Match password
          bcrypt.compare(password, customer.password, function(err, isMatch) {
            if (err) throw err;
            if (isMatch) {
              return done(null, customer);
            } else {
              return done(null, false, {
                message: "No such password",
                type: "error"
              });
              // if the password isnt an matc return wrong password
            }
          });
        });
      }
    )
  );
};

  passport.serializeUser(function(customer, done) {
    done(null, customer.id);
  });

  passport.deserializeUser(function(id, done) {
    Customer.findById(id, function(err, customer) {
      done(err, customer);
    });
  });

Вот мой файл маршрутов для входа index.js

// login route
router.get("/login", function(req, res) {
  res.render("login", {message: req.flash('error')});
});

// login Process
router.post("/login", function(req, res, next) {
  passport.authenticate('local', {
    // were using the LocalStrategy used in config/passport file
    successRedirect:'../customer/dashboard',
    failureRedirect:'/login',
    failureFlash: true
  })(req, res, next);
});

router.get("/customer/dashboard", function(req, res) {
  res.render("customer/dashboard");
});

И единственное место, где я могу подумать, что это может быть проблема, это мой app.js file:

// Express session
app.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true,
  cookie: { secure: true }
}));

// Express messages middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  // setting a global variable called express-messages
  next();
});

// Express validator middleware
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));

app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// Passport Config
require('./config/passport')(passport);
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());

app.get('*', function(req, res, next) {
  res.locals.customer = req.customer || null;
  next();
});

app.use(cookieparser());


// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

app.listen(3000, function() {
  console.log('server is running');
});
app.use(flash());
app.use(routes);

Я потратил весь день на то, чтобы рвать на себе волосы, поэтому любая помощь очень ценится

1 Ответ

0 голосов
/ 09 ноября 2018

Поскольку вы используете email для входа в систему (вместо значения по умолчанию username), вам необходимо указать это в своей локальной стратегии Passport.

Из паспортной документации,

По умолчанию LocalStrategy ожидает найти учетные данные в параметрах имя пользователя и пароль. Если ваш сайт предпочитает называть эти поля иначе доступны варианты для изменения значений по умолчанию.

passport.use(new LocalStrategy({
    passReqToCallback: true
    usernameField: 'email',
    passwordField: 'passwd'
  },
  function(username, password, done) {
    // ...
  }
));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...