簡體   English   中英

jQuery警報框,如果用戶使用password.js登錄/身份驗證失敗

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

當前,我正在嘗試讓jQuery警報框彈出,當用戶無法使用護照進行身份驗證而未能在我的節點/快速應用程序中輸入正確的用戶名和密碼時,彈出該對話框。

發生這種情況時,我確實會彈出一個警報框,但是從字面上看它會顯示約0.5秒,然后在消失之前再次消失。 但是我需要保留它直到用戶進行相應的交互,並且我不確定為什么它不會。

這里可以找到對所用對象的引用。

我嘗試使用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> 

我對護照不太滿意,因為我最近才開始使用它,所以很抱歉,如果它是一個簡單的問題.....我只需要jQuery警報框即可!

任何建議或指導都會有所幫助。

failureFlash表示它正在閃爍該消息,但是我看不出如何知道應將其保留多長時間。

也許您應該重定向到/ error#Incorrect Password,並在對話框中顯示哈希(在#之后是什么)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM