在自定义登录表单上检查正确的用户名


10

我已经使用Jeff Star的教程来创建自己的自定义登录表单http://digwp.com/2010/12/login-register-password-code/。效果很好,但是我有一个问题。在重设密码表单上,如果有人错误输入了用户名(因此无法验证),他们将被踢到默认的wp-login.php?action = lostpassword并显示错误消息。

有没有办法重定向到我自己的错误页面?

谢谢!


赶时间,可以username_exists()以某种方式帮助您吗?
Ashfame 2011年

Answers:


10

他在该教程中发布的代码(非常不错的BTW)将表单的格式发布到内置的“重置密码”模块,该模块会在错误时重定向到login.php,但是您可以更改它,并根据原始内容构建自己的代码并添加转到模板页面,更改:

<form method="post" action="<?php echo site_url('wp-login.php?action=lostpassword', 'login_post') ?>" class="wp-user-form">
    <div class="username">
        <label for="user_login" class="hide"><?php _e('Username or Email'); ?>: </label>
        <input type="text" name="user_login" value="" size="20" id="user_login" tabindex="1001" />
    </div>
    <div class="login_fields">
        <?php do_action('login_form', 'resetpass'); ?>
        <input type="submit" name="user-submit" value="<?php _e('Reset my password'); ?>" class="user-submit" tabindex="1002" />
        <?php $reset = $_GET['reset']; if($reset == true) { echo '<p>A message will be sent to your email address.</p>'; } ?>
        <input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>?reset=true" />
        <input type="hidden" name="user-cookie" value="1" />
    </div>
</form>

至:

<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>" class="wp-user-form">
<div class="username">
    <label for="user_login" class="hide"><?php _e('Username or Email'); ?>: </label>
    <input type="text" name="user_login" value="" size="20" id="user_login" tabindex="1001" />
</div>
<div class="login_fields">
    <?php do_action('login_form', 'resetpass'); ?>
    <input type="submit" name="user-submit" value="<?php _e('Reset my password'); ?>" class="user-submit" tabindex="1002" />

    <?php
    if (isset($_POST['reset_pass']))
    {
        global $wpdb;
        $username = trim($_POST['user_login']);
        $user_exists = false;
        if (username_exists($username))
        {
            $user_exists = true;
            $user_data = get_userdatabylogin($username);
        } elseif (email_exists($username))
        {

            $user_exists = true;
            $user = get_user_by_email($username);
        } else
        {
            $error[] = '<p>' . __('Username or Email was not found, try again!') . '</p>';
        }
        if ($user_exists)
        {
            $user_login = $user->user_login;
            $user_email = $user->user_email;
            // Generate something random for a password... md5'ing current time with a rand salt
            $key = substr(md5(uniqid(microtime())), 0, 8);
            // Now insert the new pass md5'd into the db
            $wpdb->query("UPDATE $wpdb->users SET user_activation_key = '$key' WHERE user_login = '$user_login'");
            //create email message
            $message = __('Someone has asked to reset the password for the following site and username.') . "\r\n\r\n";
            $message .= get_option('siteurl') . "\r\n\r\n";
            $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
            $message .= __('To reset your password visit the following address, otherwise just ignore this email and nothing will happen.') . "\r\n\r\n";
            $message .= get_option('siteurl') . "/wp-login.php?action=rp&key=$key\r\n";
            //send email meassage
            if (FALSE == wp_mail($user_email, sprintf(__('[%s] Password Reset'), get_option('blogname')), $message))
            $error[] = '<p>' . __('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...') . '</p>';
        }
        if (count($error) > 0)
        {
            foreach ($error as $e)
            {
                echo $e . '<br/>';
            }
        } else
        {
            echo '<p>' . __('A message will be sent to your email address.') . '</p>';
        }
    }
    ?> 
    <input type="hidden" name="reset_pass" value="1" />
    <input type="hidden" name="user-cookie" value="1" />
</div>
</form>

看起来不错,我会通知您是否可行。
Pippin

1
好的,仅需进行一些更改,我就可以很好地工作。有一些语法错误,并且md5密钥生成器不起作用,所以我从wp-login.php中获取了一个。我现在有一个问题。当某人单击电子邮件中的URL创建新密码时,他们将被重定向到默认表单,因此现在我也需要为此创建一个表单。
皮蓬

@pippin:这里的md5密钥生成器代码是wp-login.php的代码,对于重定向,请尝试&redirect_to=$_SERVER['REQUEST_URI']在发送的电子邮件中添加链接。
Bainternet 2011年

我的链接现在看起来像这样$message .= get_option('siteurl') . "/wp-login.php?action=rp&key=$key&login=$user_login&redirect_to=$_SERVER['REQUEST_URI']\r\n";,但是很奇怪的是,当我添加&redirect时,消息没有被发送。。。另外,我是否不需要为用户输入新密码等新表单?
Pippin

是的,我忘记了这一点,您将需要创建自己的表单来重置密码,并可能将发送给用户的链接替换为当前URL,然后根据密钥检查用户的身份并向其显示表单。
Bainternet 2011年

