Creates a session for the given person

@param object ComPeopleDomainEntityPerson
@return void
188921
private function _createSession(ComPeopleDomainEntityPerson $person)
    {
        $session = $this->getService('com:application', array('session' => true))->getSession();

        $repo = $this->getService('repos:sessions.session');
        $entity = $repo->findOrAddNew(array('sessionId' => $session->getId()));
        $entity->setData(array(
            'nodeId' => (int) $person->id,
            'username' => (string) $person->username,
            'usertype' => (string) $person->usertype,
            'guest' => 0
        ));

        $session->set('person', (object) $person->getData());
    }
581719
public function afterSessionStart()
	{
		$session = JFactory::getSession();

		if ($session->isNew())
		{
			$session->set('registry', new Registry('session'));
			$session->set('user', new JUser);
		}
	}
278632
public void createSession(Session session) {
        sessionMap.put(session.id(), session);
        Event event = new Event();
        event.attribute("session", session);

        eventManager.fireEvent(EventType.SESSION_CREATED, event);
    }
783874
public function create()
    {
        if (!$this->name) {
            throw new UnexpectedValueException(
                'Cannot create a user with no name'
            );
        }

        $parts = array('CREATE USER :user');
        $params = array(':user' => $this->name);

        if ($this->host) {
            $parts[] = '@:host';
            $params[':host'] = strtolower($this->host) == 'any' ? '%' : $this->host;
        }
        if ($this->password) {
            $parts[] = 'IDENTIFIED BY :password';
            $params[':password'] = $this->password;
        }

        // Wrap in 'FLUSH PRIVILEGES' commands to update in-memory state
        $this->client->execute('FLUSH PRIVILEGES');
        $this->client->execute(implode(' ', $parts), $params);
        $this->client->execute('FLUSH PRIVILEGES');
    }
152296
public function setUser($value)
     {
         if ($value !== null) {
             $this->_user = $value;
         } else {
             $this->_user = Zend_Gdata_Photos::DEFAULT_USER;
         }
     }
1040146
function createSession(){

    // can also check if any ealier session can be used
    if (!currentSession){
        
        const createNewSession = _setSessionReferrer();
        const currentSessionCookie = utils.getCookie(constants.sessionCookieName);

        if (currentSessionCookie && !createNewSession){

            const currentSessionSplit = currentSessionCookie.split('__');
            currentSession = new session(currentSessionSplit[0], 
                parseInt(currentSessionSplit[1]), {});
            
            logger.debug('Found existing session', currentSessionSplit[0], 
                currentSessionSplit[1]);

        } else{

            currentSession = new session(null, null, {});
            setSessionCookie();

            logger.debug('Creating new session', currentSession.getSessionToken(), 
                currentSession.getSessionUnixTime());

        }

        // associate session referrer with the session
        if (sessionReferrer){

            currentSession.setExtra('referrer', sessionReferrer);
            
        }
        
    }

    return currentSession;

}
377600
public function initializeUserSession(WebRequest $request, Response $response, User $user)
    {
        // If the session already has user data ...
        if ($request->getSessionData('userUuid') !== false) {
            $sessionToken = $request->getSessionData('userSessionToken');
            $sessionTokenLifetime = $request->getSessionData('userSessionTokenLifetime');
            
            // Cleanup the session
            $this->cleanupSession($request);
            
            // Save the old session token for some requests in the next 60 seconds
            if ($sessionToken !== false) {
                $request->setSessionData('oldUserSessionToken', $sessionToken);
                $request->setSessionData('oldUserSessionTokenLifetime', $sessionTokenLifetime);
            }
        }
        
        // Regenerate the session
        $this->regenerateSession($request);
        
        $sessionToken = md5($user->getUuid()) . '-' . md5(uniqid());
        $sessionTokenLifeTime = time() + 300;
        
        $request->setSessionData('userUuid', $user->getUuid());
        $request->setSessionData('userSessionToken', $sessionToken);
        $request->setSessionData('userSessionTokenLifetime', $sessionTokenLifeTime);

        setcookie($sessionToken, $sessionTokenLifeTime, 0, '/', '', $request->isSsl());
    }
182068
protected function createsession(){
		bimport('users.general');
		bimport('users.social.user');
		bimport('users.social.users');
		$bsu=BUsersSocialUsers::getInstance();
		$list=$bsu->items_filter(array('provider'=>$this->provider,'social_id'=>$this->getSocialId()));
		$user=NULL;
		if(!empty($list)){
			BLog::addToLog('[Social.Adapter] Found social record in the database!');
			$su=reset($list);
			$user=$su->getuser();
			}else{
			BLog::addToLog('[Social.Adapter] Could not find social record in the database! Need to create it.');
			//Try to load existing user with such email.
			$email=$this->getEmail();
			if(!empty($email)){
				BLog::addToLog('[Social.Adapter] Loading user by email "'.$email.'"!');
				$bu=BUsers::getInstance();
				$user=$bu->get_user_byemail($email);
				}
			//If we have not loaded user = 
			if(empty($user)){
				BLog::addToLog('[Social.Adapter] Could not load user! Creating it. Email="'.$email.'"');
				$user=new BUser();
				$user->email=empty($email)?NULL:$email;
				$user->name=$this->getName();
				$user->active='Y';
				$user->birthday=$this->getBirthdayObject();
				$user->last_action=new DateTime();
				$r=$user->saveToDB();
				if(empty($r)){
					BLog::addToLog('[Social.Adapter] Could not save user!',LL_ERROR);
					return false;
					}
				BLog::addToLog('[Social.Adapter] User saved. User id='.$user->id.'.');
				//User saved.
				}
			$su=new BUsersSocialUser();
			$su->user=$user->id;
			$su->social_id=$this->getSocialId();
			$su->provider=$this->provider;
			$su->created=new DateTime();
			}
		if(empty($su)){
			BLog::addToLog('[Social.Adapter] Could not load social user record!',LL_ERROR);
			return false;
			}
		if(empty($user)){
			BLog::addToLog('[Social.Adapter] Could not load user!',LL_ERROR);
			return false;
			}
		//Get fields.
		$su->name=$this->getName();
		$su->email=$this->getEmail();
		$su->sex=$this->getSex();
		$su->birthday=$this->getBirthdayObject();
		$su->lastlogin=new DateTime();
		$su->avatar_remote=$this->getAvatar();
		$su->social_page=$this->getSocialPage();
		if(!empty($su->avatar_remote)){
			$r=$su->downloadavatar();
			if(!$r){
				return false;
				}
			}
		$r=$su->saveToDB();
		if(!$r){
			return false;
			}
		if((!empty($su->avatar_local))&&($user->avatar!=$su->avatar_local)){
			$user->avatar=$su->avatar_local;
			$user->saveToDB();
			}
		//Session.
		$options=array('interval'=>2592000,'updatestep'=>60);
		$sess=BUsersSession::getInstance();
		$r=$sess->newSession($user->id,$options);
		if(empty($r)){
			return false;
			}
		return true;
		}
202984
public function unimpersonateUser()
    {
        $realId = $this->session->remove('__realId');
        if ($realId !== null) {
            $this->user->identity->remove();
            $this->session->set($this->user->idParam, $realId);
            $identity = User::findOne($realId);
            $this->user->setIdentity($identity);
            $this->restoreBackedUpToken();
        }
    }
862248
public function setPersonInfo(string $person_id, string $person_name, string $tag)
    {
        return Request::exec(self::SET_PERSON_INFO, compact('person_id', 'person_name', 'tag'));
    }
1247683
protected void initUserObject() {

        Object o = null;
        try {
            if (CmsStringUtil.isEmpty(getParamAction()) || CmsDialog.DIALOG_INITIAL.equals(getParamAction())) {
                // edit an existing user, get the user object from db
                m_user = getCms().readUser(new CmsUUID(getParamUserid()));
                m_pwdInfo = new CmsPasswordInfo();
                CmsUserSettings settings = new CmsUserSettings(m_user);
                m_language = settings.getLocale().toString();
                m_site = CmsStringUtil.joinPaths(settings.getStartSite(), "/");
                m_startProject = settings.getStartProject();
                m_startFolder = settings.getStartFolder();
                m_startView = settings.getStartView();
                return;
            } else {
                // this is not the initial call, get the user object from session
                o = getDialogObject();
                Map<?, ?> dialogObject = (Map<?, ?>)o;
                m_user = (CmsUser)dialogObject.get(USER_OBJECT);
                m_pwdInfo = (CmsPasswordInfo)dialogObject.get(PWD_OBJECT);
                CmsUserSettings settings = new CmsUserSettings(m_user);
                m_language = settings.getLocale().toString();
                m_site = CmsStringUtil.joinPaths(settings.getStartSite(), "/");
                m_startProject = settings.getStartProject();
                m_startFolder = settings.getStartFolder();
                m_startView = settings.getStartView();
                return;
            }
        } catch (Exception e) {
            // noop
        }
        // create a new user object
        m_user = new CmsUser();
        m_pwdInfo = new CmsPasswordInfo();
        m_group = "";
        try {
            m_group = getCms().readGroup(getParamOufqn() + OpenCms.getDefaultUsers().getGroupUsers()).getName();
        } catch (CmsException e) {
            // ignore
        }
        m_language = CmsLocaleManager.getDefaultLocale().toString();
        m_site = CmsStringUtil.joinPaths(OpenCms.getSiteManager().getDefaultSite().getSiteRoot(), "/");
        m_startProject = OpenCms.getWorkplaceManager().getDefaultUserSettings().getStartProject();
        m_startFolder = OpenCms.getWorkplaceManager().getDefaultUserSettings().getStartFolder();
        m_startView = OpenCms.getWorkplaceManager().getDefaultUserSettings().getStartView();
    }
436567
public function setPrimaryAmazonUserData()
    {
        $oUtils = $this->_getContainer()->getUtils();
        $sShopSecureHomeUrl = $this->_getContainer()->getConfig()->getShopSecureHomeUrl();

        //Get primary user data from Amazon
        $oData = $this->_getContainer()->getClient()->getOrderReferenceDetails();
        $oOrderReferenceDetail = isset($oData->GetOrderReferenceDetailsResult->OrderReferenceDetails)
            ? $oData->GetOrderReferenceDetailsResult->OrderReferenceDetails : null;

        if ($oOrderReferenceDetail === null
            || isset($oOrderReferenceDetail->Destination->PhysicalDestination) === false
        ) {
            $oUtils->redirect($sShopSecureHomeUrl.'cl=user&fnc=cleanAmazonPay', false);
            return;
        }

        //Creating and(or) logging user
        $sStatus = (string)$oOrderReferenceDetail->OrderReferenceStatus->State;

        if ($sStatus === 'Draft') {
            //Manage primary user data
            $oAmazonData = $oOrderReferenceDetail->Destination->PhysicalDestination;
            $this->_managePrimaryUserData($oAmazonData);

            //Recalculate basket to get shipping price for created user
            $this->_getContainer()->getSession()->getBasket()->onUpdate();

            //Redirect with registered user or new shipping address to payment page
            $oUtils->redirect($sShopSecureHomeUrl.'cl=payment', false);
            return;
        }

        $oUtils->redirect($sShopSecureHomeUrl.'cl=user&fnc=cleanAmazonPay', false);
    }
689137
public function createSession()
    {
        $obj = new stdClass();

        $obj->Timestamp = $this->getTimeStamp();
        $obj->Username = $this->getUsername();
        $obj->PinCode = $this->getPinCode();
        $obj->UserAgent = $this->getUserAgent();

        // Generate Checksum
        $obj->Checksum = $this->generateChecksum($obj);

        // PinCode only used for the Checksum
        unset($obj->PinCode);

        // Create the session and get the response
        $response = $this->client->CreateSession($obj);
        $result = $response->CreateSessionResult;

        // Verify response data by making a new Checksum
        $res = new stdClass();
        // Must be in specific order for checksum -----
        $res->Timestamp = $result->Timestamp;
        $res->SessionID = $result->SessionID;
        $res->PinCode = $this->getPinCode();
        $res->Success = $result->Success;
        $res->Description = $result->Description;
        // --------------------------------------------
        $checkSum = $this->generateChecksum($res);

        // Compare Checksums
        if ($result->Checksum != $checkSum)
            throw new Exception("Data could not be verified");

        // Assign Session
        $this->_session = $result;

        $this->createCookie(true);
        $this->createPHPSession(true);

        // Return Respsonse
        return (array) $response;
    }
23775
private function _init_session(){

    // Getting or creating the session is it doesn't exist yet
    /** @var user\session */
    $this->session = user\session::get_instance();
    if ( !$this->session ){
      $this->session = new user\session();
    }

    /** @var int $id_session The ID of the session row in the DB */
    if ( $id_session = $this->get_id_session() ){
      $this->sess_cfg = json_decode($this->db->select_one(
        $this->class_cfg['tables']['sessions'],
        $this->class_cfg['arch']['sessions']['cfg'],
        [$this->class_cfg['arch']['sessions']['id'] => $id_session]
      ), true);
    }
    else{

      /** @var string $salt */
      $salt = self::make_fingerprint();

      /** @var string $fingerprint */
      $fingerprint = self::make_fingerprint();


      /** @var array $p The fields of the sessions table */
      $p =& $this->class_cfg['arch']['sessions'];

      $this->sess_cfg = [
        'fingerprint' => $this->get_print($fingerprint),
        'last_renew' => time()
      ];

      // Inserting the session in the database
      if ( $this->db->insert($this->class_cfg['tables']['sessions'], [
        $p['sess_id'] => $this->session->get_id(),
        $p['ip_address'] => $this->ip_address,
        $p['user_agent'] => $this->user_agent,
        $p['opened'] => 1,
        $p['last_activity'] => date('Y-m-d H:i:s'),
        $p['creation'] => date('Y-m-d H:i:s'),
        $p['cfg'] => json_encode($this->sess_cfg)
      ]) ){
        // Setting the session with its ID
        $id_session = $this->db->last_id();
        $this->session->set([
          'fingerprint' => $fingerprint,
          'tokens' => [],
          'id_session' => $id_session,
          'salt' => $salt
        ], self::$sn);
        $this->save_session();
      }
      else{
        $this->set_error(16);
      }
    }
    return $this;
  }
1127128
private function handleSessions()
	{
		if ($this->getRouter()->hasRoute()) {
			if (!$this->getRouter()->getRoute()->isPublic() || $this->getRouter()->getRoute()->allowSessions()) {
				if ($this->getSetting('userservice')) {
					try
					{
						if ($this->getSetting('userclass') === false) throw new PlinthException('Please define a user class and user repository');

						$this->getUserService()->setUserRepository($this->getEntityRepository()->getRepository($this->getSetting('userclass')));

						session_start();
					}
					catch (PlinthException $e)
					{
						throw $e;
					}
				} else {
					session_start();
				}
			}
		}
    }
689723
public void checkCreateSessionForUser(CmsUser user) throws CmsException {

        if (getUserSessionMode() == UserSessionMode.single) {
            List<CmsSessionInfo> infos = getSessionInfos(user.getId());
            if (!infos.isEmpty()) {
                throw new CmsCustomLoginException(
                    org.opencms.security.Messages.get().container(
                        org.opencms.security.Messages.ERR_ALREADY_LOGGED_IN_0));
            }
        }

    }
1288987
protected function session()
    {
        if (tao_helpers_Context::check('APP_MODE')) {
            // Set a specific ID to the session.
            $request = new \Request();
            if ($request->hasParameter('session_id')) {
                session_id($request->getParameter('session_id'));
            }
        }

        // set the session cookie to HTTP only.

        $this->configureSessionHandler();

        $sessionParams = session_get_cookie_params();
        $cookieDomain = ((true == tao_helpers_Uri::isValidAsCookieDomain(ROOT_URL)) ? tao_helpers_Uri::getDomain(ROOT_URL) : $sessionParams['domain']);
        $isSecureFlag = \common_http_Request::isHttps();
        session_set_cookie_params($sessionParams['lifetime'], tao_helpers_Uri::getPath(ROOT_URL), $cookieDomain, $isSecureFlag, TRUE);
        session_name(GENERIS_SESSION_NAME);

        if (isset($_COOKIE[GENERIS_SESSION_NAME])) {

            // Resume the session
            session_start();

            //cookie keep alive, if lifetime is not 0
            if ($sessionParams['lifetime'] !== 0) {
                $expiryTime = $sessionParams['lifetime'] + time();
                setcookie(session_name(), session_id(), $expiryTime, tao_helpers_Uri::getPath(ROOT_URL), $cookieDomain, $isSecureFlag, true);
            }
        }
    }