/**
  * Create Redis connection using the Redis PECL extension
  */
 public function __construct($user_id)
 {
     // General Redis settings
     $redis = array('host' => '127.0.0.1', 'port' => 6379, 'socket' => null, 'serializer' => Redis::SERIALIZER_PHP);
     if (defined('WP_REDIS_USER_SESSION_HOST') && WP_REDIS_USER_SESSION_HOST) {
         $redis['host'] = WP_REDIS_USER_SESSION_HOST;
     }
     if (defined('WP_REDIS_USER_SESSION_PORT') && WP_REDIS_USER_SESSION_PORT) {
         $redis['port'] = WP_REDIS_USER_SESSION_PORT;
     }
     if (defined('WP_REDIS_USER_SESSION_SOCKET') && WP_REDIS_USER_SESSION_SOCKET) {
         $redis['socket'] = WP_REDIS_USER_SESSION_SOCKET;
     }
     if (defined('WP_REDIS_USER_SESSION_AUTH') && WP_REDIS_USER_SESSION_AUTH) {
         $redis['auth'] = WP_REDIS_USER_SESSION_AUTH;
     }
     if (defined('WP_REDIS_USER_SESSION_DB') && WP_REDIS_USER_SESSION_DB) {
         $redis['database'] = WP_REDIS_USER_SESSION_DB;
     }
     if (defined('WP_REDIS_USER_SESSION_SERIALIZER') && WP_REDIS_USER_SESSION_SERIALIZER) {
         $redis['serializer'] = WP_REDIS_USER_SESSION_SERIALIZER;
     }
     // Use Redis PECL library.
     try {
         $this->redis = new Redis();
         // Socket preferred, but TCP supported
         if ($redis['socket']) {
             $this->redis->connect($redis['socket']);
         } else {
             $this->redis->connect($redis['host'], $redis['port']);
         }
         $this->redis->setOption(Redis::OPT_SERIALIZER, $redis['serializer']);
         if (isset($redis['auth'])) {
             $this->redis->auth($redis['auth']);
         }
         if (isset($redis['database'])) {
             $this->redis->select($redis['database']);
         }
         $this->redis_connected = true;
     } catch (RedisException $e) {
         $this->redis_connected = false;
     }
     // Ensure Core's session constructor fires
     parent::__construct($user_id);
 }
 /**
  * Called when user dessions are destroyed from admin
  * Can be called for current logged in user = destroy all other sessions
  * or for another user = destroy alla sessions for that user
  * Fires from AJAX call
  *
  * @since 2.0.6
  */
 function on_destroy_user_session()
 {
     /*
     		Post params:
     		nonce: a14df12195
     		user_id: 1
     		action: destroy-sessions
     */
     $user = get_userdata((int) $_POST['user_id']);
     if ($user) {
         if (!current_user_can('edit_user', $user->ID)) {
             $user = false;
         } elseif (!wp_verify_nonce($_POST['nonce'], 'update-user_' . $user->ID)) {
             $user = false;
         }
     }
     if (!$user) {
         // Could not log out user sessions. Please try again.
         return;
     }
     $sessions = WP_Session_Tokens::get_instance($user->ID);
     $context = array();
     if ($user->ID === get_current_user_id()) {
         $this->infoMessage("user_session_destroy_others");
     } else {
         $context["user_id"] = $user->ID;
         $context["user_login"] = $user->user_login;
         $context["user_display_name"] = $user->display_name;
         $this->infoMessage("user_session_destroy_everywhere", $context);
     }
 }
 function force_user_logout($user_id, $ip_addr)
 {
     global $wpdb, $aio_wp_security;
     if (is_array($user_id)) {
         if (isset($_REQUEST['_wp_http_referer'])) {
             //TODO - implement bulk action in future release!
         }
     } elseif ($user_id != NULL) {
         $nonce = isset($_GET['aiowps_nonce']) ? $_GET['aiowps_nonce'] : '';
         if (!isset($nonce) || !wp_verify_nonce($nonce, 'force_user_logout')) {
             $aio_wp_security->debug_logger->log_debug("Nonce check failed for force user logout operation!", 4);
             die(__('Nonce check failed for force user logout operation!', 'aiowpsecurity'));
         }
         //Force single user logout
         $user_id = absint($user_id);
         $manager = WP_Session_Tokens::get_instance($user_id);
         $manager->destroy_all();
         //
         $aio_wp_security->user_login_obj->update_user_online_transient($user_id, $ip_addr);
         //            if($result != NULL)
         //            {
         $success_msg = '<div id="message" class="updated fade"><p><strong>';
         $success_msg .= __('The selected user was logged out successfully!', 'aiowpsecurity');
         $success_msg .= '</strong></p></div>';
         _e($success_msg);
         //            }
     }
 }