8

这是@bainternet的代码的更新版本,已纠正语法错误,@ Val的建议以及wp-login.php 3.4.2的密钥生成器:

global $wpdb;
$username = trim($_POST['user_login']);
$user_exists = false;
// First check by username
if ( username_exists( $username ) ){
    $user_exists = true;
    $user = get_user_by('login', $username);
}
// Then, by e-mail address
elseif( email_exists($username) ){
        $user_exists = true;
        $user = get_user_by_email($username);
}else{
    $error[] = '<p>'.__('Username or Email was not found, try again!').'</p>';
}
if ($user_exists){
    $user_login = $user->user_login;
    $user_email = $user->user_email;

    $key = $wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM $wpdb->users WHERE user_login = %s", $user_login));
    if ( empty($key) ) {
        // Generate something random for a key...
        $key = wp_generate_password(20, false);
        do_action('retrieve_password_key', $user_login, $key);
        // Now insert the new md5 key into the db
        $wpdb->update($wpdb->users, array('user_activation_key' => $key), array('user_login' => $user_login));
    }

    //create email message
    $message = __('Someone has asked to reset the password for the following site and username.') . "\r\n\r\n";
    $message .= get_option('siteurl') . "\r\n\r\n";
    $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
    $message .= __('To reset your password visit the following address, otherwise just ignore this email and nothing will happen.') . "\r\n\r\n";
    $message .= network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . "&redirect_to=".urlencode(get_option('siteurl'))."\r\n";
    //send email meassage
    if (FALSE == wp_mail($user_email, sprintf(__('[%s] Password Reset'), get_option('blogname')), $message))
    $error[] = '<p>' . __('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...') . '</p>';
}
if (count($error) > 0 ){
    foreach($error as $e){
                echo $e . "<br/>";
            }
}else{
    echo '<p>'.__('A message will be sent to your email address.').'</p>'; 
}

1

我仍然遇到重置密钥无法正常工作的问题,电子邮件中的链接会将我重定向到标准密码重置页面,该页面的URL参数指示密钥存在问题,因此我更加密切地关注wp-login.php文件并包含$ wp_hasher对象,此问题已解决,并且电子邮件中的密码重置现在可以正常工作

if (($_SERVER['REQUEST_METHOD'] === (string) 'POST') && (isset($_POST['reset_pass']))) {

// Acccess global properties
global $wpdb, $wp_hasher;


// Variables
$error_pass_reset = array();
$username         = (string) trim($_POST['user_login']);
$user_exists      = (bool)   false;



// ---- USERNAME OR EMAIL EXISTS ---- //
if (username_exists($username)) {
    $user_exists = (bool)   true;
    $user        = (object) get_user_by('login', $username);
} // end if

else if (email_exists($username)) {
    $user_exists = (bool)   true;
    $user        = (object) get_user_by('email', $username);
} // end else if

else {
    $error_pass_reset[] = '<p>Username or Email was not found, please try again.</p>';
} // end else



// ---- USER EXISTS ---- //
if ($user_exists === (bool) true) {
    // Variables
    $user_login = (string) $user -> user_login;
    $user_email = (string) $user -> user_email;


    // Generate password reset key
if (empty($key)) {
    $key = (string) wp_generate_password(20, false);

    do_action('retrieve_password_key', $user_login, $key);


    // Create the $wp_hasher object
    if (empty($wp_hasher)) {
        require_once(ABSPATH . WPINC . '/class-phpass.php');

        $wp_hasher = new PasswordHash(8, true);
    }

    // Reset key with hasher applied (MD5 has string output)
    $hashed = (string) time() . ':' . $wp_hasher -> HashPassword($key);


    // Insert the new key into the database
    $wpdb -> update(
        $wpdb -> users,
        array(
            'user_activation_key' => $hashed
        ),
        array(
            'user_login' => $user_login
        )
    );
} // end if


    // Email message
    $message = (string)
    'Someone requested that the password be reset for the following account:' . "\r\n\r\n" .

    get_option('siteurl') . "\r\n\r\n" .

    'Username: ' . $user_login . "\r\n\r\n" .
    'If this was a mistake, just ignore this email and nothing will happen.' . "\r\n\r\n" .
    'To reset your password, visit the following address:' . "\r\n\r\n" .

    get_option('siteurl') . '/wp-login.php?action=rp&key=' . $key . '&login=' . $user_login . "\r\n";


    // Send email
    if ((bool) false === wp_mail($user_email, get_option('blogname') . ' Password Reset', $message)) {
        $error_pass_reset[] = '<p>The e-mail could not be sent at this time.</p>' . "\n";
    } // end if
} // end if


// Send the rest password email
do_action('login_form', 'resetpass');

} // end if (($_SERVER['REQUEST_METHOD'] === (string) 'POST') && (isset($_POST['reset_pass'])))

wp_hasher代码的答案对我来说非常有用,因为我创建了一个自定义的忘记密码模板。
Neelam Khan
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.