Created
July 3, 2018 20:06
-
-
Save stephenscaff/eaebcf7a507e47abd47d552f356b546f to your computer and use it in GitHub Desktop.
Prevent Concurrent Sessions in Wordpress, leveraging WP_Session_Tokens and wp_destroy_other_sessions() / wp_destroy_current_sessions().
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* No Current Sessions | |
* Simple class to prevent concurrent user sessions. | |
*/ | |
class NoConcurrentSessions { | |
function __construct() { | |
add_action( 'init', array( $this, 'only_one' ) ); | |
} | |
/** | |
* Helper to determine if current users | |
* has concurrent sessions | |
* | |
* @return boolean | |
*/ | |
function has_current_session() { | |
return ( is_user_logged_in() && count( wp_get_all_sessions() ) > 1 ); | |
} | |
/** | |
* Helper to get current user's session array | |
* | |
* @return array | |
*/ | |
function get_current_session() { | |
$sessions = WP_Session_Tokens::get_instance( get_current_user_id() ); | |
return $sessions->get( wp_get_session_token() ); | |
} | |
/** | |
* Logic to prevent concurrent user sessions/logins | |
*/ | |
function only_one() { | |
if ( ! $this->has_current_session() ) { | |
return; | |
} | |
$user_id = get_current_user_id(); | |
$newest = max( wp_list_pluck( wp_get_all_sessions(), 'login' ) ); | |
$session = $this->get_current_session(); | |
if ( $session['login'] === $newest ) { | |
wp_destroy_other_sessions(); | |
} else { | |
wp_destroy_current_session(); | |
} | |
} | |
} | |
new NoConcurrentSessions(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment