/**
  * @param AccessToken $accessToken
  *
  * @return AccessTokenEntity
  */
 protected function createEntity(AccessToken $accessToken)
 {
     $entity = new AccessTokenEntity($this->server);
     $entity->setId($accessToken->token);
     $entity->setExpireTime(Carbon::createFromFormat('Y-m-d H:i:s', $accessToken->expireTime)->getTimestamp());
     return $entity;
 }
 /**
  * Get a session from Redis storage by an associated access token.
  * 
  * @param  \League\OAuth2\Server\Entity\AccessTokenEntity  $accessToken
  * @return \League\OAuth2\Server\Entity\SessionEntity|null
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     if (!($token = $this->getValue($accessToken->getToken(), 'oauth_access_tokens'))) {
         return null;
     }
     return $this->get($token['session_id']);
 }
 /**
  * @inheritdoc
  */
 public function get($token)
 {
     $entity = new AccessTokenEntity($this->server);
     $entity->setId('mF_9.B5f-4.1JqM');
     $entity->setExpireTime(time() + 24 * 60 * 60);
     // NOW + 24h
     return $entity;
 }
Example #4
0
 /**
  * Get a session from an access token
  *
  * @param AccessTokenEntity $accessToken
  * @return SessionEntity
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $result = $this->db->table('oauth_sessions')->select('oauth_sessions.*')->join('oauth_access_tokens', 'oauth_sessions.id', '=', 'oauth_access_tokens.session_id')->where('oauth_access_tokens.id', $accessToken->getId())->first();
     if (is_null($result)) {
         return;
     }
     return (new SessionEntity($this->getServer()))->setId($result->id)->setOwner($result->owner_type, $result->owner_id);
 }
Example #5
0
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     if ($accessToken->getId() !== 'foo') {
         return null;
     }
     $session = new SessionEntity($this->server);
     $session->setId('foo');
     return $session;
 }
 /**
  * Get a session from an access token
  * @param  \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken The access token
  * @return \League\OAuth2\Server\Entity\SessionEntity
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $allowedSessionIds = $this->getConnection()->table('oauth_access_tokens')->where('id', $accessToken->getId())->pluck('session_id');
     $result = $this->getConnection()->table('oauth_sessions')->whereIn('id', $allowedSessionIds)->first();
     if (is_null($result)) {
         return null;
     }
     return (new SessionEntity($this->getServer()))->setId($result['id'])->setOwner($result['owner_type'], $result['owner_id']);
 }
 /**
  * Get a session from an access token.
  *
  * @param \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken The access token
  *
  * @return \League\OAuth2\Server\Entity\SessionEntity
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $result = Config::get('couch.client')->useDatabase('oauth_sessions')->getDoc($accessToken->getSessionId());
     if (is_null($result)) {
         return;
     }
     config('session', $result);
     return (new SessionEntity($this->getServer()))->setId($result->_id)->setOwner($result->owner_type, $result->owner_id);
 }
Example #8
0
 public function get($token)
 {
     if ($token !== 'foo') {
         return null;
     }
     $token = new AccessTokenEntity($this->server);
     $token->setId('foo');
     $token->setExpireTime(time() + 3600);
     return $token;
 }
 /**
  * @inheritdoc
  */
 public function getByAccessToken(AccessTokenEntity $entity)
 {
     $accessToken = AccessToken::findByToken($entity->getId());
     /** @var Session $session */
     $session = Session::find($accessToken->sessionId);
     if ($session === null) {
         throw new SessionNotFound();
     }
     return $this->createEntity($session);
 }
 /**
  * {@inheritdoc}
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $result = DB::table('oauth_sessions')->select(['oauth_sessions.id', 'oauth_sessions.owner_type', 'oauth_sessions.owner_id', 'oauth_sessions.client_id', 'oauth_sessions.client_redirect_uri'])->join('oauth_access_tokens', 'oauth_access_tokens.session_id', '=', 'oauth_sessions.id')->where('oauth_access_tokens.access_token', $accessToken->getId())->get();
     if (count($result) === 1) {
         $session = new SessionEntity($this->server);
         $session->setId($result[0]->id);
         $session->setOwner($result[0]->owner_type, $result[0]->owner_id);
         return $session;
     }
     return null;
 }
 /**
  * {@inheritdoc}
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $result = M('oauth_sessions')->field('oauth_sessions.id, oauth_sessions.owner_type, oauth_sessions.owner_id, oauth_sessions.client_id, oauth_sessions.client_redirect_uri')->join('LEFT JOIN oauth_access_tokens ON oauth_access_tokens.session_id = oauth_sessions.id')->where(array('oauth_access_tokens.access_token' => $accessToken->getId()))->select();
     if (count($result) === 1) {
         $session = new SessionEntity($this->server);
         $session->setId($result[0]['id']);
         $session->setOwner($result[0]['owner_type'], $result[0]['owner_id']);
         return $session;
     }
     return;
 }
 /**
  * {@inheritdoc}
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $result = $this->getConnection()->table('oauth_sessions')->select(['oauth_sessions.id', 'oauth_sessions.owner_type', 'oauth_sessions.owner_id', 'oauth_sessions.client_id', 'oauth_sessions.client_redirect_uri'])->join('oauth_access_tokens', 'oauth_access_tokens.session_id', '=', 'oauth_sessions.id')->where('oauth_access_tokens.access_token', $accessToken->getId())->first();
     if (!is_null($result)) {
         $session = new SessionEntity($this->server);
         $session->setId($result->id);
         $session->setOwner($result->owner_type, $result->owner_id);
         return $session;
     }
     return;
 }
 /**
  * Get a session from an access token
  * @param  \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken The access token
  * @return \League\OAuth2\Server\Entity\SessionEntity
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $result = $this->db->fetchAll("SELECT s.id, s.owner_type, s.owner_id, s.client_id, s.client_redirect_uri FROM oauth_sessions s " . "JOIN oauth_access_tokens t ON t.session_id = s.id " . "WHERE t.access_token = ?", Db::FETCH_ASSOC, [$accessToken->getId()]);
     if (count($result) === 1) {
         $session = new SessionEntity($this->server);
         $session->setId($result[0]['id']);
         $session->setOwner($result[0]['owner_type'], $result[0]['owner_id']);
         return $session;
     }
     return NULL;
 }
Example #14
0
 public function getByAccessToken(AccessTokenEntity $access_token)
 {
     $sql = 'SELECT oauth_sessions.id, oauth_sessions.owner_type,' . ' oauth_sessions.owner_id, oauth_sessions.client_id,' . ' oauth_sessions.client_redirect_uri' . ' FROM oauth_sessions' . ' INNER JOIN oauth_access_tokens' . ' ON oauth_access_tokens.session_id = oauth_sessions.id' . ' WHERE oauth_access_tokens.access_token = ?;';
     $results = $this->db->fetch($sql, [$access_token->getId()]);
     if (count($results) === 1) {
         $session = new SessionEntity($this->server);
         $session->setId($result[0]['id']);
         $session->setOwner($result[0]['owner_type'], $result[0]['owner_id']);
         return $session;
     }
     return null;
 }
 /**
  * {@inheritdoc}
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $query = $this->db->createQueryBuilder()->select('s.id', 's.owner_type', 's.owner_id')->from('oauth_sessions', 's')->join('s', 'oauth_access_tokens', 'at', 's.id = at.session_id')->where('at.access_token = :accessToken');
     $query->createNamedParameter($accessToken->getId(), \PDO::PARAM_STR, ':accessToken');
     $stmt = $query->execute();
     $result = $stmt->fetchAll();
     if (count($result) === 1) {
         $session = new SessionEntity($this->server);
         $session->setId($result[0]['id']);
         $session->setOwner($result[0]['owner_type'], $result[0]['owner_id']);
         return $session;
     }
 }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function getByAccessToken(AccessTokenEntity $accessTokenEntity)
 {
     /** @var AccessToken $accessToken */
     $accessToken = $this->dm->getRepository(AccessToken::class)->find($accessTokenEntity->getId());
     if ($accessToken === null) {
         return null;
     }
     $session = $accessToken->getSession();
     $sessionEntity = new SessionEntity($this->server);
     $sessionEntity->setId($session->getId());
     $sessionEntity->setOwner($session->getOwnerType(), $session->getOwnerId());
     return $sessionEntity;
 }
 /**
  * {@inheritdoc}
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $key = RedisUtil::prefix($accessToken->getId(), 'oauth_access_tokens');
     if (isset($this->cache[$key])) {
         $result = $this->cache[$key];
     } else {
         if (!($value = RedisCapsule::get($key))) {
             return;
         }
         $result = $this->cache[$key] = RedisUtil::unserialize($value);
     }
     return $this->getSession($result['session_id']);
 }
 /**
  * {@inheritdoc}
  *
  * @param \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken Access token
  * @return \League\OAuth2\Server\Entity\SessionEntity
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $this->loadModel('OAuthServer.Sessions');
     $result = $this->Sessions->find()->matching('AccessTokens', function ($q) use($accessToken) {
         return $q->where(['oauth_token' => $accessToken->getId()]);
     })->first();
     if ($result) {
         $session = new SessionEntity($this->server);
         $session->setId($result->id);
         $session->setOwner($result->owner_model, $result->owner_id);
         return $session;
     }
 }
 public function testAssociateScope()
 {
     $redis = $this->prophesize("Corley\\OAuth2\\Server\\Storage\\Redis\\RedisMock");
     $redis->lpush("access_token:scopes:access_token_id", "scope_id:desc")->shouldBeCalledTimes(1)->willReturn(null);
     $server = $this->prophesize("League\\OAuth2\\Server\\AbstractServer");
     $server->getEventEmitter()->willReturn(new Emitter());
     $accessTokenStorage = new AccessTokenStorage($redis->reveal());
     $accessTokenStorage->setServer($server->reveal());
     $accessToken = new AccessTokenEntity($server->reveal());
     $accessToken->setId("access_token_id");
     $scope = new ScopeEntity($server->reveal());
     $scope->hydrate(["id" => "scope_id", "description" => "desc"]);
     $accessTokenStorage->associateScope($accessToken, $scope);
 }
 public function testPutAndGetSessionByAccessToken()
 {
     $server = m::mock(AbstractServer::class);
     $server->shouldReceive('getEventEmitter->emit')->once();
     $session = new SessionEntity($server);
     $session->setOwner('owner', 1);
     $session->setId('id');
     $accessToken = new AccessTokenEntity($server);
     $accessToken->setId('my_token');
     $accessToken->setExpireTime(1);
     $this->cache->putSessionByAccessToken($accessToken, $session);
     $session = $this->cache->getSessionByAccessToken('my_token');
     $this->assertSame(['id' => 'id', 'owner_type' => 'owner', 'owner_id' => 1], $session);
 }
 /**
  * Complete the password grant.
  *
  * @throws
  *
  * @return array
  */
 public function completeFlow()
 {
     // Get the required params
     $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
     if (is_null($clientId)) {
         throw new Exception\InvalidRequestException('client_id');
     }
     $clientSecret = $this->server->getRequest()->request->get('client_secret', $this->server->getRequest()->getPassword());
     if (is_null($clientSecret)) {
         throw new Exception\InvalidRequestException('client_secret');
     }
     // Validate client ID and client secret
     $client = $this->server->getClientStorage()->get($clientId, $clientSecret, null, $this->getIdentifier());
     if ($client instanceof ClientEntity === false) {
         $this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest()));
         throw new Exception\InvalidClientException();
     }
     $userId = $this->server->getRequest()->request->get('user_id', null);
     if (is_null($userId)) {
         throw new Exception\InvalidRequestException('user_id');
     }
     // Create a new session
     $session = new SessionEntity($this->server);
     $session->setOwner('user', $userId);
     $session->associateClient($client);
     // Generate an access token
     $accessToken = new AccessTokenEntity($this->server);
     $accessToken->setId(SecureKey::generate());
     $accessToken->setExpireTime($this->getAccessTokenTTL() + time());
     $this->server->getTokenType()->setSession($session);
     $this->server->getTokenType()->setParam('access_token', $accessToken->getId());
     $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
     // Associate a refresh token if set
     if ($this->server->hasGrantType('refresh_token')) {
         $refreshToken = new RefreshTokenEntity($this->server);
         $refreshToken->setId(SecureKey::generate());
         $refreshToken->setExpireTime($this->server->getGrantType('refresh_token')->getRefreshTokenTTL() + time());
         $this->server->getTokenType()->setParam('refresh_token', $refreshToken->getId());
     }
     // Save everything
     $session->save();
     $accessToken->setSession($session);
     $accessToken->save();
     if ($this->server->hasGrantType('refresh_token')) {
         $refreshToken->setAccessToken($accessToken);
         $refreshToken->save();
     }
     return $this->server->getTokenType()->generateResponse();
 }
Example #22
0
    /**
     * Get a session from an access token
     *
     * @param \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken The access token
     *
     * @return \League\OAuth2\Server\Entity\SessionEntity | null
     */
    public function getByAccessToken(AccessTokenEntity $accessToken)
    {
        $sql = <<<SQL
SELECT os.id, os.owner_type, os.owner_id, os.client_id, os.client_redirect_uri
FROM oauth_session os
INNER JOIN oauth_access_token oat ON(oat.session_id = os.id)
WHERE oat.access_token = :token
SQL;
        foreach ($this->getDbConnection()->fetchAll($sql, ['token' => $accessToken->getId()]) as $row) {
            if ($row) {
                return (new SessionEntity($this->server))->setId($row['id'])->setOwner($row['owner_type'], $row['owner_id']);
            }
        }
        return null;
    }
 /**
  * Complete the client credentials grant
  *
  * @return array
  *
  * @throws
  */
 public function completeFlow()
 {
     // Get the required params
     $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
     //$clientId= 'client1';
     if (is_null($clientId)) {
         throw new Exception\InvalidRequestException('client_id');
     }
     $clientSecret = $this->server->getRequest()->request->get('client_secret', $this->server->getRequest()->getPassword());
     //$clientSecret = 'test1';
     if (is_null($clientSecret)) {
         throw new Exception\InvalidRequestException('client_secret');
     }
     // Validate client ID and client secret
     $client = $this->server->getClientStorage()->get($clientId, $clientSecret, null, $this->getIdentifier());
     if ($client instanceof ClientEntity === false) {
         $this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest()));
         throw new Exception\InvalidClientException();
     }
     // Validate any scopes that are in the request
     $scopeParam = $this->server->getRequest()->request->get('scope', '');
     $scopes = $this->validateScopes($scopeParam, $client);
     // Create a new session
     $session = new SessionEntity($this->server);
     $session->setOwner('client', $client->getId());
     $session->associateClient($client);
     // Generate an access token
     $accessToken = new AccessTokenEntity($this->server);
     $accessToken->setId(SecureKey::generate());
     $accessToken->setExpireTime($this->getAccessTokenTTL() + time());
     // Associate scopes with the session and access token
     foreach ($scopes as $scope) {
         $session->associateScope($scope);
     }
     foreach ($session->getScopes() as $scope) {
         $accessToken->associateScope($scope);
     }
     // Save everything
     $session->save();
     $accessToken->setSession($session);
     $accessToken->save();
     $this->server->getTokenType()->setSession($session);
     $this->server->getTokenType()->setParam('access_token', $accessToken->getId());
     $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
     return $this->server->getTokenType()->generateResponse();
 }
Example #24
0
 /**
  * Get a session from an access token
  *
  * @param  \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken The access token
  *
  * @return SessionEntity
  * @throws OAuthException
  */
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $querySessions = new Query();
     $session = null;
     $sessionResult = $querySessions->select(['{{%oauth_sessions}}.id as id', '{{%oauth_sessions}}.owner_type as owner_type', '{{%oauth_sessions}}.owner_id as owner_id', '{{%oauth_sessions}}.client_id as client_id', '{{%oauth_sessions}}.client_redirect_uri as redirect_uri'])->from('{{%oauth_sessions}}')->innerJoin('oauth_access_tokens', 'oauth_access_tokens.session_id={{%oauth_sessions}}.id')->where(['oauth_access_tokens.access_token' => $accessToken->getId()])->one();
     if ($sessionResult) {
         $session = new SessionEntity($this->getServer());
         $session->setId($sessionResult['id']);
         $session->setOwner($sessionResult['owner_type'], $sessionResult['owner_id']);
         if (!$session->save()) {
             throw new OAuthException(json_encode($session->errors));
         }
     } else {
         throw new OAuthException(json_encode($sessionResult));
     }
     return $session;
 }
 public function getByAccessToken(AccessTokenEntity $accessToken)
 {
     $rawData = $this->redis->get("access_token:{$accessToken->getId()}");
     if (!$rawData) {
         return null;
     }
     $data = json_decode($rawData, true);
     $sessionId = $data['session_id'];
     $rawData = $this->redis->get("session:{$data["session_id"]}");
     if (!$rawData) {
         return null;
     }
     $data = json_decode($rawData, true);
     $session = new SessionEntity($this->server);
     $session->setId($sessionId);
     $session->setOwner($data['owner_type'], $data['owner_id']);
     return $session;
 }
    public function testGetMissingSessionIdWithAccessToken()
    {
        $redis = $this->prophesize("Corley\\OAuth2\\Server\\Storage\\Redis\\RedisMock");
        $redis->get("access_token:access_token_id")->willReturn(<<<EOF
{
    "session_id": "session_id"
}
EOF
);
        $redis->get("session:session_id")->willReturn(null);
        $server = $this->prophesize("League\\OAuth2\\Server\\AbstractServer");
        $server->getEventEmitter()->willReturn(new Emitter());
        $sessionStorage = new SessionStorage($redis->reveal());
        $sessionStorage->setServer($server->reveal());
        $accessToken = new AccessTokenEntity($server->reveal());
        $accessToken->setId("access_token_id");
        $session = $sessionStorage->getByAccessToken($accessToken);
        $this->assertNull($session);
    }
