Check if a token already exists.

@param string $token The token to check for.
@param bool $returnQuery Whether to return or execute the query.
@return Query The Token Query or an empty Entity if none is found
559165
public function tokenExists($token, $returnQuery = false)
    {
        $query = $this->find()
            ->where([
                $this->alias() . '.token' => $token
            ]);
        if ($returnQuery) {
            return $query;
        }
        return $query->first();
    }
437635
public function checkQueryBoolean($fullUrlWithQuery)
    {
        if (is_array($fullUrlWithQuery)) {
            $result = call_user_func_array(array($this,'queryIsDeeply'), $fullUrlWithQuery);
        } else {
            $result = $this->queryIsDeeply($fullUrlWithQuery);   
        }
        return $result;
    }
783319
public function delete($token)
    {
        $query = $this->find(compact('token'));

        return $query->count() ? $this->getTable()->delete($query->first()) : false;
    }
128705
public function refreshAccessToken(TokenInterface $token)
    {
      $refreshToken = $token->getRefreshToken();

      if(empty($refreshToken))
        throw new MissingRefreshTokenException();

      $parameters = array(
        'grant_type'    => 'refresh_token',
        'type'          => 'web_server',
        'client_id'     => $this->credentials->getConsumerId(),
        'client_secret' => $this->credentials->getConsumerSecret(),
        'refresh_token' => $refreshToken,
      );

      require_once 'libx/base.php';

      require_once 'libx/net/http/codes.class.php';
      require_once 'libx/net/rest/client.class.php';
      require_once 'libx/net/rest/request.class.php';
      require_once 'libx/net/rest/response.class.php';

      $request = new \LibXRestRequest($this->getAccessTokenEndpoint(), \LibXRestRequest::REQUEST_METHOD_POST);
      $request->setParameters($parameters);

      $response = new \LibXRestResponse();

      $client = new \LibXRestClient();
      $client->execute($request, $response);

      // Parse token
      $token = $this->parseAccessToken($response->getData());

      // Store token
      $this->storage->storeAccessToken($this->service(), $token);

      // Return token
      return $token;
    }
112044
public function refreshToken(Token $token)
    {
        $user = $this->getProvider()->retrieveById($token->getClaim('sub'));
        $claimValidation = [static::JWT_GUARD_CLAIM => $this->id];
        if (!($user instanceof SubjectContract)
            || !$token->ensureClaimValues(array_merge($user->getJWTClaimValidation(), $claimValidation))) {
            return false;
        }
        return $this->generateToken($user);
    }
75473
public function refreshCreateAccessTokenResponse(
        ClientInterface $client,
        \Limoncello\OAuthServer\Contracts\TokenInterface $token,
        bool $isScopeModified,
        array $scope = null,
        array $extraParameters = []
    ): ResponseInterface {
        $this->logDebug('Prepare refresh token.');

        /** @var TokenInterface $token */
        assert($token instanceof TokenInterface);

        $updatedToken   = clone $token;
        $tokenExpiresIn = $this->getIntegration()->isRenewRefreshValue() === false ?
            $this->setUpTokenValue($updatedToken) : $this->setUpTokenValues($updatedToken);

        $tokenRepo = $this->getIntegration()->getTokenRepository();
        if ($isScopeModified === false) {
            $tokenRepo->updateValues($updatedToken);
        } else {
            assert(is_array($scope));
            $tokenRepo->inTransaction(function () use ($tokenRepo, $updatedToken, $scope) {
                $tokenRepo->updateValues($updatedToken);
                $tokenRepo->unbindScopes($updatedToken->getIdentifier());
                $tokenRepo->bindScopeIdentifiers($updatedToken->getIdentifier(), $scope);
            });
            $updatedToken->setScopeModified()->setScopeIdentifiers($scope);
        }
        $response = $this->createBodyTokenResponse($updatedToken, $tokenExpiresIn);

        return $response;
    }
943484
protected function _scopeOperator(Query $query, TokenInterface $token)
    {
        return $this->_table->applySearchOperator($query, $token);
    }
1138570
protected function renderIncludeQuery(Token $token)
    {
        $collections = $this->query->getIncludes();

        $mainMetadata = $this->query->getEntityMetadata();
        $mainCollection = $mainMetadata->getCollection();

        $subqueryTemplateSql = "SELECT {{fieldList}} FROM " . $this->renderArbitraryReference($mainCollection);

        // parse the tokens for join conditions
        $joinConditions = [];
        $joinMap = [];
        $sequenceInWhereClause = false;
        $collectionsInWhereClause = [];

        while (!empty($token) && !in_array($token->getType(), ["group", "sort", "limit"])) {
            $subqueryTemplateSql .= " " . $this->renderToken($token);
            if ($token->getType() == "join") {
                /** @var Reference $ref */
                $ref = $this->query->getNextToken();
                $alias = $this->getReferenceAlias($ref);;
                $subqueryTemplateSql .= " " . $this->renderToken($ref);
                $subqueryTemplateSql .= " " . $this->renderToken($this->query->getNextToken()); // ON
                $subqueryTemplateSql .= " " . $this->renderToken($this->query->getNextToken()); // (

                // write the join condition to a separate array, so we can replace it into the SQL when appropriate
                $level = 1; // counter to keep track of how deep we go into any closures
                $joinCondition = "";
                $joinCollectionsFound = [];
                while (($token = $this->query->getNextToken()) && !($token->getType() == "close" && $level == 1)) {
                    /** @var Token $token */
                    $joinCondition .= " " . $this->renderToken($token);
                    $type = $token->getType();
                    switch ($type) {
                        case "field":
                            /** @var Reference $token */
                            // save the collection from this reference
                            $collection = $this->getCollectionFromReference($token);
                            if (!empty($collection)) {
                                $joinCollectionsFound[] = $collection;
                            }
                            break;
                        case "open":
                            ++$level;
                            break;
                        case "close":
                            --$level;
                            break;
                    }

                }

                // if we found enough collections, create a mapping between them
                if (count($joinCollectionsFound) > 1) {
                    $this->mapJoins($joinCollectionsFound, $joinMap, $collections);
                }

                // save the join condition and write a placeholder to the template SQL
                $joinConditions[$alias] = $joinCondition;
                $subqueryTemplateSql .= "%{$alias}Condition%";

                $subqueryTemplateSql .= $this->renderToken($token); // )
            }

            if ($sequenceInWhereClause && $token->getType() == "field") {
                // record that this field's collection is used in the where clause
                /** @var Reference $token */
                $field = $token->getValue();
                $refs = explode(".", $field);

                // remove the field ref and leave the collection ref, if it exists
                array_pop($refs);

                if (!empty($refs)) {
                    $collection = array_pop($refs);
                    $collectionsInWhereClause[$collection] = true;
                }
            }

            if ($token->getType() == "where") {
                $sequenceInWhereClause = true;
            }

            $token = $this->query->getNextToken();
        };

        // add target entity to the collections array (as the first element to make sorting easier later)
        unset($collections[$mainCollection]);
        $collections = array_merge([$mainCollection => $mainMetadata], $collections);

        $primaryKeys = $this->getPrimaryKeys($collections);

        // recursively construct the join tree
        $joinTree = $this->constructJoinTree($joinMap, $mainCollection);
        // recursively parse the tree into join lists
        $joinLists = $this->parseJoinTree($joinTree, $collections);

        $sortData = $this->processSortFields($token, $collections, $mainCollection, $primaryKeys);

        $allFields = array_merge($this->fields, $sortData["additionalFields"]);

        // find all collection lists that have at least one collection in the where clause and add all of them
        foreach ($joinLists as $collectionList) {
            $list = array_flip($collectionList);
            if (!empty(array_intersect_key($collectionsInWhereClause, $list))) {
                $collectionsInWhereClause = array_replace($collectionsInWhereClause, $list);
            }
        }

        // create the SQL for each subquery
        $subqueries = [];
        foreach ($joinLists as $collectionList) {
            $templateJoinConditions = $joinConditions;
            $replacements = [];

            $subqueryFields = $allFields;

            foreach ($templateJoinConditions as $collection => $condition) {
                // if this is a collection that were including and that isn't in the collection list, exclude it from the subquery
                if (isset($collections[$collection]) && !in_array($collection, $collectionList)) {
                    if (!isset($collectionsInWhereClause[$collection])) {
                        // we don't need this join at all
                        $condition = "FALSE";
                    } else {
                        // we need the join, but mask this collections fields
                        foreach ($subqueryFields as $alias => $fieldSql) {
                            if (strpos($alias, $collection . "__") !== false) {
                                $subqueryFields[$alias] = "NULL" . substr($fieldSql, stripos($fieldSql, " as "));
                            }
                        }
                        $replacements["{{fieldList}}"] = implode(", ", $subqueryFields);
                    }
                }
                $replacements["%{$collection}Condition%"] = $condition;
            }
            $subqueries[] = strtr($subqueryTemplateSql, $replacements);
        }

        $sortSql = empty($sortData["sort"])? "": " ORDER BY " . implode(", ", $sortData["sort"]);
        $limitSort = empty($sortData["limitSort"])? "": " ORDER BY " . implode(", ", $sortData["limitSort"]);

        // process limits
        $mainAliasedPk = $this->getSelectFieldAlias($mainCollection . "." . $primaryKeys[$mainCollection]);
        $limitSubquery = $this->processIncludeQueryLimit($sortData["nextToken"], $joinConditions, $collections, $subqueryTemplateSql, $limitSort, $mainAliasedPk);

        $fieldList = implode(", ", $allFields);

        $sql = "SELECT s.* FROM (" . implode(" UNION ", $subqueries) . ") s";
        $sql .= $limitSubquery;
        $sql = str_replace("{{fieldList}}", $fieldList, $sql);

        // add the sort SQL, but with the fields aliased to the "s" table
        $sql .= $sortSql;

        return $sql;
    }
