Skip to content

Instantly share code, notes, and snippets.

@fjarrett
Last active September 3, 2021 20:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fjarrett/0fa79273bd879f7ab6b3 to your computer and use it in GitHub Desktop.
Save fjarrett/0fa79273bd879f7ab6b3 to your computer and use it in GitHub Desktop.
Prevent Concurrent Logins
<?php
/**
* Detect if the current user has concurrent sessions
*
* @return bool
*/
function pcl_user_has_concurrent_sessions() {
return ( is_user_logged_in() && count( wp_get_all_sessions() ) > 1 );
}
/**
* Get the user's current session array
*
* @return array
*/
function pcl_get_current_session() {
$sessions = WP_Session_Tokens::get_instance( get_current_user_id() );
return $sessions->get( wp_get_session_token() );
}
/**
* Only allow one session per user
*
* If the current user's session has been taken over by a newer
* session then we will destroy their session automattically and
* they will have to login again to continue.
*
* @action init
*
* @return void
*/
function pcl_disallow_account_sharing() {
if ( ! pcl_user_has_concurrent_sessions() ) {
return;
}
$newest = max( wp_list_pluck( wp_get_all_sessions(), 'login' ) );
$session = pcl_get_current_session();
if ( $session['login'] === $newest ) {
wp_destroy_other_sessions();
} else {
wp_destroy_current_session();
}
}
add_action( 'init', 'pcl_disallow_account_sharing' );
@fjarrett
Copy link
Author

This is also available as a plugin https://github.com/fjarrett/prevent-concurrent-logins

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment