Jquery 如果用户登录 in/authentication 使用 passportjs 失败时的警告框

Jquery alert box if user log in/authentication fails using passportjs

我目前正在尝试让 jQuery 警告框在用户因未在我的 node/express 应用程序中输入正确的用户名和密码而无法使用护照进行身份验证时弹出。

当发生这种情况时,我确实弹出了一个警告框,但它确实显示了大约 0.5 秒,然后在您可以阅读之前再次消失。但我需要它一直存在,直到用户相应地与它交互,我不确定为什么它不会。

找到我正在使用的内容的参考 here

我曾尝试使用 connect-flash,但无法使用我找到的所有示例。有什么方法可以让警告框停留而不是出现然后立即消失。

服务器端代码

//Global vars
var ari = require('ari-client');
var util = require('util');
var error;
var state;
var response;
var mysql = require('mysql');
var connection = mysql.createConnection({
    host : 'localhost',
    user : 'test',
    password : '',
    database : 'test'
  });
var express = require('express');
var app = express();
var passport = require('passport');
var passportLocal = require('passport-local');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');

server = require('http').createServer(app),
io = require('socket.io').listen(server);

  server.listen(3010, function () {
    console.log('listening on *:3010');
  });

  //All express middleware located here.
  //Access to local folder called public, enables the usage of local path files for CSS/JS/Images etc.
  app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
  app.use(morgan('dev')); // log every request to the console
  app.use(cookieParser()); // read cookies (needed for auth)
  app.use(flash());
  app.use(bodyParser.urlencoded({
      extended : false
    }));
  app.set('view engine', 'ejs');
  app.use(session({
      secret : 'testersecret',
      name: 'Test-cookie',
      resave : false,
      saveUninitialized : false,
      cookie : {
        maxAge : 3600000
      } // 1 Hour
    })); // session secret
  app.use(passport.initialize());
  app.use(passport.session());

  //Use passport and local strategy, outcome for success or failure is then dependent on if the users details that they entered matched up with the values in the database.
  passport.use(new passportLocal.Strategy(function (username, password, done) {
      //SQL Query to run. where the values passed are paired which and compared in the DB table.
      connection.query({
        sql : 'SELECT * from `userman_users` WHERE `username`= ?AND`password` = sha1(?)',
        timeout : 40000, // 40s
        values : [username, password]
      }, function (err, results, rows) {
        if (results.length > 0) {
          response = "Success";
          console.log(results);
        } else {
          console.log('Error while performing Query.');
          console.log(error);
          response = "Failed";
        }
        if (response === "Success") {
          done(null, {
            id : username
          });
        } else if (response === "Failed") {
          error = ("Incorrect username or password");
          Error();
          done(null, null);
        }
      });

    }));

  //Serialize user information
  passport.serializeUser(function (user, done) {
    done(null, user.id);
  });

  //Deserialize User information
  passport.deserializeUser(function (id, done) {
    done(null, {
      id : id
    });
  });

  //Gets the login route and renders the page.
  app.get('/', redirectToIndexIfLoggedIn, function (req, res) {
    res.render('login');
  });

  //The index page, isLoggedIn function always called to check to see if user is authenticated or in a session, if they are they can access the index route, if they are not they will be redirected to the login route instead.
  app.get('/index', checkLoggedIn, function (req, res) {
    res.render('index', {
      isAuthenticated : req.isAuthenticated(),
      user : req.user
    });
  });

  //This is where the users log in details are posted to, if they are successfull then redirect to index otherwise keep them on the login route.
  app.post('/login', passport.authenticate('local', {
      successRedirect : '/index',
      failureRedirect : '/',
      failureFlash : 'Invalid username or password.'
    }));

  //When logout is clicked  it gets the user, logs them out and deletes the session, session cookie included then redirects the user back to the login route.
  app.get('/logOut', function (req, res) {
    req.logOut();
    req.session.destroy();
    res.redirect('/')
  });

  //Check to see if logged in, if so carry on otherwise go back to login.
  function checkLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on to the next middleware stack.
    if (req.isAuthenticated())
      return next();

    // if they aren't redirect them to the index page
    res.redirect('/');
  }

  // If user authenticated then redirect to index, than arry on to the next middleware stack.
  function redirectToIndexIfLoggedIn(req, res, next) {
    if (req.isAuthenticated())
      res.redirect('/index');

    return next();
  }

  /*Server side listeners for all the ARI functionality from the client side E.G Kick/Mute,
  This handles all real time updating/maintains proper state even if page refreshed.*/
  io.sockets.on('connection', function (socket) {
  });

  //Updates the web page, used to update webpage in real time, and call channel dump function.
  //Used for error handling, emits error message to the server side to be displayed.
  function Error() {
    io.sockets.emit("error", error);
    error = '';
  }

客户端代码

jQuery(function ($) {
    //Global Varibles
    var socket = io.connect();

    //Handles all error messages for the stasis application being passed from the server side functions.
    socket.on("error", function (err) {
        $("<div title='Error Message'>" + err + "</div>").dialog({
            modal : true,
            buttons : {
                Ok : function () {
                    $(this).dialog("close");
                }
            }
        });
    });
});

表格

    <div class="container">

        <form action="/login" id="form_reset" method="post" class="form-signin">
            <h2 class="form-signin-heading">Please sign in</h2>
            <label for="inputUser" class="sr-only">Username</label>
            <input type="text" id="inputUser" name ="username" class="form-control username" placeholder="Username" required autofocus>
                <label for="inputPassword" class="sr-only">Password</label>
                <input type="password" name="password" id="inputPassword" class="form-control password" placeholder="Password" required>
                    <button class="btn btn-lg btn-primary btn-block clear" type="submit">Sign in</button>
                </form>

            </div> 

我对 passport 不是很好,因为我最近才开始使用它,如果这是一个简单的问题,我很抱歉......我只需要留下 jQuery 警告框!

任何建议或指导都会有所帮助。

failureFlash 意味着它正在闪烁消息,但我不知道你怎么知道它应该保留多长时间。

也许你应该重定向到 /error#Incorrect Password,并在对话框中显示散列(# 后面的内容)。