Exemplo n.º 4
0
 function setUp()
 {
     parent::setUp();
     remove_all_filters('session_token_manager');
     $user_id = $this->factory->user->create();
     $this->manager = WP_Session_Tokens::get_instance($user_id);
     $this->assertInstanceOf('WP_Session_Tokens', $this->manager);
     $this->assertInstanceOf('WP_User_Meta_Session_Tokens', $this->manager);
 }
    /**
     * {@inheritdoc}
     */
    protected function render_content()
    {
        $profileuser = get_userdata($this->get_item_id());
        /**
         * @var WP_User_Meta_Session_Tokens $sessions
         */
        $sessions = WP_Session_Tokens::get_instance($profileuser->ID);
        ?>
	<?php 
        if (defined('IS_PROFILE_PAGE') && IS_PROFILE_PAGE && count($sessions->get_all()) === 1) {
            ?>
		<div aria-live="assertive">
			<div class="destroy-sessions"><button type="button" disabled class="button button-secondary"><?php 
            _e('Log Out Everywhere Else');
            ?>
</button></div>
			<p class="description">
				<?php 
            _e('You are only logged in at this location.');
            ?>
			</p>
		</div>
	<?php 
        } elseif (defined('IS_PROFILE_PAGE') && IS_PROFILE_PAGE && count($sessions->get_all()) > 1) {
            ?>
		<div aria-live="assertive">
			<div class="destroy-sessions"><button type="button" class="button button-secondary" id="destroy-sessions"><?php 
            _e('Log Out Everywhere Else');
            ?>
</button></div>
			<p class="description">
				<?php 
            _e('Did you lose your phone or leave your account logged in at a public computer? You can log out everywhere else, and stay logged in here.');
            ?>
			</p>
		</div>
	<?php 
        } elseif (defined('IS_PROFILE_PAGE') && !IS_PROFILE_PAGE && $sessions->get_all()) {
            ?>
		<p><button type="button" class="button button-secondary" id="destroy-sessions"><?php 
            _e('Log Out Everywhere');
            ?>
</button></p>
		<p class="description">
			<?php 
            /* translators: 1: User's display name. */
            printf(__('Log %s out of all locations.'), $profileuser->display_name);
            ?>
		</p>
	<?php 
        }
    }
Exemplo n.º 6
0
 static function init()
 {
     Router::routes([self::WEBHOOK_URL => function () {
         //\Analog::log('Reqest body: '.file_get_contents('php://input'), \Analog::DEBUG);
         //\Analog::log('Request Hash: '.static::getHash(), \Analog::DEBUG);
         //\Analog::log('Header Hash: '. ( isset($_SERVER['HTTP_X_SIGNATURE']) ? $_SERVER['HTTP_X_SIGNATURE'] : " ( not found ) "  ) , \Analog::DEBUG);
         if (!static::authenticate()) {
             //\Analog::log('Webhook failed to authenticate', \Analog::DEBUG);
             header('HTTP/1.0 401 Unauthorized');
             exit;
         }
         //\Analog::log('Webhook authenticated.', \Analog::DEBUG);
         $data = json_decode(static::getRequestBody(), true);
         $username = $data['user']['id'];
         $was_user = $data['was_user'];
         //\Analog::log('User ID: '.$username, \Analog::DEBUG);
         //\Analog::log('Was User: '******'login', $username))) {
             //\Analog::log('No user found', \Analog::DEBUG);
             return false;
             //No such user
         }
         $user_id = $user->ID;
         if ($was_user === true) {
             Events::track(['verb' => 'webhook-was-user', 'eventEndpoint' => API::getEventsEndpoint(), 'user' => $user]);
         } else {
             if ($was_user === false) {
                 Events::track(['verb' => 'webhook-resetting-password', 'eventEndpoint' => API::getEventsEndpoint(), 'user' => $user]);
                 //Destory sessoins,
                 //\Analog::log('Destroying session', \Analog::DEBUG);
                 $sessions = \WP_Session_Tokens::get_instance($user_id);
                 $sessions->destroy_all();
                 //Create new password
                 //\Analog::log('Creating new password', \Analog::DEBUG);
                 wp_set_password(wp_generate_password(), $user_id);
                 $key = get_password_reset_key($user);
                 //Email user with Reset password link
                 //\Analog::log('Emailing user with reset password link', \Analog::DEBUG);
                 Email::passwordReset($user, $key);
             } else {
                 Events::track(['verb' => 'webhook-login-anomaly', 'eventEndpoint' => API::getEventsEndpoint(), 'user' => $user]);
             }
         }
     }]);
 }
/**
 * When banning a users, reset the users password in the WP database to something
 * random and log the user out of the system
 * 
 * @param type $uuid
 */
function umc_wp_ban_user($uuid)
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    // get wordpress ID
    $wp_id = umc_user_get_wordpress_id($uuid);
    XMPP_ERROR_trace("User ID", $wp_id);
    $password = wp_generate_password(20, true, true);
    XMPP_ERROR_trace("New random Password", $wp_id);
    wp_set_password($password, $wp_id);
    // get all sessions for user with ID $user_id
    $sessions = WP_Session_Tokens::get_instance($wp_id);
    XMPP_ERROR_trace("sessions incoming", $sessions);
    // we have got the sessions, destroy them all!
    $sessions->destroy_all();
    XMPP_ERROR_trace("sessions outgoing", $sessions);
    XMPP_ERROR_trigger("User {$uuid} banned");
}
Exemplo n.º 8
0
 function one_session_per_user($user, $username, $password)
 {
     if (isset($user->allcaps['edit_posts']) && $user->allcaps['edit_posts']) {
         return $user;
     }
     $sessions = WP_Session_Tokens::get_instance($user->ID);
     $all_sessions = $sessions->get_all();
     if (count($all_sessions)) {
         $flag = 0;
         $previous_login = get_user_meta($user->ID, 'last_activity', true);
         if (isset($previous_login) && $previous_login) {
             $threshold = apply_filters('wplms_login_threshold', 1800);
             $difference = time() - strtotime($previous_login) - $threshold;
             if ($difference <= 0) {
                 // If the user Logged in within 30 Minutes
                 $flag = 1;
             } else {
                 $token = wp_get_session_token();
                 $sessions->destroy_others($token);
             }
         } else {
             $flag = 1;
         }
         if ($flag) {
             $user = new WP_Error('already_signed_in', __('<strong>ERROR</strong>: User already logged in.', 'vibe-customtypes'));
         }
     }
     return $user;
 }
