• Hello to all! I am trying to create one functionality that forces the users to change their password after sometime, let’s say, 60 days, for example. I have made a modification to make this expiration happens in 5 minutes for test purposes, but i cant make it work. What am I doing wrong? thanks in advance.

    /**
     * Desconectar o usuário e forçar a troca de senha a cada 5 minutos (apenas para fins de teste).
     */
    
    // Define o número de segundos para a expiração da senha (5 minutos = 5 * 60)
    define( 'PASSWORD_EXPIRY_SECONDS', 5 * 60 );
    
    // Verifica se a senha expirou antes de permitir o login
    function password_expiry_check_password( $user, $password ) {
        if ( empty( $user ) ) {
            return $user;
        }
    
        $user_id = $user->ID;
        $last_password_update = get_user_meta( $user_id, 'password_last_updated', true );
    
        if ( $last_password_update ) {
            $expiry_time = strtotime( '+' . PASSWORD_EXPIRY_SECONDS . ' seconds', strtotime( $last_password_update ) );
    
            if ( time() > $expiry_time && $password !== '' ) {
                $user->set_role( 'expired_password' );
                wp_logout();
                $login_url = wp_login_url();
                $change_password_url = home_url( '/trocar-senha' );
    
                wp_safe_redirect( $change_password_url );
                exit;
            }
        }
    
        return $user;
    }
    add_filter( 'authenticate', 'password_expiry_check_password', 30, 2 );
    
    // Exibe um aviso na página de login para usuários com senha expirada
    function password_expiry_login_message() {
        if ( isset( $_GET['password-expired'] ) && $_GET['password-expired'] === 'true' ) {
            echo '<div class="notice notice-warning"><p>Sua senha expirou. Por favor, troque sua senha.</p></div>';
        }
    }
    add_action( 'login_message', 'password_expiry_login_message' );
    
    // Atualiza a data da última troca de senha sempre que o usuário altera sua senha
    function password_expiry_update_last_updated( $user_id, $new_pass ) {
        update_user_meta( $user_id, 'password_last_updated', date( 'Y-m-d H:i:s' ) );
    }
    add_action( 'password_reset', 'password_expiry_update_last_updated', 10, 2 );
    add_action( 'user_profile_update_errors', 'password_expiry_update_last_updated', 10, 3 );
    
    // Verifica se a nova senha é diferente da anterior
    function password_expiry_check_password_change( $errors, $user, $new_pass ) {
        if ( ! empty( $user ) && $new_pass !== '' ) {
            $user_id = $user->ID;
            $last_password = get_user_meta( $user_id, 'password_last', true );
    
            if ( ! empty( $last_password ) && $new_pass === $last_password ) {
                $errors->add( 'password_change_error', 'A nova senha deve ser diferente da anterior.' );
            }
        }
    
        return $errors;
    }
    add_filter( 'user_profile_update_errors', 'password_expiry_check_password_change', 10, 3 );
    add_filter( 'validate_password_reset', 'password_expiry_check_password_change', 10, 3 );
    
Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    Thread Starter Wanderson Silva

    (@wandersoncs)

    Hello @sterndata thanks for the hint, but i dont want to use third party plugins.

    Thread Starter Wanderson Silva

    (@wandersoncs)

    Here is an english version of the code:

    /**
     * Disconnect the user and force password change every 5 minutes (for testing purposes only).
     */
    
    // Define the number of seconds for password expiration (5 minutes = 5 * 60)
    define('PASSWORD_EXPIRY_SECONDS', 5 * 60);
    
    // Check if password has expired before allowing login
    function password_expiry_check_password($user, $password) {
        if (empty($user)) {
            return $user;
        }
    
        $user_id = $user->ID;
        $last_password_update = get_user_meta($user_id, 'password_last_updated', true);
    
        if ($last_password_update) {
            $expiry_time = strtotime('+' . PASSWORD_EXPIRY_SECONDS . ' seconds', strtotime($last_password_update));
    
            if (time() > $expiry_time && $password !== '') {
                $user->set_role('expired_password');
                wp_logout();
                $login_url = wp_login_url();
                $change_password_url = home_url('/change-password');
    
                wp_safe_redirect($change_password_url);
                exit;
            }
        }
    
        return $user;
    }
    add_filter('authenticate', 'password_expiry_check_password', 30, 2);
    
    // Display a warning on the login page for users with expired passwords
    function password_expiry_login_message() {
        if (isset($_GET['password-expired']) && $_GET['password-expired'] === 'true') {
            echo '<div class="notice notice-warning"><p>Your password has expired. Please change your password.</p></div>';
        }
    }
    add_action('login_message', 'password_expiry_login_message');
    
    // Update the last password change date whenever the user changes their password
    function password_expiry_update_last_updated($user_id, $new_pass) {
        update_user_meta($user_id, 'password_last_updated', date('Y-m-d H:i:s'));
    }
    add_action('password_reset', 'password_expiry_update_last_updated', 10, 2);
    add_action('user_profile_update_errors', 'password_expiry_update_last_updated', 10, 3);
    
    // Check if the new password is different from the previous one
    function password_expiry_check_password_change($errors, $user, $new_pass) {
        if (!empty($user) && $new_pass !== '') {
            $user_id = $user->ID;
            $last_password = get_user_meta($user_id, 'password_last', true);
    
            if (!empty($last_password) && $new_pass === $last_password) {
                $errors->add('password_change_error', 'The new password must be different from the previous one.');
            }
        }
    
        return $errors;
    }
    add_filter('user_profile_update_errors', 'password_expiry_check_password_change', 10, 3);
    add_filter('validate_password_reset', 'password_expiry_check_password_change', 10, 3);
    


    Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    Have you looked at the code for that plugin?

    Moderator bcworkz

    (@bcworkz)

    You have get_user_meta( $user_id, 'password_last', true ); but I don’t see where you are saving this value to start with. Maybe that’s why it’s not working for you?

    You must not save plain text passwords. You can save a hash of the current and earlier passwords and confirm a new password hash is not the same as the saved hashes. Saving plain text passwords in the DB is introducing an additional security risk.

    FWIW, my understanding is occasionally changing one’s password is no longer a recommended security measure. Most important is to use a good, very strong password. If that is done, there’s little to gain by changing it on occasion. IMO, if you want better security, remove the option to accept weak passwords. But it’s your site, you do you 🙂

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘Force users to change password after some time’ is closed to new replies.