Example #27
0
 /**
  * Complete the client credentials grant
  *
  * @return array
  *
  * @throws
  */
 public function completeFlow()
 {
     $selfClient = app('selfClient');
     // Get the required params
     if (is_null($selfClient)) {
         throw new Exception\InvalidClientException();
     }
     // Validate client ID and client secret
     $client = $this->server->getClientStorage()->get($selfClient->id, $selfClient->secret, null, $this->getIdentifier());
     if ($client instanceof ClientEntity === false) {
         $this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest()));
         throw new Exception\InvalidClientException();
     }
     // Create a new session
     $session = new SessionEntity($this->server);
     $session->setOwner('client', $client->getId());
     $session->associateClient($client);
     // Generate an access token
     $accessToken = new AccessTokenEntity($this->server);
     $accessToken->setId(SecureKey::generate());
     $accessToken->setExpireTime($this->getAccessTokenTTL() + time());
     foreach ($session->getScopes() as $scope) {
         $accessToken->associateScope($scope);
     }
     // Save everything
     $session->save();
     $accessToken->setSession($session);
     $accessToken->save();
     $oauthClient = new GenericProvider(['clientId' => $selfClient->id, 'clientSecret' => $selfClient->secret, 'redirectUri' => null, 'urlAuthorize' => null, 'urlAccessToken' => null, 'urlResourceOwnerDetails' => null]);
     $accessToken = new AccessToken(['access_token' => $accessToken->getId(), 'expires' => $accessToken->getExpireTime()]);
     return function ($method, $url, $options = []) use($oauthClient, $accessToken) {
         return $oauthClient->getAuthenticatedRequest($method, $url, $accessToken, $options);
     };
 }
 /**
  * Checks if the access token is valid or not
  *
  * @param bool                                                $headerOnly Limit Access Token to Authorization header
  * @param \League\OAuth2\Server\Entity\AccessTokenEntity|null $accessToken Access Token
  *
  * @throws \League\OAuth2\Server\Exception\AccessDeniedException
  * @throws \League\OAuth2\Server\Exception\InvalidRequestException
  *
  * @return bool
  */
 public function isValidRequest($headerOnly = true, $accessToken = null)
 {
     $accessTokenString = $accessToken !== null ? $accessToken : $this->determineAccessToken($headerOnly);
     // Set the access token
     $this->accessToken = $this->getAccessTokenStorage()->get($accessTokenString);
     // Ensure the access token exists
     if (!$this->accessToken instanceof AccessTokenEntity) {
         throw new AccessDeniedException();
     }
     // Check the access token hasn't expired
     // Ensure the auth code hasn't expired
     if ($this->accessToken->isExpired() === true) {
         throw new AccessDeniedException();
     }
     return true;
 }
 /**
  * {@inheritdoc}
  */
 public function delete(AccessTokenEntity $token)
 {
     $this->getConnection()->table('oauth_access_tokens')->where('id', $token->getId())->delete();
 }
 /**
  * Validate a routes scopes.
  *
  * @param \League\OAuth2\Server\Entity\AccessTokenEntity $token
  * @param \Dingo\Api\Routing\Route                       $route
  *
  * @throws \League\OAuth2\Server\Exception\InvalidScopeException
  *
  * @return bool
  */
 protected function validateRouteScopes(AccessTokenEntity $token, Route $route)
 {
     $scopes = $route->scopes();
     if (empty($scopes)) {
         return true;
     }
     foreach ($scopes as $scope) {
         if ($token->hasScope($scope)) {
             return true;
         }
     }
     throw new InvalidScopeException($scope);
 }