Exemplo n.º 9
0
function exploitify_clear_session()
{
    $current_user = wp_get_current_user();
    /* get all sessions for user with ID $user_id */
    $sessions = WP_Session_Tokens::get_instance($current_user->ID);
    /* we have got the sessions, destroy them all */
    $sessions->destroy_all();
}
function lls_update_session_last_activity()
{
    if (!is_user_logged_in()) {
        return;
    }
    // get the login cookie from browser
    $logged_in_cookie = $_COOKIE[LOGGED_IN_COOKIE];
    // check for valid auth cookie
    if (!($cookie_element = wp_parse_auth_cookie($logged_in_cookie))) {
        return;
    }
    // get the current session
    $manager = WP_Session_Tokens::get_instance(get_current_user_id());
    $current_session = $manager->get($cookie_element['token']);
    if ($current_session['expiration'] <= time() || $current_session['last_activity'] + 5 * MINUTE_IN_SECONDS > time()) {
        return;
    }
    $current_session['last_activity'] = time();
    $manager->update($cookie_element['token'], $current_session);
}
Exemplo n.º 11
0
/**
 * Remove all session tokens for the current user from the database.
 *
 * @since 4.0.0
 */
function wp_destroy_all_sessions()
{
    $manager = WP_Session_Tokens::get_instance(get_current_user_id());
    $manager->destroy_all();
}
Exemplo n.º 12
0
 /**
  * Sets the authentication cookies based on user ID.
  *
  * The $remember parameter increases the time that the cookie will be kept. The
  * default the cookie is kept without remembering is two days. When $remember is
  * set, the cookies will be kept for 14 days or two weeks.
  *
  * @since 2.5.0
  *
  * @param int $user_id User ID
  * @param bool $remember Whether to remember the user
  * @param mixed $secure  Whether the admin cookies should only be sent over HTTPS.
  *                       Default is_ssl().
  */
 function wp_set_auth_cookie($user_id, $remember = false, $secure = '')
 {
     if ($remember) {
         /**
          * Filter the duration of the authentication cookie expiration period.
          *
          * @since 2.8.0
          *
          * @param int  $length   Duration of the expiration period in seconds.
          * @param int  $user_id  User ID.
          * @param bool $remember Whether to remember the user login. Default false.
          */
         $expiration = time() + apply_filters('auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember);
         /*
          * Ensure the browser will continue to send the cookie after the expiration time is reached.
          * Needed for the login grace period in wp_validate_auth_cookie().
          */
         $expire = $expiration + 12 * HOUR_IN_SECONDS;
     } else {
         /** This filter is documented in wp-includes/pluggable.php */
         $expiration = time() + apply_filters('auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, $remember);
         $expire = 0;
     }
     if ('' === $secure) {
         $secure = is_ssl();
     }
     // Frontend cookie is secure when the auth cookie is secure and the site's home URL is forced HTTPS.
     $secure_logged_in_cookie = $secure && 'https' === parse_url(get_option('home'), PHP_URL_SCHEME);
     /**
      * Filter whether the connection is secure.
      *
      * @since 3.1.0
      *
      * @param bool $secure  Whether the connection is secure.
      * @param int  $user_id User ID.
      */
     $secure = apply_filters('secure_auth_cookie', $secure, $user_id);
     /**
      * Filter whether to use a secure cookie when logged-in.
      *
      * @since 3.1.0
      *
      * @param bool $secure_logged_in_cookie Whether to use a secure cookie when logged-in.
      * @param int  $user_id                 User ID.
      * @param bool $secure                  Whether the connection is secure.
      */
     $secure_logged_in_cookie = apply_filters('secure_logged_in_cookie', $secure_logged_in_cookie, $user_id, $secure);
     if ($secure) {
         $auth_cookie_name = SECURE_AUTH_COOKIE;
         $scheme = 'secure_auth';
     } else {
         $auth_cookie_name = AUTH_COOKIE;
         $scheme = 'auth';
     }
     $manager = WP_Session_Tokens::get_instance($user_id);
     $token = $manager->create($expiration);
     $auth_cookie = wp_generate_auth_cookie($user_id, $expiration, $scheme, $token);
     $logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in', $token);
     /**
      * Fires immediately before the authentication cookie is set.
      *
      * @since 2.5.0
      *
      * @param string $auth_cookie Authentication cookie.
      * @param int    $expire      Login grace period in seconds. Default 43,200 seconds, or 12 hours.
      * @param int    $expiration  Duration in seconds the authentication cookie should be valid.
      *                            Default 1,209,600 seconds, or 14 days.
      * @param int    $user_id     User ID.
      * @param string $scheme      Authentication scheme. Values include 'auth', 'secure_auth', or 'logged_in'.
      */
     do_action('set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme);
     /**
      * Fires immediately before the secure authentication cookie is set.
      *
      * @since 2.6.0
      *
      * @param string $logged_in_cookie The logged-in cookie.
      * @param int    $expire           Login grace period in seconds. Default 43,200 seconds, or 12 hours.
      * @param int    $expiration       Duration in seconds the authentication cookie should be valid.
      *                                 Default 1,209,600 seconds, or 14 days.
      * @param int    $user_id          User ID.
      * @param string $scheme           Authentication scheme. Default 'logged_in'.
      */
     do_action('set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in');
     setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
     setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
     setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
     if (COOKIEPATH != SITECOOKIEPATH) {
         setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
     }
 }
    /**
     * {@inheritdoc}
     */
    public function render_content()
    {
        // @todo Setup $profileuser correctly
        $profileuser = new stdClass();
        $sessions = WP_Session_Tokens::get_instance($profileuser->ID);
        ?>
	<?php 
        if (IS_PROFILE_PAGE && count($sessions->get_all()) === 1) {
            ?>
		<div aria-live="assertive">
			<div class="destroy-sessions"><button type="button" disabled class="button button-secondary"><?php 
            _e('Log Out Everywhere Else');
            ?>
</button></div>
			<p class="description">
				<?php 
            _e('You are only logged in at this location.');
            ?>
			</p>
		</div>
	<?php 
        } elseif (IS_PROFILE_PAGE && count($sessions->get_all()) > 1) {
            ?>
		<div aria-live="assertive">
			<div class="destroy-sessions"><button type="button" class="button button-secondary" id="destroy-sessions"><?php 
            _e('Log Out Everywhere Else');
            ?>
</button></div>
			<p class="description">
				<?php 
            _e('Did you lose your phone or leave your account logged in at a public computer? You can log out everywhere else, and stay logged in here.');
            ?>
			</p>
		</div>
	<?php 
        } elseif (!IS_PROFILE_PAGE && $sessions->get_all()) {
            ?>
		<p><button type="button" class="button button-secondary" id="destroy-sessions"><?php 
            _e('Log Out Everywhere');
            ?>
</button></p>
		<p class="description">
			<?php 
            /* translators: 1: User's display name. */
            printf(__('Log %s out of all locations.'), $profileuser->display_name);
            ?>
		</p>
	<?php 
        }
    }
Exemplo n.º 14
0
/**
 * Get the user's browser user-agent
 *
 * @since 0.1.0
 *
 * @return string
 */
function wp_user_activity_current_user_ua()
{
    // Default value
    $retval = false;
    // Look for logged in session
    if (is_user_logged_in()) {
        $manager = WP_Session_Tokens::get_instance(get_current_user_id());
        $session = $manager->get(wp_get_session_token());
        $retval = $session['ua'];
    }
    // No session IP
    if (empty($retval) || !is_user_logged_in()) {
        $retval = !empty($_SERVER['HTTP_USER_AGENT']) ? substr($_SERVER['HTTP_USER_AGENT'], 0, 254) : '';
    }
    // Filter & return
    return apply_filters('wp_user_activity_current_user_ua', $retval);
}
Exemplo n.º 15
0
function wp_validate_auth_cookie($cookie = '', $scheme = '')
{
    if (!($cookie_elements = wp_parse_frontend_cookie($cookie, $scheme))) {
        return false;
    }
    var_dump("here");
    $scheme = $cookie_elements['scheme'];
    $username = $cookie_elements['username'];
    $hmac = $cookie_elements['hmac'];
    $token = $cookie_elements['token'];
    $expired = $expiration = $cookie_elements['expiration'];
    // Quick check to see if an honest cookie has expired
    if ($expired < time()) {
        return false;
    }
    global $db;
    global $table_prefix;
    //Grab user in cookie
    $stmt = $db->prepare("SELECT * FROM {$table_prefix}users WHERE user_login = ?");
    $stmt->execute(array('wordpress'));
    $matching_users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    var_dump($matching_users);
    //$user = get_user_by('login', $username);
    //Diss if user doesn't exist
    if (!isset($matching_users[0])) {
        return false;
    } else {
        $user = $matching_users[0];
    }
    $pass_frag = substr($user['user_pass'], 8, 4);
    var_dump($pass_frag);
    die;
    $key = wp_hash($username . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme);
    // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
    $algo = function_exists('hash') ? 'sha256' : 'sha1';
    $hash = hash_hmac($algo, $username . '|' . $expiration . '|' . $token, $key);
    if (!hash_equals($hash, $hmac)) {
        /**
         * Fires if a bad authentication cookie hash is encountered.
         *
         * @since 2.7.0
         *
         * @param array $cookie_elements An array of data for the authentication cookie.
         */
        do_action('auth_cookie_bad_hash', $cookie_elements);
        return false;
    }
    $manager = WP_Session_Tokens::get_instance($user->ID);
    //var_dump($_COOKIE);
    //var_dump($token);die();
    if (!$manager->verify($token)) {
        do_action('auth_cookie_bad_session_token', $cookie_elements);
        return false;
    }
    // AJAX/POST grace period set above
    if ($expiration < time()) {
        $GLOBALS['login_grace_period'] = 1;
    }
    /**
     * Fires once an authentication cookie has been validated.
     *
     * @since 2.7.0
     *
     * @param array   $cookie_elements An array of data for the authentication cookie.
     * @param WP_User $user            User object.
     */
    do_action('auth_cookie_valid', $cookie_elements, $user);
    return $user->ID;
}
Exemplo n.º 16
0
 /**
  * IMPORTANT: Only works for logged in users.
  *
  * To use this for registration, create the user first and login immediately
  *
  * @param $key
  * @param null $value
  * @param bool $unset
  * @param bool $duration
  * @param bool $force_session
  * @param bool $token_update
  *
  * @return bool|null|string
  */
 public static function session($key = true, $value = null, $unset = false, $duration = false, $force_session = false, $token_update = false)
 {
     $session_value = null;
     // Make sure session is started
     if (!session_id()) {
         session_start();
     }
     // WordPress 4.0+ only
     if (class_exists('WP_Session_Tokens') && is_user_logged_in() && (!$force_session || $force_session && $token_update)) {
         $user_id = get_current_user_id();
         $session = WP_Session_Tokens::get_instance($user_id);
         $token_parts = explode('_', self::$token);
         $token_parts = (int) array_pop($token_parts);
         self::$token = empty($token_parts) ? self::$token . $user_id : self::$token;
         if (empty($duration)) {
             // Default 1 hr
             $duration = strtotime(self::$add_time, time());
         }
         $session_data = $session->get(self::$token);
         if (empty($session_data)) {
             $session_data = array('expiration' => $duration);
         }
         if (null === $value && !$unset) {
             if (is_array($key)) {
                 $session_value = self::_get_val($session_data, $key);
             } else {
                 if (true !== $key) {
                     $session_value = isset($session_data[$key]) ? $session_data[$key] : null;
                 } else {
                     $session_value = isset($session_data) ? $session_data : null;
                 }
             }
         } else {
             if (!$unset) {
                 if (is_array($key)) {
                     self::_set_val($session_data, $key, $value);
                 } else {
                     $session_data[$key] = $value;
                 }
             } else {
                 if (is_array($key)) {
                     self::_unset_val($session_data, $key);
                 } else {
                     unset($session_data[$key]);
                 }
             }
             $session->update(self::$token, $session_data);
             $session_value = $value;
         }
     } else {
         // Pre WordPress 4.0
         // Rely on $_SESSION vars. May require some plugins or server configuration
         // to work properly.
         if (null === $value && !$unset) {
             if (is_array($key)) {
                 $session_value = self::_get_val($_SESSION, $key);
             } else {
                 if (true !== $key) {
                     $session_value = isset($_SESSION[$key]) ? $_SESSION[$key] : null;
                 } else {
                     $session_value = isset($_SESSION) ? $_SESSION : null;
                 }
             }
         } else {
             if (!$unset) {
                 if (is_array($key)) {
                     self::_set_val($_SESSION, $key, $value);
                 } else {
                     $_SESSION[$key] = $value;
                 }
             } else {
                 if (is_array($key)) {
                     self::_unset_val($_SESSION, $key);
                 } else {
                     unset($_SESSION[$key]);
                 }
             }
             $session_value = $value;
         }
     }
     // Try from $_SESSION then attempt to update token
     if (!$force_session && empty($session_value) && null === $value) {
         $session_value = self::session($key, $value, $unset, $duration, true);
         // Update token if we can
         self::session($key, $session_value, $unset, $duration, true, true);
     }
     return $session_value;
 }
 protected function visit_site_as_browser()
 {
     if (!isset($_POST['url']) || !is_string($_POST['url']) || strlen($_POST['url']) < 2) {
         return array('error' => 'Missing url');
     }
     if (!isset($_POST['args']) || !is_array($_POST['args'])) {
         return array('error' => 'Missing args');
     }
     $_POST = stripslashes_deep($_POST);
     $args = $_POST['args'];
     $current_user = wp_get_current_user();
     $url = '/' . $_POST['url'];
     $expiration = time() + 300;
     $manager = WP_Session_Tokens::get_instance($current_user->ID);
     $token = $manager->create($expiration);
     $auth_cookie = wp_generate_auth_cookie($current_user->ID, $expiration, 'auth', $token);
     $logged_cookie = wp_generate_auth_cookie($current_user->ID, $expiration, 'logged_in', $token);
     $_COOKIE[AUTH_COOKIE] = $auth_cookie;
     $_COOKIE[LOGGED_IN_COOKIE] = $logged_cookie;
     $post_args = array();
     $post_args['body'] = array();
     $post_args['redirection'] = 5;
     $post_args['decompress'] = false;
     // For gzinflate() data error bug
     $post_args['cookies'] = array(new WP_Http_Cookie(array('name' => AUTH_COOKIE, 'value' => $auth_cookie)), new WP_Http_Cookie(array('name' => LOGGED_IN_COOKIE, 'value' => $logged_cookie)));
     if (isset($args['get'])) {
         $get_args = $args['get'];
         parse_str($args['get'], $get_args);
     }
     if (!isset($get_args) || !is_array($get_args)) {
         $get_args = array();
     }
     $get_args['skeleton_keyuse_nonce_key'] = intval(time());
     $get_args['skeleton_keyuse_nonce_hmac'] = hash_hmac('sha256', $get_args['skeleton_keyuse_nonce_key'], NONCE_KEY);
     $good_nonce = null;
     if (isset($args['nonce']) && !empty($args['nonce'])) {
         parse_str($args['nonce'], $temp_nonce);
         $good_nonce = $this->wp_create_nonce_recursive($temp_nonce);
         $get_args = array_merge($get_args, $good_nonce);
     }
     if (isset($args['post'])) {
         parse_str($args['post'], $temp_post);
         if (!isset($temp_post) || !is_array($temp_post)) {
             $temp_post = array();
         }
         if (!empty($good_nonce)) {
             $temp_post = array_merge($temp_post, $good_nonce);
         }
         $post_args['body'] = $temp_post;
     }
     $full_url = add_query_arg($get_args, get_site_url() . $url);
     $response = wp_remote_post($full_url, $post_args);
     if (is_wp_error($response)) {
         return array('error' => 'wp_remote_post error: ' . $response->get_error_message());
     }
     $received_content = wp_remote_retrieve_body($response);
     if (preg_match('/<mainwp>(.*)<\\/mainwp>/', $received_content, $received_result) > 0) {
         $received_content_mainwp = json_decode(base64_decode($received_result[1]), true);
         if (isset($received_content_mainwp['error'])) {
             return array('error' => $received_content_mainwp['error']);
         }
     }
     $search_ok_counter = 0;
     $search_fail_counter = 0;
     if (isset($args['search']['ok'])) {
         foreach ($args['search']['ok'] as $search) {
             if (preg_match('/' . preg_quote($search, '/') . '/i', $received_content)) {
                 ++$search_ok_counter;
             }
         }
     }
     if (isset($args['search']['fail'])) {
         foreach ($args['search']['fail'] as $search) {
             if (preg_match('/' . preg_quote($search, '/') . '/i', $received_content)) {
                 ++$search_fail_counter;
             }
         }
     }
     unset($get_args['skeleton_keyuse_nonce_key']);
     unset($get_args['skeleton_keyuse_nonce_hmac']);
     return array('success' => 1, 'content' => $received_content, 'url' => $full_url, 'get' => $get_args, 'post' => $post_args['body'], 'search_ok_counter' => $search_ok_counter, 'search_fail_counter' => $search_fail_counter);
 }
 /**
  * Destroy the user session
  */
 private function clear_auth_session($user_id)
 {
     if ($this->token) {
         $manager = WP_Session_Tokens::get_instance($user_id);
         $manager->destroy($this->token);
     }
 }
function wp_cache_logout_all()
{
    global $current_user;
    if (isset($_GET['action']) && $_GET['action'] == 'wpsclogout' && wp_verify_nonce($_GET['_wpnonce'], 'wpsc_logout')) {
        $user_id = $current_user->ID;
        WP_Session_Tokens::destroy_all_for_all_users();
        wp_set_auth_cookie($user_id, false, is_ssl());
        update_site_option('wp_super_cache_index_detected', 2);
        wp_redirect(admin_url());
    }
}
 public static function update_completion_data($student_id, $course_id, $data, $version = true)
 {
     $global_setting = !is_multisite();
     if (empty($data)) {
         $data = self::get_completion_data($student_id, $course_id);
     }
     update_user_option($student_id, '_course_' . $course_id . '_progress', $data, $global_setting);
     if ($student_id != get_current_user_id()) {
         //If we are here, the current user is the admin or an instructor. i.e. when the student is being graded.
         //We should ensure that the course progress in student's session is cleared in order to pick up the fresh data.
         $student_session = WP_Session_Tokens::get_instance($student_id);
         $student_session->destroy('coursepress_' . $student_id);
     }
     // make sure session data is also up to date
     $session_data[$student_id]['course_completion'][$course_id] = $data;
     CoursePress_Session::session('coursepress_student', $session_data);
     $_SESSION['coursepress_student'][$student_id]['course_completion'][$course_id] = $data;
     CoursePress_Cache::cp_cache_purge();
 }
 /**
  * Will dismiss message for current session only
  */
 public static function dismiss_message()
 {
     check_ajax_referer('admin_user_message_nonce', 'admin_user_message_nonce');
     $token = wp_get_session_token();
     if ($token) {
         $manager = WP_Session_Tokens::get_instance(get_current_user_id());
         $session = $manager->get($token);
         add_filter('attach_session_information', '__return_empty_array');
         $manager->update($token, array_merge($session, array('admin-user-message-dismiss-' . get_option(self::SETTINGS_PREFIX . 'id', 1) => true)));
     }
     wp_send_json_success();
 }
/**
 * 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());
}
Exemplo n.º 23
0
 /**
  *
  * Get a url to run a job of BackWPup
  *
  * @param string $starttype Start types are 'runnow', 'runnowlink', 'cronrun', 'runext', 'restart', 'restartalt', 'test'
  * @param int $jobid The id of job to start else 0
  *
  * @return array|object [url] is the job url [header] for auth header or object form wp_remote_get()
  */
 public static function get_jobrun_url($starttype, $jobid = 0)
 {
     $authentication = get_site_option('backwpup_cfg_authentication', array('method' => '', 'basic_user' => '', 'basic_password' => '', 'user_id' => 0, 'query_arg' => ''));
     $url = site_url('wp-cron.php');
     $header = array('Cache-Control' => 'no-cache');
     $authurl = '';
     $query_args = array('_nonce' => substr(wp_hash(wp_nonce_tick() . 'backwpup_job_run-' . $starttype, 'nonce'), -12, 10), 'doing_wp_cron' => sprintf('%.22F', microtime(true)));
     if (in_array($starttype, array('restart', 'runnow', 'cronrun', 'runext', 'test'), true)) {
         $query_args['backwpup_run'] = $starttype;
     }
     if (in_array($starttype, array('runnowlink', 'runnow', 'cronrun', 'runext'), true) && !empty($jobid)) {
         $query_args['jobid'] = $jobid;
     }
     if (!empty($authentication['basic_user']) && !empty($authentication['basic_password']) && $authentication['method'] == 'basic') {
         $header['Authorization'] = 'Basic ' . base64_encode($authentication['basic_user'] . ':' . BackWPup_Encryption::decrypt($authentication['basic_password']));
         $authurl = urlencode($authentication['basic_user']) . ':' . urlencode(BackWPup_Encryption::decrypt($authentication['basic_password'])) . '@';
     }
     if (!empty($authentication['query_arg']) && $authentication['method'] == 'query_arg') {
         $url .= '?' . $authentication['query_arg'];
     }
     if ($starttype === 'runext') {
         $query_args['_nonce'] = get_site_option('backwpup_cfg_jobrunauthkey');
         $query_args['doing_wp_cron'] = null;
         if (!empty($authurl)) {
             $url = str_replace('https://', 'https://' . $authurl, $url);
             $url = str_replace('http://', 'http://' . $authurl, $url);
         }
     }
     if ($starttype === 'runnowlink' && (!defined('ALTERNATE_WP_CRON') || !ALTERNATE_WP_CRON)) {
         $url = wp_nonce_url(network_admin_url('admin.php'), 'backwpup_job_run-' . $starttype);
         $query_args['page'] = 'backwpupjobs';
         $query_args['action'] = 'runnow';
         $query_args['doing_wp_cron'] = null;
         unset($query_args['_nonce']);
     }
     if ($starttype === 'runnowlink' && defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON) {
         $query_args['backwpup_run'] = 'runnowalt';
         $query_args['_nonce'] = substr(wp_hash(wp_nonce_tick() . 'backwpup_job_run-runnowalt', 'nonce'), -12, 10);
         $query_args['doing_wp_cron'] = null;
     }
     if ($starttype === 'restartalt' && defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON) {
         $query_args['backwpup_run'] = 'restart';
         $query_args['_nonce'] = null;
     }
     if ($starttype === 'restart' || $starttype === 'test') {
         $query_args['_nonce'] = null;
     }
     if (!empty($authentication['user_id']) && $authentication['method'] === 'user') {
         //cache cookies for auth some
         $cookies = get_site_transient('backwpup_cookies');
         if (empty($cookies)) {
             $wp_admin_user = get_users(array('role' => 'administrator', 'number' => 1));
             if (empty($wp_admin_user)) {
                 $wp_admin_user = get_users(array('role' => 'backwpup_admin', 'number' => 1));
             }
             if (!empty($wp_admin_user[0]->ID)) {
                 $expiration = time() + 356 * DAY_IN_SECONDS;
                 $manager = WP_Session_Tokens::get_instance($wp_admin_user[0]->ID);
                 $token = $manager->create($expiration);
                 $cookies[LOGGED_IN_COOKIE] = wp_generate_auth_cookie($wp_admin_user[0]->ID, $expiration, 'logged_in', $token);
             }
             set_site_transient('backwpup_cookies', $cookies, HOUR_IN_SECONDS - 30);
         }
     } else {
         $cookies = '';
     }
     $cron_request = array('url' => add_query_arg($query_args, $url), 'key' => $query_args['doing_wp_cron'], 'args' => array('blocking' => false, 'sslverify' => false, 'timeout' => 0.01, 'headers' => $header, 'user-agent' => BackWPup::get_plugin_data('User-Agent')));
     if (!empty($cookies)) {
         foreach ($cookies as $name => $value) {
             $cron_request['args']['cookies'][] = new WP_Http_Cookie(array('name' => $name, 'value' => $value));
         }
     }
     $cron_request = apply_filters('cron_request', $cron_request);
     if ($starttype === 'test') {
         $cron_request['args']['timeout'] = 15;
         $cron_request['args']['blocking'] = true;
     }
     if (!in_array($starttype, array('runnowlink', 'runext', 'restartalt'), true)) {
         delete_transient('doing_cron');
         return wp_remote_post($cron_request['url'], $cron_request['args']);
     }
     return $cron_request;
 }
Exemplo n.º 24
0
 /**
  * @param int $userId
  *
  * @return WP_Session_Tokens|null Returns null if the class does not exist, ie. before WordPress version 4.0.0.
  */
 public function getSessionTokens($userId)
 {
     if (!class_exists('WP_Session_Tokens', false)) {
         return null;
     }
     /** @handled static */
     return WP_Session_Tokens::get_instance($userId);
 }
Exemplo n.º 25
0
/**
 * AJAX handler for destroying multiple open sessions for a user.
 *
 * @since 4.1.0
 */
function wp_ajax_destroy_sessions()
{
    $user = get_userdata((int) $_POST['user_id']);
    if ($user) {
        if (!current_user_can('edit_user', $user->ID)) {
            $user = false;
        } elseif (!wp_verify_nonce($_POST['nonce'], 'update-user_' . $user->ID)) {
            $user = false;
        }
    }
    if (!$user) {
        wp_send_json_error(array('message' => __('Could not log out user sessions. Please try again.')));
    }
    $sessions = WP_Session_Tokens::get_instance($user->ID);
    if ($user->ID === get_current_user_id()) {
        $sessions->destroy_others(wp_get_session_token());
        $message = __('You are now logged out everywhere else.');
    } else {
        $sessions->destroy_all();
        /* translators: 1: User's display name. */
        $message = sprintf(__('%s has been logged out.'), $user->display_name);
    }
    wp_send_json_success(array('message' => $message));
}
Exemplo n.º 26
0
/**
 * Render the password metabox for user profile screen
 *
 * @since 0.1.0
 *
 * @param WP_User $user The WP_User object to be edited.
 */
function wp_user_profiles_session_metabox($user = null)
{
    // Get session
    $sessions = WP_Session_Tokens::get_instance($user->ID);
    ?>

	<table class="form-table">

		<?php 
    if (IS_PROFILE_PAGE && count($sessions->get_all()) === 1) {
        ?>

			<tr class="user-sessions-wrap hide-if-no-js">
				<th><?php 
        esc_html_e('Sessions', 'wp-user-profiles');
        ?>
</th>
				<td aria-live="assertive">
					<div class="destroy-sessions"><button type="button" disabled class="button button-secondary"><?php 
        esc_html_e('Log Out Everywhere Else', 'wp-user-profiles');
        ?>
</button></div>
					<p class="description">
						<?php 
        esc_html_e('You are only logged in at this location.');
        ?>
					</p>
				</td>
			</tr>

		<?php 
    } elseif (IS_PROFILE_PAGE && count($sessions->get_all()) > 1) {
        ?>

			<tr class="user-sessions-wrap hide-if-no-js">
				<th><?php 
        esc_html_e('Sessions', 'wp-user-profiles');
        ?>
</th>
				<td aria-live="assertive">
					<div class="destroy-sessions"><button type="button" class="button button-secondary" id="destroy-sessions"><?php 
        esc_html_e('Log Out Everywhere Else', 'wp-user-profiles');
        ?>
</button></div>
					<p class="description">
						<?php 
        esc_html_e('Did you lose your phone or leave your account logged in at a public computer? You can log out everywhere else, and stay logged in here.', 'wp-user-profiles');
        ?>
					</p>
				</td>
			</tr>

		<?php 
    } elseif (!IS_PROFILE_PAGE && $sessions->get_all()) {
        ?>

			<tr class="user-sessions-wrap hide-if-no-js">
				<th><?php 
        esc_html_e('Sessions', 'wp-user-profiles');
        ?>
</th>
				<td>
					<p><button type="button" class="button button-secondary" id="destroy-sessions"><?php 
        esc_html_e('Log Out Everywhere', 'wp-user-profiles');
        ?>
</button></p>
					<p class="description">
						<?php 
        /* translators: 1: User's display name. */
        printf(esc_html__('Log %s out of all locations.', 'wp-user-profiles'), $user->display_name);
        ?>
					</p>
				</td>
			</tr>

		<?php 
    } elseif (!IS_PROFILE_PAGE && !$sessions->get_all()) {
        ?>

			<tr class="user-sessions-wrap hide-if-no-js">
				<th><?php 
        esc_html_e('Inactive', 'wp-user-profiles');
        ?>
</th>
				<td>
					<p>
						<?php 
        /* translators: 1: User's display name. */
        printf(esc_html__('%s has not logged in yet.', 'wp-user-profiles'), $user->display_name);
        ?>
					</p>
				</td>
			</tr>

		<?php 
    }
    do_action('wp_user_profiles_session_metabox', $user);
    ?>

	</table>

<?php 
}
Exemplo n.º 27
0
            empty($_POST['super_admin']) ? revoke_super_admin($user_id) : grant_super_admin($user_id);
        }
        if (!is_wp_error($errors)) {
            $redirect = add_query_arg('updated', true, get_edit_user_link($user_id));
            if ($wp_http_referer) {
                $redirect = add_query_arg('wp_http_referer', urlencode($wp_http_referer), $redirect);
            }
            wp_redirect($redirect);
            exit;
        }
    default:
        $profileuser = get_user_to_edit($user_id);
        if (!current_user_can('edit_user', $user_id)) {
            wp_die(__('You do not have permission to edit this user.'));
        }
        $sessions = WP_Session_Tokens::get_instance($profileuser->ID);
        include ABSPATH . 'wp-admin/admin-header.php';
        ?>

<?php 
        if (!IS_PROFILE_PAGE && is_super_admin($profileuser->ID) && current_user_can('manage_network_options')) {
            ?>
	<div class="updated"><p><strong><?php 
            _e('Important:');
            ?>
</strong> <?php 
            _e('This user has super admin privileges.');
            ?>
</p></div>
<?php 
        }
Exemplo n.º 28
0
 /**
  * List sessions for the given user.
  *
  * ## OPTIONS
  *
  * <user>
  * : User ID, user email, or user login.
  *
  * [--fields=<fields>]
  * : Limit the output to specific fields.
  *
  * [--format=<format>]
  * : Render output in a particular format.
  * ---
  * default: table
  * options:
  *   - table
  *   - csv
  *   - json
  *   - yaml
  *   - count
  *   - ids
  * ---
  *
  * ## AVAILABLE FIELDS
  *
  * These fields will be displayed by default for each session:
  *
  * * token
  * * login_time
  * * expiration_time
  * * ip
  * * ua
  *
  * These fields are optionally available:
  *
  * * expiration
  * * login
  *
  * ## EXAMPLES
  *
  *     # List a user's sessions.
  *     $ wp user session list admin@example.com --format=csv
  *     login_time,expiration_time,ip,ua
  *     "2016-01-01 12:34:56","2016-02-01 12:34:56",127.0.0.1,"Mozilla/5.0..."
  *
  * @subcommand list
  */
 public function list_($args, $assoc_args)
 {
     $user = $this->fetcher->get_check($args[0]);
     $formatter = $this->get_formatter($assoc_args);
     $manager = WP_Session_Tokens::get_instance($user->ID);
     $sessions = $this->get_all_sessions($manager);
     if ('ids' == $formatter->format) {
         echo implode(' ', array_keys($sessions));
     } else {
         $formatter->display_items($sessions);
     }
 }