Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

351
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda