Exemplo n.º 1
0
 /**
  * Retrieves the currently authenticate user's username.
  *
  * @return User
  *
  * @throws InvalidRequestException
  * @throws AccessDeniedException
  */
 public function getCurrentUser()
 {
     $this->server->isValidRequest();
     // Choooo chooo!!
     $ownerId = $this->server->getAccessToken()->getSession()->getOwnerId();
     return $this->speakerRepository->findById($ownerId);
 }
Exemplo n.º 2
0
 /**
  * Register the Resource Server
  *
  * @return void
  */
 private function resource()
 {
     $this->app->singleton('League\\OAuth2\\Server\\ResourceServer', function ($app) {
         $server = new ResourceServer(new SessionStorage($app->make('db')), new AccessTokenStorage($app->make('db')), new ClientStorage($app->make('db')), new ScopeStorage($app->make('db')));
         $server->setRequest($app['request']);
         return $server;
     });
 }
Exemplo n.º 3
0
 /**
  * Handle an incoming request
  *
  * @param Request $request
  * @param Closure $next
  * @return Response
  */
 public function handle($request, Closure $next)
 {
     try {
         $this->server->isValidRequest();
         return $next($request);
     } catch (OAuthException $e) {
         return new JsonResponse(['error' => $e->errorType, 'message' => $e->getMessage()], $e->httpStatusCode, $e->getHttpHeaders());
     }
 }
Exemplo n.º 4
0
 /**
  * Handle an incoming request
  *
  * @param Request $request
  * @param Closure $next
  * 
  * @return Response
  */
 public function handle($request, Closure $next)
 {
     try {
         $this->server->isValidRequest();
         return $next($request);
     } catch (OAuthException $e) {
         $error = $e->errorType;
         $message = $e->getMessage();
         return response()->json(compact('error', 'message'), $e->httpStatusCode, $e->getHttpHeaders());
     }
 }
Exemplo n.º 5
0
 public function createToken(Request $request, $providerKey)
 {
     $this->resourceServer->setRequest($request);
     try {
         $accessToken = $this->resourceServer->determineAccessToken(true);
     } catch (InvalidRequestException $e) {
         // skip OAuth authentication
         return null;
     }
     return new PreAuthenticatedToken('anon.', $accessToken, $providerKey);
 }
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable               $next
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     try {
         $request = $this->server->validateAuthenticatedRequest($request);
     } catch (OAuthServerException $exception) {
         return $exception->generateHttpResponse($response);
         // @codeCoverageIgnoreStart
     } catch (\Exception $exception) {
         return (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500))->generateHttpResponse($response);
         // @codeCoverageIgnoreEnd
     }
     // Pass the request and response on to the next responder in the chain
     return $next($request, $response);
 }
Exemplo n.º 7
0
 public function getUser(Request $request)
 {
     try {
         $this->Server->isValidRequest(true, $request->query('access_token'));
         $ownerModel = $this->Server->getAccessToken()->getSession()->getOwnerType();
         $ownerId = $this->Server->getAccessToken()->getSession()->getOwnerId();
         $event = new Event('OAuthServer.getUser', $request, [$ownerModel, $ownerId]);
         EventManager::instance()->dispatch($event);
         if ($event->result) {
             return $event->result;
         } else {
             $model = TableRegistry::get($ownerModel);
             return $model->get($ownerId)->toArray();
         }
     } catch (OAuthException $e) {
         $this->_exception = $e;
         return false;
     }
 }
 /**
  * Save the session
  *
  * @return void
  */
 public function save()
 {
     // Save the session and get an identifier
     $id = $this->server->getSessionStorage()->create($this->getOwnerType(), $this->getOwnerId(), $this->getClient()->getId(), $this->getClient()->getRedirectUri());
     $this->setId($id);
     // Associate the scope with the session
     foreach ($this->getScopes() as $scope) {
         $this->server->getSessionStorage()->associateScope($this, $scope);
     }
 }
 /**
  * @param mixed $element
  * @throws AbortException
  */
 public final function checkRequirements($element)
 {
     if (!$element instanceof ComponentReflection) {
         return;
     }
     $request = $this->createServerRequest();
     $response = $this->createResponse();
     try {
         $request = $this->resourceServer->validateAuthenticatedRequest($request);
     } catch (OAuthServerException $e) {
         $this->sendResponse($e->generateHttpResponse($response));
     } catch (\Exception $e) {
         if ($this->logger) {
             $this->logger->error($e->getMessage(), ['exception' => $e]);
         }
         $body = $this->createStream();
         $body->write('Unknown error');
         $this->sendResponse($response->withStatus(IResponse::S500_INTERNAL_SERVER_ERROR)->withBody($body));
     }
     $this->onAuthorized($request);
 }
 function it_validates_an_access_token(ResourceServer $checker)
 {
     $checker->isValidRequest(false, null)->shouldBeCalled();
     $this->validateAccessToken(false, null);
 }
Exemplo n.º 11
0
 /**
  * Constructor
  *
  * The constructor does nothing by default but can be passed a boolean
  * variable to tell it to automatically run the __default() method. This is
  * typically used when a module is called outside of the scope of the
  * controller (the registration page calls the login page in this manner.
  */
 public function __construct($uids = false)
 {
     parent::__construct();
     $this->uids = $uids;
     $method = $_SERVER['REQUEST_METHOD'];
     try {
         // Checks if auth flag is explicity true or true for the method
         if ($this->auth === true || isset($this->auth[$method]) && $this->auth[$method]) {
             if (isset($this->config['oauth'][$_SERVER['__version']])) {
                 $server = new ResourceServer(new SessionStorage(), new AccessTokenStorage(), new ClientStorage(), new ScopeStorage());
                 $server->isValidRequest();
             } else {
                 throw new \Exception('Authentication is not configured properly.', 401);
             }
         }
         // Hacks together some new globals
         if (in_array($method, ['PUT', 'DELETE'])) {
             $GLOBALS['_' . $method] = [];
             // @todo Populate it
         }
         $filter = isset($this->filter[$method]);
         $validate = isset($this->validate[$method]);
         if ($filter || $validate) {
             $global =& $GLOBALS['_' . $method];
             // Checks that the required parameters are present
             // @todo Add in support for uid:* variables
             if ($validate) {
                 $variables = [];
                 foreach ($this->validate[$method] as $variable => $rules) {
                     if (!is_array($rules)) {
                         $variable = $rules;
                     }
                     $variables[] = $variable;
                 }
                 $missing_variables = array_diff($variables, array_keys($global));
                 if ($missing_variables !== array()) {
                     foreach ($missing_variables as $variable) {
                         $this->errors[$variable][] = 'The ' . $variable . ' parameter is required.';
                     }
                 }
             }
             foreach ($global as $variable => $value) {
                 // Applies any filters
                 if ($filter && isset($this->filter[$method][$variable])) {
                     $function = $this->filter[$method][$variable];
                     if ($function == 'password_hash') {
                         $global[$variable] = password_hash($value, PASSWORD_DEFAULT);
                     } else {
                         $global[$variable] = $function($value);
                     }
                 }
                 if ($validate && isset($this->validate[$method][$variable])) {
                     $rules = $this->validate[$method][$variable];
                     if (is_array($rules)) {
                         if (isset($global[$variable]) && !String::isEmpty($global[$variable])) {
                             if (is_array($rules)) {
                                 foreach ($rules as $rule => $message) {
                                     $rule = explode(':', $rule);
                                     for ($i = 1; $i <= 2; $i++) {
                                         if (!isset($rule[$i])) {
                                             $rule[$i] = false;
                                         }
                                     }
                                     switch ($rule[0]) {
                                         // {{{ Checks using filter_var()
                                         case 'filter':
                                             switch ($rule[1]) {
                                                 case 'boolean':
                                                 case 'email':
                                                 case 'float':
                                                 case 'int':
                                                 case 'ip':
                                                 case 'url':
                                                     $filter = constant('FILTER_VALIDATE_' . strtoupper($rule[1]));
                                                     if (!filter_var($value, $filter)) {
                                                         $this->errors[$variable][] = $message;
                                                     }
                                                     break;
                                                 default:
                                                     $this->errors[$variable] = 'Invalid filter, expecting boolean, email, float, int, ip or url.';
                                                     break;
                                             }
                                             break;
                                             // }}}
                                             // {{{ Checks using strlen()
                                         // }}}
                                         // {{{ Checks using strlen()
                                         case 'length':
                                             $length = strlen($value);
                                             switch ($rule[1]) {
                                                 case '<':
                                                     $valid = $length < $rule[2];
                                                     break;
                                                 case '<=':
                                                     $valid = $length <= $rule[2];
                                                     break;
                                                 case '==':
                                                     $valid = $length == $rule[2];
                                                     break;
                                                 case '!=':
                                                     $valid = $length != $rule[2];
                                                     break;
                                                 case '>=':
                                                     $valid = $length >= $rule[2];
                                                     break;
                                                 case '>':
                                                     $valid = $length > $rule[2];
                                                     break;
                                                 default:
                                                     $valid = false;
                                                     $message = 'Invalid operator, expecting <, <=, ==, !=, >= or >.';
                                                     break;
                                             }
                                             if (!$valid) {
                                                 $this->errors[$variable][] = $message;
                                             }
                                             break;
                                             // }}}
                                             // {{{ Checks using preg_match()
                                         // }}}
                                         // {{{ Checks using preg_match()
                                         case 'regex':
                                             if (preg_match($rule[1], $value)) {
                                                 $this->errors[$variable][] = $message;
                                             }
                                             break;
                                             // }}}
                                             // @todo case 'alpha':
                                             // @todo case 'alphanumeric':
                                             // @todo case 'date':
                                             // @todo case 'range':
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             // if PUT or DELETE, need to update the super globals directly as
             // they do not stay in sync. Probably need to make them global in
             // this class method
             //
             // $_PUT = $GLOBALS['_PUT'];
         }
         if ($this->errors) {
             throw new \Exception('Missing or invalid parameters.', 400);
         }
         parent::__construct();
         // Checks if the request method has been implemented
         if (get_class($this) != 'Pickles\\Resource') {
             if (!method_exists($this, $method)) {
                 throw new \Exception('Method not allowed.', 405);
             } else {
                 // Starts a timer before the resource is executed
                 if ($this->config['profiler']) {
                     $timer = get_class($this) . '->' . $method . '()';
                     Profiler::timer($timer);
                 }
                 $this->response = $this->{$method}();
                 // Stops the resource timer
                 if ($this->config['profiler']) {
                     Profiler::timer($timer);
                 }
             }
         }
     } catch (\Exception $e) {
         $code = $e->getCode();
         // Anything below 200 is probably a PHP error
         if ($code < 200) {
             $code = 500;
         }
         $this->status = $code;
         $this->message = $e->getMessage();
     }
 }
Exemplo n.º 12
0
 /**
  * Set the token type to use.
  *
  * @param \League\OAuth2\Server\TokenType\TokenTypeInterface $tokenType
  */
 public function setTokenType(TokenTypeInterface $tokenType)
 {
     $this->issuer->setTokenType($tokenType);
     $this->checker->setTokenType($tokenType);
 }
Exemplo n.º 13
0
<?php

use League\OAuth2\Server\ResourceServer;
use Orno\Http\Exception\NotFoundException;
use Orno\Http\Request;
use Orno\Http\Response;
use RelationalExample\Model;
use RelationalExample\Storage;
include __DIR__ . '/vendor/autoload.php';
// Set up the OAuth 2.0 resource server
$sessionStorage = new Storage\SessionStorage();
$accessTokenStorage = new Storage\AccessTokenStorage();
$clientStorage = new Storage\ClientStorage();
$scopeStorage = new Storage\ScopeStorage();
$server = new ResourceServer($sessionStorage, $accessTokenStorage, $clientStorage, $scopeStorage);
// Routing setup
$request = (new Request())->createFromGlobals();
$router = new \Orno\Route\RouteCollection();
// GET /tokeninfo
$router->get('/tokeninfo', function (Request $request) use($server) {
    $accessToken = $server->getAccessToken();
    $session = $server->getSessionStorage()->getByAccessToken($accessToken);
    $token = ['owner_id' => $session->getOwnerId(), 'owner_type' => $session->getOwnerType(), 'access_token' => $accessToken, 'client_id' => $session->getClient()->getId(), 'scopes' => $accessToken->getScopes()];
    return new Response(json_encode($token));
});
// GET /users
$router->get('/users', function (Request $request) use($server) {
    $results = (new Model\Users())->get();
    $users = [];
    foreach ($results as $result) {
        $user = ['username' => $result['username'], 'name' => $result['name']];
Exemplo n.º 14
0
$sessionStorage = new Storage\SessionStorage();
$accessTokenStorage = new Storage\AccessTokenStorage();
$clientStorage = new Storage\ClientStorage();
$scopeStorage = new Storage\ScopeStorage();
$refreshTokenStorage = new Storage\RefreshTokenStorage();
$authorizationServer = new \League\OAuth2\Server\AuthorizationServer();
$authorizationServer->setSessionStorage($sessionStorage);
$authorizationServer->setAccessTokenStorage($accessTokenStorage);
$authorizationServer->setClientStorage($clientStorage);
$authorizationServer->setScopeStorage($scopeStorage);
$authorizationServer->setRefreshTokenStorage($refreshTokenStorage);
//$clientCredentials = new \League\OAuth2\Server\Grant\ClientCredentialsGrant();
//$server->addGrantType($clientCredentials);
$refreshTokenGrant = new \League\OAuth2\Server\Grant\RefreshTokenGrant();
$authorizationServer->addGrantType($refreshTokenGrant);
$resourceServer = new ResourceServer($sessionStorage, $accessTokenStorage, $clientStorage, $scopeStorage, $refreshTokenStorage);
$passwordGrant = new \League\OAuth2\Server\Grant\PasswordGrant();
$authorizationServer->addGrantType($passwordGrant);
$passwordGrant->setVerifyCredentialsCallback(function ($username, $password) use($app) {
    // implement logic here to validate a username and password, return an ID if valid, otherwise return false
    $host = new Host();
    $valid = $host->oauth2Login($username, $password);
    if ($valid !== false) {
        return $valid;
    } else {
        $app->halt(401, 'Unauthorized. The user credentials were incorrect.');
    }
});
$authorize = function () use($resourceServer) {
    return function () use($resourceServer) {
        //401 = Unauthorized
Exemplo n.º 15
0
 /**
  * @return string
  */
 public function getClientId()
 {
     return $this->resourceServer->getAccessToken()->getSession()->getClient()->getId();
 }
Exemplo n.º 16
0
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @param  string  $scope
  * @return mixed
  */
 public function handle(Request $request, Closure $next, $scope = '')
 {
     // Set up the OAuth 2.0 resource server
     $server = new ResourceServer(new SessionStorage(), new AccessTokenStorage(), new ClientStorage(), new ScopeStorage());
     $isError = false;
     try {
         // Check that access token is present
         $server->isValidRequest();
     } catch (OAuthException $e) {
         // Catch an OAuth exception
         $response = new Response(['error' => $e->errorType, 'message' => $e->getMessage()], $e->httpStatusCode, $e->getHttpHeaders());
         $isError = true;
     } catch (\Exception $e) {
         $response = new Response(['error' => $e->getCode(), 'message' => $e->getMessage()], 500, []);
         $isError = true;
     }
     if (!$isError) {
         // Get session info
         $session = $server->getSessionStorage()->getByAccessToken($server->getAccessToken());
         if (!$session instanceof SessionEntity) {
             $isError = true;
         }
     }
     if (!$isError) {
         // Get user info
         $user = null;
         if ($session->getOwnerType() === 'user') {
             $user = User::find($session->getOwnerId());
             if (!$user instanceof User) {
                 $isError = true;
             }
         }
     }
     if (!$isError) {
         // Get client info
         $client = $server->getClientStorage()->getCompleteBySession($session);
         if (!$client instanceof ClientEntity) {
             $isError = true;
         }
     }
     if (!$isError) {
         // Get scopes info
         $scopes = $session->getScopes();
         if (!empty($scope)) {
             $isScopeFound = false;
             if (!is_null($scopes) && is_array($scopes)) {
                 foreach ($scopes as $scopeEntity) {
                     if ($scopeEntity->getId() === $scope) {
                         $isScopeFound = true;
                         break;
                     }
                 }
             }
             if (!$isScopeFound) {
                 $response = new Response(['error' => 'invalid_client', 'message' => 'Client authentication failed.'], 401);
                 $isError = true;
             }
         }
     }
     if ($isError) {
         $response->headers->set('Content-type', 'application/json');
         return $response;
     } else {
         // Put the identified client & scopes into request
         // for further app process
         $request->merge(['identified_oauth' => ['client' => $client, 'user' => $user, 'scopes' => $scopes]]);
     }
     return $next($request);
 }
 /**
  * The route responsible for giving user information
  *
  * @param Router $router
  * @param ResourceServer $resourceServer
  * @return \Response
  */
 private function userDetailsRoute(Router $router, ResourceServer $resourceServer)
 {
     $router->get(Config::get('laravel-oauth2-server.user_details_path'), function () use($resourceServer) {
         try {
             $accessToken = new AccessTokenEntity($resourceServer);
             $accessToken->setId(Request::input('access_token'));
             $resourceServer->isValidRequest(false, $accessToken);
             $session = $resourceServer->getSessionStorage()->getByAccessToken($accessToken);
             if (!($session->getOwnerType() === 'user' && $resourceServer->getAccessToken()->hasScope('uid'))) {
                 throw new AccessDeniedException();
             }
             return response()->json(['id' => $session->getOwnerId()]);
         } catch (InvalidRequestException $ire) {
             return response()->json(['error' => $ire->getCode(), 'message' => $ire->getMessage()], $ire->httpStatusCode);
         } catch (AccessDeniedException $acd) {
             return response()->json(['error' => $acd->getCode(), 'message' => $acd->getMessage()], $acd->httpStatusCode);
         } catch (Exception $e) {
             return response()->json(['error' => $e->getCode(), 'message' => $e->getMessage()], 500);
         }
     });
 }
Exemplo n.º 18
0
 /**
  * @param ResourceServer $resourceServer
  * @param EmitterInterface $emitter
  * @param string $ownerId
  */
 private function resourceServerWillReturnOwnerId(ResourceServer $resourceServer, EmitterInterface $emitter, $ownerId)
 {
     $resourceServer->getEventEmitter()->willReturn($emitter);
     $sessionEntity = new SessionEntity($resourceServer->getWrappedObject());
     $sessionEntity->setOwner('user', $ownerId);
     $accessTokenEntity = new AccessTokenEntity($resourceServer->getWrappedObject());
     $accessTokenEntity->setSession($sessionEntity);
     $resourceServer->getAccessToken()->willReturn($accessTokenEntity);
 }