1338025
public function parseToken($method = 'bearer', $header = 'authorization', $query = 'token')
    {
        if (! $token = $this->parseAuthHeader($header, $method)) {
            if (! $token = $this->request->{$query}) {
                if (! $token = $this->request->header('Token')) {
                    throw new JWTException('The token could not be parsed from the request', 400);
                }
            }
        }

        return $this->setToken($token);
    }
261595
public function readTokenByRefreshValue(string $refreshValue): ?\Limoncello\OAuthServer\Contracts\TokenInterface
    {
        return $this->getIntegration()->getTokenRepository()->readByRefresh(
            $refreshValue,
            $this->getIntegration()->getTokenExpirationPeriod()
        );
    }
1107298
public function explainAction($token, $connectionName, $query)
    {
        /** @var Profiler $profiler */
        $profiler = $this->container->get('profiler');
        $profiler->disable();

        $profile = $profiler->loadProfile($token);
        $queries = $profile->getCollector('db')->getQueries();

        if (! isset($queries[$connectionName][$query])) {
            return new Response('This query does not exist.');
        }

        $query = $queries[$connectionName][$query];
        if (! $query['explainable']) {
            return new Response('This query cannot be explained.');
        }

        /** @var Connection $connection */
        $connection = $this->container->get('doctrine')->getConnection($connectionName);
        try {
            if ($connection->getDatabasePlatform() instanceof SQLServerPlatform) {
                $results = $this->explainSQLServerPlatform($connection, $query);
            } else {
                $results = $this->explainOtherPlatform($connection, $query);
            }
        } catch (Exception $e) {
            return new Response('This query cannot be explained.');
        }

        return new Response($this->container->get('twig')->render('@Doctrine/Collector/explain.html.twig', [
            'data' => $results,
            'query' => $query,
        ]));
    }
853632
public function createToken($owner, $client, array $scopes = []): RefreshToken
    {
        if (empty($scopes)) {
            $scopes = $this->scopeService->getDefaultScopes();
        } else {
            $this->validateTokenScopes($scopes);
        }

        do {
            $token = RefreshToken::createNewRefreshToken(
                $this->serverOptions->getRefreshTokenTtl(),
                $owner,
                $client,
                $scopes
            );
        } while ($this->tokenRepository->tokenExists($token->getToken()));

        return $this->tokenRepository->save($token);
    }
1165010
protected function getTokenFromQuery(ServerRequestInterface $request, $queryParam)
    {
        $queryParams = $request->getQueryParams();

        if (empty($queryParams[$queryParam])) {
            return null;
        }

        return $queryParams[$queryParam];
    }
895416
public function retrieveResetToken($token)
    {
        return $this->queryBuilder->from($this->getTokenTable())
            ->where('token', $token)
            ->first();
    }
84476
public function get($token)
    {
        $result = $this->getConnection()->table('oauth_refresh_tokens')
                ->where('oauth_refresh_tokens.id', $token)
                ->where('oauth_refresh_tokens.expire_time', '>=', time())
                ->first();

        if (is_null($result)) {
            return;
        }

        return (new RefreshTokenEntity($this->getServer()))
               ->setId($result->id)
               ->setAccessTokenId($result->access_token_id)
               ->setExpireTime((int) $result->expire_time);
    }
154675
public static function hasToken(array $coll, $token)
    {
        if (!\is_array($token)) {
            return false;
        }

        return \in_array(\token_name($token[0]), $coll);
    }
334693
private function validateAPIToken($token, $request)
    {
        //get owner with that token
        $SQL_token = Convert::raw2sql($token);
        $tokenColumn = $this->tokenConfig['DBColumn'];

        $tokenOwner = DataObject::get_one(
            $this->tokenConfig['owner'],
            "\"" . $this->tokenConfig['DBColumn'] . "\"='" . $SQL_token . "'",
            false
        );

        if ($tokenOwner) {
            //check token expiry
            $tokenExpire = $tokenOwner->{$this->tokenConfig['expireDBColumn']};
            $now = time();
            $life = $this->tokenConfig['life'];

            if ($tokenExpire > ($now - $life)) {
                // check if token should automatically be updated
                if ($this->tokenConfig['autoRefresh']) {
                    $tokenOwner->setField($this->tokenConfig['expireDBColumn'], $now + $life);
                    $tokenOwner->write();
                }
                //all good, log Member in
                if (is_a($tokenOwner, Member::class)) {
                    # this is a login without the logging
                    Config::nest();
                    Config::modify()->set(Member::class, 'session_regenerate_id', true);
                    $identityStore = Injector::inst()->get(IdentityStore::class);
                    $identityStore->logIn($tokenOwner, false, $request);
                    Config::unnest();
                }

                return true;
            } else {
                //too old
                return new RESTfulAPIError(403,
                    'Token expired.',
                    array(
                        'message' => 'Token expired.',
                        'code' => self::AUTH_CODE_TOKEN_EXPIRED,
                    )
                );
            }
        } else {
            //token not found
            //not sure it's wise to say it doesn't exist. Let's be shady here
            return new RESTfulAPIError(403,
                'Token invalid.',
                array(
                    'message' => 'Token invalid.',
                    'code' => self::AUTH_CODE_TOKEN_INVALID,
                )
            );
        }
    }