사용자 정의 로그인 양식에서 올바른 사용자 이름을 확인하십시오


10

필자 자신의 사용자 지정 로그인 양식 ( http://digwp.com/2010/12/login-register-password-code/) 을 만드는 데 Jeff Star의 자습서를 사용했습니다 . 잘 작동하지만 한 가지 문제가 있습니다. 비밀번호 재설정 양식에서 누군가 사용자 이름을 잘못 입력하면 (확인하지 못함) 오류 메시지와 함께 기본 wp-login.php? action = lostpassword로 시작됩니다.

내 자신의 오류 페이지로 리디렉션하는 방법이 있습니까?

감사!


서두에서, 수 username_exists()어떻게 든 당신을 도와 드릴까요?
— Ashfame

답변:


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

@pippin : 여기에있는 md5 키 생성기 코드는 wp-login.php 용 코드이며 리디렉션의 경우 &redirect_to=$_SERVER['REQUEST_URI']보내는 전자 메일의 링크에 추가 하십시오.
— Bainternet

내 링크는 이제 다음과 $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

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
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.