S
S
SpideR-KOSS2018-08-14 13:17:47
MongoDB
SpideR-KOSS, 2018-08-14 13:17:47

How to connect correctly Passport.js?

I take an example from off. site.
I paste the code into the app.js file.

app.use(express.urlencoded({extended: true}));

var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;

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

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

app.use(passport.initialize());
  app.use(passport.session());

Express, Passport, Mongoose are naturally installed and declared in the file.
The "User" model has been created.
In the home.hbs file (the template engine is also installed and connected), I place the form, again with off. site.
<form action="/login" method="post">
    <div>
        <label>Username:</label>
        <input type="text" name="username"/>
    </div>
    <div>
        <label>Password:</label>
        <input type="password" name="password"/>
    </div>
    <div>
        <input type="submit" value="Log In"/>
    </div>
</form>

After submitting the form, an endless request, nothing happens.
What did I miss?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RidgeA, 2018-08-14
@SpideR-KOSS

is passport connected to the app?

app.use(passport.initialize());
  app.use(passport.session());

www.passportjs.org/docs/configure

A
Alex_Zdorgor, 2018-08-15
@Alex_Zdorgor

app.use(passport.initialize());
app.use(passport.session());

must be above the authentication route.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question