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
 /**
  * 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.º 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) {
         $error = $e->errorType;
         $message = $e->getMessage();
         return response()->json(compact('error', 'message'), $e->httpStatusCode, $e->getHttpHeaders());
     }
 }
Exemplo n.º 4
0
 public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
 {
     try {
         $this->resourceServer->isValidRequest(true);
     } catch (AccessDeniedException $e) {
         throw new AuthenticationException(sprintf('OAuth token "%s" does not exist or is expired.', $token->getCredentials()));
     }
     $userIdentifier = $this->resourceServer->getAccessToken()->getSession()->getOwnerId();
     try {
         $user = $userProvider->loadUserByUsername($userIdentifier);
     } catch (UsernameNotFoundException $e) {
         $e->setUsername($userIdentifier);
         throw $e;
     }
     return new PreAuthenticatedToken($user, $token->getCredentials(), $providerKey, $user->getRoles());
 }
Exemplo n.º 5
0
 function it_throws_authentication_exception_when_user_could_not_be_loaded(ResourceServer $resourceServer, UserProviderInterface $userProvider, EmitterInterface $emitter)
 {
     $providerKey = 'default';
     $userIdentifier = '*****@*****.**';
     $token = new PreAuthenticatedToken('anon.', 'DDSHs55zpG51Mtxnt6H8vwn5fVJ230dF', $providerKey);
     $resourceServer->isValidRequest(true)->shouldBeCalled();
     $this->resourceServerWillReturnOwnerId($resourceServer, $emitter, $userIdentifier);
     $userProvider->loadUserByUsername($userIdentifier)->willThrow(UsernameNotFoundException::class);
     $this->shouldThrow(AuthenticationException::class)->during('authenticateToken', [$token, $userProvider, $providerKey]);
 }
Exemplo n.º 6
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;
     }
 }
Exemplo n.º 7
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.º 8
0
 /**
  * Validate a request with an access token in it.
  *
  * @param bool $httpHeadersOnly whether or not to check only the http headers of the request
  * @param string|null $accessToken an access token to validate
  *
  * @return mixed
  */
 public function validateAccessToken($httpHeadersOnly = false, $accessToken = null)
 {
     return $this->checker->isValidRequest($httpHeadersOnly, $accessToken);
 }
    // 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
        //403 = Forbidden
        $app = \Slim\Slim::getInstance();
        try {
            $authenticated = $resourceServer->isValidRequest(false);
            if ($authenticated === false) {
                $app->halt(401, 'Unauthorized');
            }
            //else {
            //if (!$resourceServer->getAccessToken()->hasScope($scope))
            //$app->halt(403, 'Forbidden');
            //}
        } catch (\League\OAuth2\Server\Exception\OAuthException $e) {
            $error = json_encode(['error' => $e->errorType, 'message' => $e->getMessage()]);
            $app->halt($e->httpStatusCode, $error);
        } catch (\League\OAuth2\Server\Exception\AccessDeniedException $e) {
            $error = json_encode(['error' => $e->errorType, 'message' => $e->getMessage()]);
            $app->halt($e->httpStatusCode, $error);
        } catch (\League\OAuth2\Server\Exception\InvalidRequestException $e) {
            $error = json_encode(['error' => $e->errorType, 'message' => $e->getMessage()]);
Exemplo n.º 10
0
 /**
  * @param bool        $headersOnly
  * @param null|string $accessToken
  *
  * @return bool
  * @throws \League\OAuth2\Server\Exception\AccessDeniedException
  */
 public function validateAccessToken($headersOnly = true, $accessToken = null)
 {
     return $this->resourceServer->isValidRequest($headersOnly, $accessToken);
 }
 function it_validates_an_access_token(ResourceServer $checker)
 {
     $checker->isValidRequest(false, null)->shouldBeCalled();
     $this->validateAccessToken(false, null);
 }
 /**
  * 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.º 13
0
    if (count($result) === 0) {
        throw new NotFoundException();
    }
    $user = ['username' => $result[0]['username'], 'name' => $result[0]['name']];
    if ($server->getAccessToken()->hasScope('email')) {
        $user['email'] = $result[0]['email'];
    }
    if ($server->getAccessToken()->hasScope('photo')) {
        $user['photo'] = $result[0]['photo'];
    }
    return new Response(json_encode($user));
});
$dispatcher = $router->getDispatcher();
try {
    // Check that access token is present
    $server->isValidRequest(false);
    // A successful response
    $response = $dispatcher->dispatch($request->getMethod(), $request->getPathInfo());
} catch (\Orno\Http\Exception $e) {
    // A failed response
    $response = $e->getJsonResponse();
    $response->setContent(json_encode(['status_code' => $e->getStatusCode(), 'message' => $e->getMessage()]));
} catch (\League\OAuth2\Server\Exception\OAuthException $e) {
    $response = new Response(json_encode(['error' => $e->errorType, 'message' => $e->getMessage()]), $e->httpStatusCode);
    foreach ($e->getHttpHeaders() as $header) {
        $response->headers($header);
    }
} catch (\Exception $e) {
    $response = new Orno\Http\Response();
    $response->setStatusCode(500);
    $response->setContent(json_encode(['status_code' => 500, 'message' => $e->getMessage()]));
Exemplo n.º 14
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);
 }