Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

352
Vistas
No redirect on failed passport authentication

New to nodejs, liking it so far, trying to do some custom handling for passport authentication. The success redirect works fine, however upon an unsuccessful attempt i would like to not continue the post event.
What I'm trying to accomplish is fire an alert off that opens a dialog (this part is working like I want, via the socket call) to the current page if there is an issue with the login attempt. The browser just waits if I don't call res.send() for example, or attempts to redirect to a page that does not exist if I do.

routes.js

app.post('/login', function (req, res, next) {
    passport.authenticate('local-login', function (err, user, msg) {
        if (err) {
            io.emit('status alert', err);
        }
        if (!user) {
            io.emit('status alert', msg);
            //res.send();
        }
        req.logIn(user, function (err) {
            if (err) {
                io.emit('status alert', err);
            }
            if (user) {
                return res.redirect('/loginsplash');
            }
        });
    })(req, res, next);
});

passport.js

passport.use(
    'local-login',
    new LocalStrategy({
        usernameField : 'username',
        passwordField : 'password',
        passReqToCallback : true
    },
    function (req, username, password, done) {
        db.getConnection().query("SELECT * FROM users WHERE uname = ?", [username], function (err, rows) {
            if (err)
                return done(err);
            if (!rows.length) {
                return done(null, false,  'Invalid Username or Password.');
            }

            // if the user is found but the password is wrong
            if (!bcrypt.compareSync(password, rows[0].upw))
                return done(null, false, 'Invalid Username or Password.');

            // all is well, return successful user
            return done(null, rows[0]);
        });
    })
);
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Well after a weekend of persistence and trial/error, my hunch to use ajax seems to be right. I finally came across a similar so here that was helpful. Hope this helps someone else, I'm probably going to tweak it some, but right now basically if the ajax response is empty (res.end), my custom dialog pops up. If there's something in it (from the res.redirect), it redirects to the intended page :

passport.js, no changes from above

routes.js

app.post('/login/ajax', function (req, res, next) {
        passport.authenticate('local-login', function (err, user, info) {
                    if (err) { return next(err); }
                    if (!user) { return res.end(); }
                    req.logIn(user, function (err) {
                        if (err) { return next(err); }
                        return res.redirect('/loggedin');
                    });
        })(req, res, next);
    });

ajax call in .ejs page

$.ajax({
        type: "POST",
        url: "/login/ajax",
        data: { username: username , password: password },
        dataType: 'html',
        success: function(data) {
        if (data) {
          window.location.href = '/loginsplash';
          }
          else {
            OpenFeedbackMsgDlg("Login Failed");
          }
        }
      }).done(function () {
                console.log("http request succeeded");
                alert("login success");
            });
    });

If anyone has suggestions/alternate approaches, I'd still be interested in learning.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda