当前位置: 首页 > 知识库问答 >
问题:

WordPress Ajax登录错误消息

严琨
2023-03-14

我正在尝试为wordpress开发一个登录ajax表单。这个插件似乎工作得很好。如果我插入了正确的用户名和密码,登录将正常工作并显示正确的消息,然后重定向到正确的页面,但是如果我插入了错误的用户名和密码值,则不会发生任何情况,错误消息也不会出现。

似乎该函数是_wp_error,不回显该错误。

你知道为什么吗?低于我的代码

感谢在adv.

PHP

function ajax_login_init(){
wp_enqueue_script( 'ajax-login', get_template_directory_uri() . '/js/jquery.ajax.login.js', array( 'jquery' ) , $ver , true );
wp_localize_script('ajax-login', 'loginajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), ) );
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_met_login_member', 'met_login_member' );
}

if (!is_user_logged_in()) {
add_action('init', 'ajax_login_init');

}

function met_login_member() {
    $user_login     = $_POST['met_user_login']; 
    $user_pass      = $_POST['met_user_pass'];

    if( !check_ajax_referer( 'ajax-login-nonce', 'login-security', false) ) {
        echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('Session token has expired, please reload the page and try again', 'met').'</div>'));
    }

    else if( empty($user_login) || empty($user_pass) ){
        echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('Please fill all form fields', 'met').'</div>'));
    } else { // Now we can insert this account

        $creds = array();
       $creds['user_login'] = $user_login;
       $creds['user_password'] = $user_pass;
       $creds['remember'] = true;
       $user = wp_signon( $creds, false );

        if( is_wp_error($user) ) {
            echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.$user->get_error_message().'</div>'));
        } else {
            echo json_encode(array('error' => false, 'message'=> '<div class="alert alert-success">'.__('Login successful, reloading page...', 'met').'</div>'));
        }
    }

    die();
}

超文本标记语言

<div class="user-modal">

        <div class="user-modal-container">

            <ul class="switcher">

                <li><span><?php _e('Sign in', 'met'); ?></span></li>

                <li><span><?php _e('New Account', 'met'); ?></span></li>

            </ul>

            <div class="modal-login">

                <form id="login-form" class="modal-form" action="<?php echo home_url( '/' ); ?>" method="post" />

                    <p class="fieldset">

                        <label class="image-replace email" for="signin-email"><?php _e('Username', 'met'); ?></label>

                        <input id="user-login" class="full-width has-padding has-border" type="text" name="met_user_login" placeholder="<?php _e('Username', 'met'); ?>" value="" size="20" tabindex="10" required />

                    </p>

                    <p class="fieldset">

                        <label class="image-replace password" for="signin-password"><?php _e('Password', 'met'); ?></label>

                        <input id="user-pass" class="full-width has-padding has-border" type="password" name="met_user_pass" placeholder="<?php _e('Password', 'met'); ?>" value="" size="20" tabindex="20" required />

                        <span class="show-password"><?php _e('Show', 'met'); ?></span>

                    </p>

                    <p class="fieldset">

                        <label class="checkbox" for="rememberme">

                            <input name="rememberme" type="checkbox" id="rememberme" value="forever" tabindex="90"><?php _e('Remember me', 'met'); ?>

                        </label>

                    </p>

                    <p class="fieldset">

                        <button id="wp-submit" class="full-width" data-loading-text="<?php _e('Loading...', 'met') ?>" type="submit"><?php _e('Sign In', 'met'); ?></button>

                        <input type="hidden" name="action" value="met_login_member" />

                    </p>

                    <?php wp_nonce_field( 'ajax-login-nonce', 'login-security' ); ?>

                </form>

                <div class="errors"></div>

                <p class="modal-form-bottom-message"><span><?php _e('Lost your password?', 'met'); ?></span></p>

            </div>

    </div>
</div>

JS

$('button').on('click', function(e) {

    e.preventDefault();

    $.post(loginajax.ajaxurl, $('#login-form').serialize(), function(data) {

        var obj = $.parseJSON(data);

        $('.modal-login .errors').html(obj.message);

        if(obj.error === false) {
            window.location.reload(true);
        } else if(obj.error === true) {
            $('.alert-danger').delay(2000).fadeOut('slow',function(){$(this).hide();});
        }


    });

});

共有1个答案

李跃
2023-03-14

看来你的方向是对的。为了填补一些空白,我对您的代码做了一些更改。在WordPress中提交敏感(或任何)数据时,强烈建议清理从$POST收集的所有数据。

此外,我们正在通过简单的用户名或电子邮件检查来验证收集的凭据,如果检查正常,我们将定义成功登录时验证用户所需的用户数据,用户在访问时也将登录到管理仪表板/wp-admin/直接。为此,我们清除了所有旧的身份验证cookie,并为当前用户设置了新的cookie。

虽然这里没有什么新的进展,但这些步骤已经证明可以减少在WordPress中通过Ajax对用户进行身份验证时最常见的问题。

我已经测试了这个函数,它似乎与is_wp_error()抛出的错误消息没有问题。此外,我还添加了一个可选的简单方法来捕获最常见的错误消息,然后自定义这些消息。我希望它能让你进步!

function met_login_member() {

// First check the nonce, if it fails the function will break
if( !check_ajax_referer( 'ajax-login-nonce', 'login-security' ) ) {

    echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('Session token has expired, please reload the page and try again', 'met').'</div>'));

    die();

}

// Nonce is checked, get the POST data and sign the user on
$creds = array();
$creds['user_login']    = !empty( $_POST['met_user_login'] ) ? sanitize_user( trim($_POST['met_user_login']) ) : NULL; 
$creds['user_password'] = !empty( $_POST['met_user_pass'] ) ? sanitize_text_field( trim($_POST['met_user_pass']) ) : NULL; 
$creds['remember'] = true;

// Pass login details through wp_signon()
// wp_signon() accepts an optional boolean parameter false OR true, whether to use a secure cookie in case of running a website over SSL.
$user_creds = wp_signon( $creds, false );

$user_login     = (string) sanitize_user( $_POST['met_user_login'] );
$user_pass      = (string) sanitize_text_field( trim($_POST['met_user_pass']) );

// ---- CHECK IF USERNAME OR EMAIL EXISTS ---- //
if (username_exists($user_login)) {

    $user_exists = (bool)   true;
    $user        = (object) get_user_by('login', $user_login);

} elseif (email_exists($user_login)) {

    $user_exists = (bool)   true;
    $user        = (object) get_user_by('email', $user_login);

} else {

    $error = new WP_Error( 'no_user_found', 'Username or Email was not found, please try again', 'Page Data' );

    //echo json_encode( array( 'error' => true, 'message'=> '<div class="alert alert-danger">'.__('Username or Email was not found, please try again', 'met').'</div>') );
    //die();

} // end else

if ($user_exists === (bool) true) {

    // Define user data

    $user_id = $user->ID;
    $user_data = get_userdata($user_id);

    $username = $user_data->user_login;
    $userpass = $user_data->user_pass;

}

// ---- CHECK FOR EMPTY / INCORRECT DATA  ---- //
if( empty( $user_login ) && empty( $user_pass ) ){

    echo json_encode( array( 'error' => true, 'message'=> '<div class="alert alert-danger">'.__('The username and password cannot be empty', 'met').'</div>') );
    die();

} elseif ( is_wp_error( $user_signon ) ) {

    echo json_encode( array( 'error' => true, 'message'=> '<div class="alert alert-danger">'.$user_signon->get_error_message().'</div>') );
    die();

    // Optionally catch & customize error messages

    // $signon_errors = $user_creds->get_error_codes();

    // if ( in_array( 'invalid_username', $signon_errors ) ) {
    //     echo json_encode( array( 'error' => true, 'message'=> '<div class="alert alert-danger">'.__('Wrong username or email', 'met').'</div>') );
    //     die();    

    // } elseif ( in_array( 'empty_username', $signon_errors ) ) {
    //     echo json_encode( array( 'error' => true, 'message'=> '<div class="alert alert-danger">'.__('The username or email cannot be empty', 'met').'</div>') );
    //     die();

    // } elseif ( in_array( 'empty_password', $signon_errors ) ) {
    //     echo json_encode( array( 'error' => true, 'message'=> '<div class="alert alert-danger">'.__('The password field cannot be empty', 'met').'</div>') );
    //     die();

    // } elseif ( in_array( 'incorrect_password', $signon_errors ) ) {
    //     echo json_encode( array( 'error' => true, 'message'=> '<div class="alert alert-danger">'.__('Wrong password', 'met').'</div>') );
    //     die();   

    // } else {
    //     echo json_encode( array( 'error' => true, 'message'=> '<div class="alert alert-danger">'.__('Wrong username or password', 'met').'</div>') );
    //     die();

    // }

} else {

    wp_clear_auth_cookie();
    wp_set_current_user( $user_id, $username );
    wp_set_auth_cookie( $user_id );

    echo json_encode(array('error' => false, 'message'=> '<div class="alert alert-success">'.__('Login successful, reloading page...', 'met').'</div>'));

    die();

}

    die();

}
 类似资料:
  • 编辑:我发现了一个类似的问题,专门针对Facebook的登录。我正在使用电子邮件认证,但问题/解决方案可能是相同的。 userinfo={nsunderlyingerror=0x14704d4b0{Error domain=firauthinternalerrordomain code=3“(null)”userinfo={firautherroruserinfoderializedrespons

  • 我已经创建了一个登录名。html页面和登录名。php脚本。在脚本中,它将首先获得我们输入的用户名和密码,然后使用数据库检查用户名或密码是否存在,如果用户有效,则它将检查他的部门id,并使用部门权限打开他们的页面,但问题是无论他们的部门是什么,都会一直打开管理页面。请帮我做这件事。 这是我的login.html代码 登录。php脚本

  • 我试图了解Spotify的登录/授权流程。我遵循一个教程,最终得到了这段代码。当我尝试登录时,会出现以下错误:-canOpenURL:URL失败:“spotify操作:/”-错误:“(null)” 我查看了回购协议,发现我需要将spotify action和spotify添加到信息中。在LSApplicationQueriesSchemes下注册。然而,在这样做后,我仍然得到上述错误。

  • 我使用cakephp2.1和我在UsersController中使用登录操作如下。 和登录名。ctp代码如下。 当使用电子邮件和密码提交表单时,用户无法登录,因此显示错误“无效电子邮件或密码,请重试”。就连我都把这美元给递了-

  • 我目前正在创建一个Symfony3应用程序,我无法使我的登录表单工作;我遵循以下步骤: http://symfony.com/doc/current/cookbook/security/form_login_setup.html http://symfony.com/doc/current/cookbook/doctrine/registration_form.html 注册系统正在工作,但我无法