Wordpress - Ban a user and end their session
Use wp_logout()
. It calls wp_clear_auth_cookie()
and invalidates the current log-in information immediately.
Sample code, not tested:
add_action( 'init', 'log_out_banned_user' );
function log_out_banned_user() {
if ( ! is_user_logged_in() )
return;
$user = wp_get_current_user();
if ( ! get_user_option( 'rc_banned', $user->ID, false ) )
return;
wp_logout();
wp_redirect( home_url( '/' ) );
exit;
}
While toscho's method works, a simpler approach might be to use the authenticate
hook to prevent them from authenticating via cookie, or any other means, in a more direct fashion.
Totally untested code. Should work though.
// the priority of 999 is to ensure it's last in the auth chain
add_filter('authenticate', 'force_fail_banned_users', 999, 3);
function force_fail_banned_users($user, $username, $password) {
if ( ! is_a($user, 'WP_User') ) {
// we only care about actual users who already auth'd okay via some means
return $user;
}
if ( rc_is_user_banned( $user->ID ) ) {
// user is banned, so return a failure case
return new WP_Error('banned_user', 'Banned message goes here.');
}
// user not banned, so return the user normally
return $user;
}
The authenticate filter chain lets you decide whether or not a user is authenticated at every possible opportunity for them to authenticate. Returning a value WP_User logs them in. Returning a WP_Error of any sort fails their authentication attempt, no matter how it was done, whether via username/password or via cookie.
I also write similar plugin and already published it on WordPress.org. I think the best solution drop user session immediately then administrator click "ban" (block) button (link). This possible with WP_Session_Tokens
class:
$manager = \WP_Session_Tokens::get_instance( $user_id );
$manager->destroy_all();
And even if user currently authorised and some pages from /wp-admin/
opened they will be force log out because we already drop sessions (immediately).
Source code: https://wordpress.org/plugins/mark-user-as-spammer/