简体   繁体   中英

Repeated login action in Passport.js with local strategy

can't understand the following: I'm using express with passportjs local strategy login with session. When i do first login to my app it works fine. But when i login again when im already logged in, i do not recieve any response (no matter my creds are right or not). My passport.js:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const db = require('../models');

module.exports = function (app, db) {
  app.use(passport.initialize());
  app.use(passport.session());

  passport.serializeUser(function (user, done) {
    done(null, user.tn);
  });

  passport.deserializeUser(function (tn, done) {
    db.User.findByPk(tn, function (error, user) {
      done(error, user);
    });
  });

  const localStrategy = new LocalStrategy(async (tn, password, done) => {
    try {
      const user = await db.User.findByPk(tn);
      if (user) {
        const passwordIsValid = await user.verifyPassword(password);
        if (passwordIsValid) {
          return done(null, user);
        } else {
          return done(null, false, { message: 'Unknown user or password' });
        }
      } else {
        return done(null, false, { message: 'Unknown user or password' });
      }
    } catch (error) {
      return done(error);
    }
  });
  passport.use('local', localStrategy);
  return passport;
};

My login route:

const express = require('express');
const passport = require('passport');

module.exports = (app) => {
  app.post('/login', passport.authenticate('local'), (req, res) => {
    console.log('Authorized');
    res.send('Authorized');
  });
};

So i have 2 questions:

  1. Why i do not get Authorized response when i'm trying to login for the second time with the right/wrong creds?
  2. How to get Unknown user or password messages from localStrategy to send to client (where passportjs saves them)?

Ok, figured it out:

  1. Because of my wrong passport.deserializeUser() function (copypasted and forgot to change)
  2. You can get these messages in custom callback function, provided in passport.authenticate(strategy, options, callback) method (info object):
    app.post('/login', (req, res, next) => {
        passport.authenticate('local', (error, user, info) => {
            if (error) {
                return res.status(503).send({ message: error.message });
            }
            if (info) {
                console.log('message: ' + info.message);
            }
            req.login(user, (err) => {
                return res.status(200).send('You were authenticated & logged in');
            });
        })(req, res, next);
    });





The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM