Generate session id from session token

@param string $brokerId
@param string $token
@return string
554110
protected function generateSessionId($brokerId, $token)
    {
        $broker = $this->getBrokerInfo($brokerId);

        if (!isset($broker)) {
            return null;
        }

        return "SSO-{$brokerId}-{$token}-" . hash('sha256', 'session' . $token . $broker['secret']);
    }
800073
def session_token(self):
        """"""
        session_token = None
        if self.user_id is not None:
            session_token = token_getter(self.remote)
        if session_token:
            token = RemoteToken.get(
                self.user_id, self.remote.consumer_key,
                access_token=session_token[0]
            )
            return token
        return None
77178
private function activeNamespace(int $tokenID): string
    {
        foreach ($this->namespaces as $namespace => $position) {
            if ($tokenID >= $position[self::O_TOKEN] && $tokenID <= $position[self::C_TOKEN]) {
                return $namespace;
            }
        }

        //Seems like no namespace declaration
        $this->namespaces[''] = [
            self::O_TOKEN => 0,
            self::C_TOKEN => count($this->tokens),
            self::N_USES  => [],
        ];

        return '';
    }
276405
public static function generateTokenHash($host, $uri, $token, $secret)
    {
        $m0 = static::$tokenHashMagics[ord(substr($secret, -1, 1)) % 4];
        $m1 = static::$tokenHashMagics[ord(substr($secret, -2, 1)) % 4];
        $m2 = static::$tokenHashMagics[ord(substr($secret, -3, 1)) % 4];
        $m3 = static::$tokenHashMagics[ord(substr($secret, -4, 1)) % 4];

        $sha1 = sha1(
                $m0
                . $host
                . $m1
                . $uri
                . $m2
                . $token
                . $m3
                . $secret
        );

        return substr($sha1, 3, 4)
                . substr($sha1, 33, 4)
                . substr($sha1, 17, 4)
                . substr($sha1, 25, 4);
    }
260372
protected function validateBrokerSessionId(string $sessionId)
    {
        $matches = null;

        if (!preg_match('/^SSO-(\w*+)-(\w*+)-([a-z0-9]*+)$/', $this->getBrokerSessionId(), $matches)) {
            $this->fail('Invalid session id');
        }

        if ($this->generateSessionId($matches[1], $matches[2]) != $sessionId) {
            $this->fail('Checksum failed: Client IP address may have changed');
        }

        return $matches[1];
    }
315960
public static function get(string $token, string $openID = null, bool $echostr = false, bool $returnArray = false)
    {
        $nonce = 'test';
        $timestamp = time();

        $array = [$nonce, $timestamp, $token];
        sort($array, SORT_STRING);
        $signature = sha1(implode('', $array));
        $data = [
            'signature' => $signature,
            'timestamp' => $timestamp,
            'nonce' => $nonce,
            'openid' => $openID,
            'echostr' => $echostr ? 'echostr' : null,
        ];

        if ($returnArray) {
            return $data;
        }

        return '?'.http_build_query($data);
    }
1198950
public function createCustomToken($uid, array $claims = [], \DateTimeInterface $expiresAt = null): Token
    {
        if (count($claims)) {
            $this->builder->set('claims', $claims);
        }

        $this->builder->set('uid', (string) $uid);

        $now = time();
        $expiration = $expiresAt ? $expiresAt->getTimestamp() : $now + (60 * 60);

        $token = $this->builder
            ->setIssuedAt($now)
            ->setExpiration($expiration)
            ->sign($this->signer, $this->privateKey)
            ->getToken();

        $this->builder->unsign();

        return $token;
    }
1271689
protected function generateRoute(Token $token) : string
    {
        $route = route($this->config->get("laranixauth.{$this->configKey}.route"), [], false);

        return urlTo($route, ['token' => $token->token, 'email' => $token->email]);
    }
189158
public function tokenLoginAction($token)
    {
        $newSessionId = $this->loginTokenCache->get($token);
        $this->loginTokenCache->remove($token);

        if ($newSessionId === false) {
            $this->systemLogger->log(sprintf('Token-based login failed, non-existing or expired token %s', $token), LOG_WARNING);
            $this->redirect('index');
        }

        $this->systemLogger->log(sprintf('Token-based login succeeded, token %s', $token), LOG_DEBUG);

        $newSession = $this->sessionManager->getSession($newSessionId);
        if ($newSession->canBeResumed()) {
            $newSession->resume();
        }
        if ($newSession->isStarted()) {
            $newSession->putData('lastVisitedNode', null);
        } else {
            $this->systemLogger->log(sprintf('Failed resuming or starting session %s which was referred to in the login token %s.', $newSessionId, $token), LOG_ERR);
        }

        $this->replaceSessionCookie($newSessionId);
        $this->redirect('index', 'Backend\Backend');
    }
3831
public function generateToken($token_length=30, $prefix='') {
        $token_length = $token_length - strlen($prefix);
        if ($token_length < 0) { throw new Exception("Prefix is too long", 1); }
        
        $token = "";
        while (($len = strlen($token)) < $token_length) {
            $remaining_len = $token_length - $len;
            $bytes = random_bytes($remaining_len);
            $token .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $remaining_len);
        }

        return $prefix.$token;
    }
160241
private static function generatePoolClientId()
    {
        $now = ceil(microtime(true) * 10000);
        if (class_exists('Reaction', false)) {
            $rand = \Reaction::$app->security->generateRandomString(8);
        } else {
            $rand = static::randomStr();
        }
        return static::getClientIdPrefix() . $now . $rand;
    }
655848
public function read($sessionId): string
    {
        $identifier = $this->cryptProvider->makeSessionIdentifier($sessionId);

        if (!$this->storageDriver->sessionExists($identifier)) {
            return '';
        }

        $content = $this->storageDriver->get($identifier);
        if (!$content) {
            return '';
        }

        return $this->cryptProvider->decryptSessionData($sessionId, $content);
    }
1311649
public static function forgeDtoFromToken($token) {
        $token = trim($token);
        if(empty($token)) {
            return null;
        }
	    $token = trim($token);
	    $token = StringHelper::removeDoubleSpace($token);
        $tokenSegments = explode(SPC, $token);
	    $countSegments = count($tokenSegments);
       
        $isValid = $countSegments == 1 || $countSegments == 2;
        if(!$isValid) {
            throw new InvalidArgumentException('Invalid token format');
        }
		$tokenDto = new TokenDto();
        if(count($tokenSegments) == 1) {
	        $tokenDto->type = null;
	        $tokenDto->token = $tokenSegments[0];
        } elseif(count($tokenSegments) == 2) {
	        $tokenDto->type = strtolower($tokenSegments[0]);
	        $tokenDto->token = $tokenSegments[1];
        }
        return $tokenDto;
    }
640347
public function verifyToken($messageId, $token)
    {
        try {
            $verification = $this->getTokenResult($messageId, $token);

            return ($verification->getStatusCode() === Verification::STATUS_SUCCESS);
        } catch (Exception $e) {
            return false;
        }
    }
4250
public function getUserIdByResetPasswordToken($token)
    {
        $tokenData = (new UserPasswordReset())->getTokenData($token);
        return $tokenData == false ? null : $tokenData->user_id;
    }
1024630
public function init($id)
    {
        //as suggested in the OWASP PHP CSRF helper page
        //https://www.owasp.org/index.php/PHP_CSRF_Guard
        if (function_exists("hash_algos") && in_array("sha512", hash_algos())) {
            $token = hash("sha512", mt_rand(0, mt_getrandmax()));
        } else {
            $token = ' ';
            for ($i = 0; $i < 128; ++$i) {
                $r = mt_rand(0, 35);
                if ($r < 26) {
                    $c = chr(ord('a') + $r);
                } else {
                    $c = chr(ord('0') + $r - 26);
                }
                $token .= $c;
            }
        }
        $this->session->set($this->session_key.$id, $token);

        return $token;
    }
298426
public function forPreviousTokenId($tokenId) {
        $this->sql_select->join('gems__tokens as ct',
                'gems__tokens.gto_id_respondent_track = ct.gto_id_respondent_track AND
                    gems__tokens.gto_id_token != ct.gto_id_token AND
                        ((gems__tokens.gto_round_order > ct.gto_round_order) OR
                            (gems__tokens.gto_round_order = ct.gto_round_order AND gems__tokens.gto_created > ct.gto_created))',
                array());

        $this->sql_select
                ->where('ct.gto_id_token = ?', $tokenId)
                ->order('gems__tokens.gto_round_order')
                ->order('gems__tokens.gto_created');

        return $this;
    }