AJAX和PHP登录类不能很好地协同工作.仍在登录无效凭据


AJAX and PHP login class aren't working nicely together. Invalid credentials still being logged in

我编写了一个PHP登录类:

include('../../datatypes/User.datatype.php');
$usher = new Authenticator;
$usher->checkCreds();
$usher->ensureHasAccess();
Class Authenticator {
    protected $user;
    protected function getCreds() {
        if (!isset($_POST['adminLogin']))
            echo('There was an error handling your request');
        else if (empty($_POST['username']) || empty($_POST['password']))
            echo('You must enter a username and password');
        $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
        $password = md5(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING));
        $this->user = new User;
        $this->user->username = $username;
        $this->user->password = $password;
    }
    public function checkCreds() {
        $this->getCreds();
        if (empty($this->user->username) || empty($this->user->password))
            echo('There was an error processing your request');
        include('../../../dbconnect.php');
        $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
        $stmt = $pdo->prepare('SELECT userID, userFName FROM Users WHERE username = ? AND password = ?');
        $stmt->bindParam(1, $this->user->username);
        $stmt->bindParam(2, $this->user->password);
        $stmt->bindColumn(1, $tblUserID, PDO::PARAM_INT);
        $stmt->bindColumn(2, $userFName, PDO::PARAM_STR);
        $stmt->execute();
        $stmt->fetch(PDO::FETCH_BOUND);
        if ($stmt->rowCount() != 1)
            echo "{'"result'" : false}";
        $this->user->tblUserID = $tblUserID;
        $this->user->firstName = $userFName;
        $status = true;
    }
    protected function createSessionID() {
        $seshID = mt_rand(99999, 1000000000);
        return $seshID;
    }
    protected function startSession() {
        if ($status === false)
            echo "{'"result'" : false}";
        echo "{'"result'" : true}";
        session_start();
        $_SESSION['id'] = $this->createSessionID();
        $secret = crypt($_SESSION['id']);
        $_SESSION['lastInsert'] = 0;
        $_SESSION['tblUserID'] = $this->user->tblUserID;
        $_SESSION['firstName'] = $this->user->firstName;
        $_SESSION['logged-in'] = true;
        header('Location: ../../index.php?=admin');
    }
    public function ensureHasAccess() {
        $grantedAccess = $this->startSession();
        if ($grantedAccess === false)
            header('Location: ../../error/403.php');
        echo "{'"result'" : true}";
        session_start();
    }
}

注意:我使用MD5进行测试,否则使用bcrypt。此外,没有AJAX也可以正常工作,它看起来像这样:

$('#login_form').on('submit', function(e) {
    e.preventDefault();
    var $form = $(this);
    var username = $('#username').val();
    var password = $('#password').val();
    if (username == '' || password == '')
        $('span#errForm').fadeIn(200).text('You must enter a username and password');
    $.ajax({
        type: 'post',
        url: '/classes/login/Authenticator.php',
        dataType: 'json',
        data: $form.serialize(),
        success: function(data) {
            if (data.result === false)
                $('span#errForm').fadeIn(200).text('Invalid username or password');
            else
                window.location = '/index.php?=admin';
        }
    });
    return false;
});

处理此表单:

    <div class="actionDiv">
        <span id="errForm"></span>
        <form id="login_form" action="./classes/login/Authenticator.php" method="post" onsubmit="return false;">
            <p>username: <input type="text" name="username" id="username" /></p>
            <p>password: <input type="password" name="password" id="password" /></p>
            <p><input type="submit" name="adminLogin" value="Log in" id="adminLogin" /></p>
        </form>
        <p><a id="cancelLogin" href="">Cancel</a></p>
    </div>

问题是,当没有输入表单数据或输入无效表单数据时,仍然会发生登录。当我使用正确的登录数据时,单击提交按钮什么也不做,我必须手动刷新页面。当没有输入表单数据时,会有提示信息,但是刷新页面只会创建一个空会话。

我尝试使用error: function(data),但没有任何变化。控制台也不会显示任何错误。我遗漏了什么?PHP在类中对此有任何影响吗?

编辑:在Chrome开发工具中,在网络下,Authenticator.php的状态是200 ok正确和不正确的登录

您忘记在以下javascript行返回false:

if (username == '' || password == '')
    $('span#errForm').fadeIn(200).text('You must enter a username and password');

应该是

if (username == '' || password == '')
{
    $('span#errForm').fadeIn(200).text('You must enter a username and password');
    return false;
}

此外,在php类中,您可以更改以下内容:

if ($stmt->rowCount() != 1)
    echo "{'"result'" : false}";

:

if ($stmt->rowCount() != 1)
    die "{'"result'" : false}";