Generates the user's session cookie.

@param int $UserID The unique id assigned to the user in the database.
@param boolean $Persist Should the user's session remain persistent across visits?
325776
public function SetIdentity($UserID, $Persist = FALSE) {
      if (is_null($UserID)) {
         $this->_ClearIdentity();
         return;
      }
      
      $this->UserID = $UserID;
      
      // If we're persisting, both the cookie and its payload expire in 30days
      $PayloadExpires = time();
      if ($Persist) {
         
         $PayloadExpires += (86400 * self::COOKIE_PERSIST_DAYS);
         $CookieExpires = $PayloadExpires;
         
      // Otherwise the payload expires in 2 days and the cookie expires on borwser restart
      } else {
         // Note: $CookieExpires = 0 causes cookie to die when browser closes.
         
         $PayloadExpires += (86400 * self::COOKIE_SESSION_DAYS);
         $CookieExpires = 0;
      }

      // Create the cookie
      $KeyData = $UserID.'-'.$PayloadExpires;
      $this->_SetCookie($this->CookieName, $KeyData, array($UserID, $PayloadExpires), $CookieExpires);
      $this->SetVolatileMarker($UserID);
   }
1062018
public function deleteSession($user_id)
    {
        if (!isset($_SESSION['admin_sid'])) {
            return true;
        }
        $user_id = (int)$user_id;

        $sessions = new UsersSessionEntityRepository();
        $sessions->setWhereUserId($user_id);
        $sessions->setWhereSid($_SESSION['admin_sid']);
        $sessions->deleteObjectCollection();

        return true;
    }
794589
public function saveSession($user_id = null, $provider = [])
    {
        if (empty($user_id)) {
            $user_id = activeUser('id');
        }

        if (empty($user_id)) {
            $this->setError('Must specify which user ID\'s session to save.');
            return false;
        }

        $oUser = $this->oUserModel->getById($user_id);

        if (!$oUser) {
            $this->setError('Invalid User ID');
            return false;
        }

        // --------------------------------------------------------------------------

        if (!is_array($provider)) {

            $_provider = (array) $provider;
            $_provider = array_unique($_provider);
            $_provider = array_filter($_provider);

        } else {

            $_provider = $provider;
        }

        // --------------------------------------------------------------------------

        $_session     = $this->oHybridAuth->getSessionData();
        $_session     = unserialize($_session);
        $_save        = [];
        $_identifiers = [];

        //  Now we sort the session into individual providers
        foreach ($_session as $key => $value) {

            //  Get the bits
            list($hauth, $provider) = explode('.', $key, 3);

            if (!isset($_save[$provider])) {
                $_save[$provider] = [];
            }

            $_save[$provider][$key] = $value;
        }

        // --------------------------------------------------------------------------

        //  Prune any which aren't worth saving
        foreach ($_save as $provider => $values) {

            //  Are we only interested in a particular provider?
            if (!empty($_provider)) {

                if (array_search($provider, $_provider) === false) {
                    unset($_save[$provider]);
                    continue;
                }
            }

            //  Connected?
            if (!$this->isConnectedWith($provider)) {
                unset($_save[$provider]);
                continue;
            }

            //  Got an identifier?
            try {

                $oAdapter = $this->oHybridAuth->getAdapter($provider);
                $oProfile = $oAdapter->getUserProfile();

                if (!empty($oProfile->identifier)) {
                    $_identifiers[$provider] = $oProfile->identifier;
                }

            } catch (\Exception $e) {
                unset($_save[$provider]);
                continue;
            }
        }

        // --------------------------------------------------------------------------

        /**
         * Get the user's existing data, so we know whether we're inserting or
         * updating their data
         */

        $this->oDb->where('user_id', $user_id);
        $aExisting = $this->oDb->get(NAILS_DB_PREFIX . 'user_social')->result();
        $aExists   = [];

        foreach ($aExisting as $existing) {
            $aExists[$existing->provider] = $existing->id;
        }

        // --------------------------------------------------------------------------

        //  Save data
        $this->oDb->trans_begin();

        $oNow = Factory::factory('DateTime');

        foreach ($_save as $provider => $keys) {

            if (isset($aExists[$provider])) {

                //  Update
                $aData = [
                    'identifier'   => $_identifiers[$provider],
                    'session_data' => serialize($keys),
                    'modified'     => $oNow->format('Y-m-d H:i{s'),
                ];

                $this->oDb->set($aData);
                $this->oDb->where('id', $aExists[$provider]);
                $this->oDb->update(NAILS_DB_PREFIX . 'user_social');

            } else {

                //  Insert
                $aData = [
                    'user_id'      => (int) $user_id,
                    'provider'     => $provider,
                    'identifier'   => $_identifiers[$provider],
                    'session_data' => serialize($keys),
                    'created'      => $oNow->format('Y-m-d H:i:s'),
                    'modified'     => $oNow->format('Y-m-d H:i:s'),
                ];

                $this->oDb->set($aData);
                $this->oDb->insert(NAILS_DB_PREFIX . 'user_social');
            }
        }

        // --------------------------------------------------------------------------

        if ($this->oDb->trans_status() === false) {
            $this->oDb->trans_rollback();
            return false;
        } else {
            $this->oDb->trans_commit();
            return true;
        }
    }
182611
public static function generate($userId, $lifetime = 3600)
    {
        $token = new static;

        $token->token = str_random(40);
        $token->user_id = $userId;
        $token->created_at = Carbon::now();
        $token->last_activity_at = Carbon::now();
        $token->lifetime_seconds = $lifetime;

        return $token;
    }
27678
public function loginUsingId($userId)
    {
        $guard = config('autologin.guard');

        if ($user = Auth::guard($guard)->getProvider()->retrieveById($userId)) {

            Auth::guard($guard)->login($user);

            return $user;
        }

        return null;
    }
1062065
protected static function export_user_data_in_system_context($userid) {
        static::export_user_data_frameworks_in_context($userid, context_system::instance());
        static::export_user_data_templates_in_context($userid, context_system::instance());
    }
882285
protected static function delete_user_data($userid) {
        global $DB;
        $DB->delete_records_select('messageinbound_messagelist', 'userid = :userid', ['userid' => $userid]);
        \core_userkey\privacy\provider::delete_userkeys('messageinbound_handler', $userid);
    }
1082199
public function getUser(string $userid)
    {
        $cl = $this->getUserClass();
        $user = new $cl;
        return $user->obtainByUserID($userid);
    }
293124
public function isOnline(int $user_id): bool
    {
        if (isset($this->_online_status_cached[$user_id])) {
            return $this->_online_status_cached[$user_id];
        }

        // Check session for current user exists
        $sessions = new UsersSessionEntityRepository();
        $sessions->setWhereUserId($user_id);
        $sessions->setLimit(1);
        $sessions->addWhereFieldIsHigher('ts', (NOW - 120)); // 2 minutes

        return $this->_online_status_cached[$user_id] = $sessions->hasAnyObjectInCollection();
    }
959459
protected function getUser($userId = null)
    {
        if ($userId === null) {
            /** @var Token $sessionAuth */
            if ($this->session()->isStarted() && $sessionAuth = $this->session()->get('authentication')) {
                return $sessionAuth->getUser();
            }

            return false;
        }
        /** @var Repository\UsersRepository $repo */
        $repo = $this->storage()->getRepository(Entity\Users::class);

        return $repo->getUser($userId);
    }
223928
public function markAsRead($userId)
    {
        try {
            $participant = $this->getParticipantFromUser($userId);
            $participant->last_read = new Carbon;
            $participant->save();
        } catch (ModelNotFoundException $e) {
            // do nothing
        }
    }
718312
public function login(UserInterface $user, $remember = false)
    {
        $this->updateSession($user->getAuthIdentifier());

        // If the user should be permanently "remembered" by the application we will
        // queue a permanent cookie that contains the encrypted copy of the user
        // identifier. We will then decrypt this later to retrieve the users.
        if ($remember) {
            $this->createRememberTokenIfDoesntExist($user);

            $this->queueRecallerCookie($user);
        }

        // If we have an event dispatcher instance set we will fire an event so that
        // any listeners will hook into the authentication events and run actions
        // based on the login and logout events fired from the guard instances.
        if (isset($this->events)) {
            $this->events->dispatch('auth.login', array($user, $remember));
        }

        $this->setUser($user);
    }
394845
protected function setLastLogin($userId)
    {
        $user = $this->userService->findById($userId);

        $result = $this->userService->update($user, [
            'last_login' => time()
        ]);
    }
860320
public function loginUsingId($userId)
    {
        // Find the user using the user id
        try {
            $user = Sentry::findUserById($userId);

            // Log the user in
            Sentry::login($user);

            return $user;
        } catch (UserNotFoundException $e) {
            return null;
        }
    }
452850
public function getUser($userId)
    {
        // Check if we've already retrieved this user.
        if (isset($this->userEntities[$userId])) {
            return $this->userEntities[$userId];
        }

        $query = $this->getUserQuery($userId);
        /** @var Entity\Users $userEntity */
        if ($userEntity = $this->findOneWith($query)) {
            $this->unsetSensitiveFields($userEntity);
        }

        // Remember the user
        $this->userEntities[$userId] = $userEntity;

        return $userEntity;
    }
420450
public function write($userdata, $splash, $session, $sessionId, $expiry)
    {

        $database = $this->database;

        $database->insert($session->table, array(
            "session_key" => $database->quote($sessionId),
            "session_ip" => $database->quote($splash['ip']),
            "session_host" => $database->quote($splash['domain']),
            "session_agent" => $database->quote($splash['agent']),
            "session_token" => $database->quote($splash['token']),
            "session_expires" => $expiry,
            "session_lastactive" => time(),
            "session_registry" => $database->quote($userdata)
        ));
    }
456362
public function login(UserInterface $user, $remember = false)
	{
		if ( ! $user->isActivated())
		{
			$login = $user->getLogin();
			throw new UserNotActivatedException("Cannot login user [$login] as they are not activated.");
		}

		$this->user = $user;

		// Create an array of data to persist to the session and / or cookie
		$toPersist = array($user->getId(), $user->getPersistCode());

		// Set sessions
		$this->session->put($toPersist);

		if ($remember)
		{
			$this->cookie->forever($toPersist);
		}

		// The user model can attach any handlers
		// to the "recordLogin" event.
		$user->recordLogin();
	}