public function handleRequest(HttpRequest $request)
 {
     $response = NULL;
     try {
         $requestMethod = $request->getRequestMethod();
         if ("GET" !== $requestMethod && "POST" !== $requestMethod) {
             throw new TokenIntrospectionException("method_not_allowed", "invalid request method");
         }
         $parameters = "GET" === $requestMethod ? $request->getQueryParameters() : $request->getPostParameters();
         $response = new HttpResponse(200, "application/json");
         $response->setHeader('Cache-Control', 'no-store');
         $response->setHeader('Pragma', 'no-cache');
         $response->setContent(Json::enc($this->_introspectToken($parameters)));
     } catch (TokenIntrospectionException $e) {
         $response = new HttpResponse($e->getResponseCode(), "application/json");
         $response->setContent(Json::enc(array("error" => $e->getMessage(), "error_description" => $e->getDescription())));
         if ("method_not_allowed" === $e->getMessage()) {
             $response->setHeader("Allow", "GET,POST");
         }
         if (NULL !== $this->_logger) {
             $this->_logger->logFatal($e->getLogMessage(TRUE) . PHP_EOL . $request . PHP_EOL . $response);
         }
     }
     return $response;
 }
 public function testHttpResponseEmptyResponseFromFile()
 {
     $h = HttpResponse::fromFile($this->_filePath . DIRECTORY_SEPARATOR . "empty_response.txt");
     $this->assertEquals(200, $h->getStatusCode());
     $this->assertEquals("text/html", $h->getContentType());
     $this->assertEquals("", $h->getContent());
 }
use RestService\Http\HttpRequest;
use RestService\Http\IncomingHttpRequest;
use OAuth\Authorize;
use RestService\Http\HttpResponse;
$logger = NULL;
$request = NULL;
$response = NULL;
try {
    $config = new Config(dirname(__DIR__) . DIRECTORY_SEPARATOR . "config" . DIRECTORY_SEPARATOR . "oauth.ini");
    $logger = new Logger($config->getSectionValue('Log', 'logLevel'), $config->getValue('serviceName'), $config->getSectionValue('Log', 'logFile'), $config->getSectionValue('Log', 'logMail', FALSE));
    $a = new Authorize($config, $logger);
    $request = HttpRequest::fromIncomingHttpRequest(new IncomingHttpRequest());
    $response = $a->handleRequest($request);
} catch (Exception $e) {
    // internal server error, inform resource owner through browser
    $response = new HttpResponse(500);
    $loader = new \Twig_Loader_Filesystem(dirname(__DIR__) . DIRECTORY_SEPARATOR . "views");
    $twig = new \Twig_Environment($loader);
    $output = $twig->render("error.twig", array("statusCode" => $response->getStatusCode(), "statusReason" => $response->getStatusReason(), "errorMessage" => $e->getMessage()));
    $response->setContent($output);
    if (NULL !== $logger) {
        $logger->logFatal($e->getMessage() . PHP_EOL . $request . PHP_EOL . $response);
    }
}
if (NULL !== $logger) {
    $logger->logDebug($request);
}
if (NULL !== $logger) {
    $logger->logDebug($response);
}
if (NULL !== $response) {
Esempio n. 4
0
    $request->matchRest("POST", "/hello/:str", function ($str) use(&$response) {
        if ("foo" === $str) {
            // it would make more sense to create something like an ApiException
            // class that would return the code 400 "Bad Request" instead of
            // internal server error as this is a 'mistake' by the client...
            throw new Exception("you cannot say 'foo'!'");
        }
        $response = new HttpResponse(200, "application/json");
        $response->setContent(Json::enc(array("type" => "POST", "response" => "hello " . $str)));
    });
    $request->matchRestDefault(function ($methodMatch, $patternMatch) use($request, &$response) {
        // methodMatch contains all the used request methods 'registrered'
        // through the matchRest method calls above, in this case GET and POST
        //
        // patternMatch indicates (boolean) whether or not the request URL
        // matches any of the patterns 'registered' through the matchRest
        // methods above...
        if (!in_array($request->getRequestMethod(), $methodMatch)) {
            $response = new HttpResponse(405, "application/json");
            $response->setHeader("Allow", implode(",", $methodMatch));
            $response->setContent(Json::enc(array("error" => "method_not_allowed", "error_description" => "request method not allowed")));
        } elseif (!$patternMatch) {
            $response = new HttpResponse(404, "application/json");
            $response->setContent(Json::enc(array("error" => "not_found", "error_description" => "resource not found")));
        }
    });
} catch (Exception $e) {
    $response = new HttpResponse(500, "application/json");
    $response->setContent(Json::enc(array("error" => "internal_server_error", "error_description" => $e->getMessage())));
}
$response->sendResponse();
Esempio n. 5
0
 public function handleRequest(HttpRequest $request)
 {
     $response = new HttpResponse(200, "application/json");
     try {
         if (!$this->_config->getSectionValue("Api", "enableApi")) {
             throw new ApiException("forbidden", "api disabled");
         }
         $this->_rs->verifyAuthorizationHeader($request->getHeader("Authorization"));
         $storage = $this->_storage;
         // FIXME: can this be avoided??
         $rs = $this->_rs;
         // FIXME: can this be avoided??
         $request->matchRest("POST", "/authorizations/", function () use($request, $response, $storage, $rs) {
             $rs->requireScope("authorizations");
             $data = Json::dec($request->getContent());
             if (NULL === $data || !is_array($data) || !array_key_exists("client_id", $data) || !array_key_exists("scope", $data)) {
                 throw new ApiException("invalid_request", "missing required parameters");
             }
             // client needs to exist
             $clientId = $data['client_id'];
             $client = $storage->getClient($clientId);
             if (FALSE === $client) {
                 throw new ApiException("invalid_request", "client is not registered");
             }
             // scope should be part of "allowed_scope" of client registration
             $clientAllowedScope = new Scope($client['allowed_scope']);
             $requestedScope = new Scope($data['scope']);
             if (!$requestedScope->isSubSetOf($clientAllowedScope)) {
                 throw new ApiException("invalid_request", "invalid scope for this client");
             }
             $refreshToken = array_key_exists("refresh_token", $data) && $data['refresh_token'] ? Utils::randomHex(16) : NULL;
             // check to see if an authorization for this client/resource_owner already exists
             if (FALSE === $storage->getApprovalByResourceOwnerId($clientId, $rs->getResourceOwnerId())) {
                 if (FALSE === $storage->addApproval($clientId, $rs->getResourceOwnerId(), $data['scope'], $refreshToken)) {
                     throw new ApiException("invalid_request", "unable to add authorization");
                 }
             } else {
                 throw new ApiException("invalid_request", "authorization already exists for this client and resource owner");
             }
             $response->setStatusCode(201);
             $response->setContent(Json::enc(array("ok" => true)));
         });
         $request->matchRest("GET", "/authorizations/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("authorizations");
             $data = $storage->getApprovalByResourceOwnerId($id, $rs->getResourceOwnerId());
             if (FALSE === $data) {
                 throw new ApiException("not_found", "the resource you are trying to retrieve does not exist");
             }
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("GET", "/authorizations/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("authorizations");
             $data = $storage->getApprovalByResourceOwnerId($id, $rs->getResourceOwnerId());
             if (FALSE === $data) {
                 throw new ApiException("not_found", "the resource you are trying to retrieve does not exist");
             }
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("DELETE", "/authorizations/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("authorizations");
             if (FALSE === $storage->deleteApproval($id, $rs->getResourceOwnerId())) {
                 throw new ApiException("not_found", "the resource you are trying to delete does not exist");
             }
             $response->setContent(Json::enc(array("ok" => true)));
         });
         $request->matchRest("GET", "/authorizations/", function () use($request, $response, $storage, $rs) {
             $rs->requireScope("authorizations");
             $data = $storage->getApprovals($rs->getResourceOwnerId());
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("GET", "/applications/", function () use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             // $rs->requireEntitlement("urn:x-oauth:entitlement:applications");    // do not require entitlement to list clients...
             $data = $storage->getClients();
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("DELETE", "/applications/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             $rs->requireEntitlement("urn:x-oauth:entitlement:applications");
             if (FALSE === $storage->deleteClient($id)) {
                 throw new ApiException("not_found", "the resource you are trying to delete does not exist");
             }
             $response->setContent(Json::enc(array("ok" => true)));
         });
         $request->matchRest("GET", "/applications/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             $rs->requireEntitlement("urn:x-oauth:entitlement:applications");
             // FIXME: for now require entitlement as long as password hashing is not
             // implemented...
             $data = $storage->getClient($id);
             if (FALSE === $data) {
                 throw new ApiException("not_found", "the resource you are trying to retrieve does not exist");
             }
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("POST", "/applications/", function () use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             $rs->requireEntitlement("urn:x-oauth:entitlement:applications");
             try {
                 $client = ClientRegistration::fromArray(Json::dec($request->getContent()));
                 $data = $client->getClientAsArray();
                 // check to see if an application with this id already exists
                 if (FALSE === $storage->getClient($data['id'])) {
                     if (FALSE === $storage->addClient($data)) {
                         throw new ApiException("invalid_request", "unable to add application");
                     }
                 } else {
                     throw new ApiException("invalid_request", "application already exists");
                 }
                 $response->setStatusCode(201);
                 $response->setContent(Json::enc(array("ok" => true)));
             } catch (ClientRegistrationException $e) {
                 throw new ApiException("invalid_request", $e->getMessage());
             }
         });
         $request->matchRest("GET", "/stats/", function () use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             $rs->requireEntitlement("urn:x-oauth:entitlement:applications");
             $data = $storage->getStats();
             $response->setContent(Json::enc($data));
         });
         $request->matchRest("PUT", "/applications/:id", function ($id) use($request, $response, $storage, $rs) {
             $rs->requireScope("applications");
             $rs->requireEntitlement("urn:x-oauth:entitlement:applications");
             try {
                 $client = ClientRegistration::fromArray(Json::dec($request->getContent()));
                 $data = $client->getClientAsArray();
                 if ($data['id'] !== $id) {
                     throw new ApiException("invalid_request", "resource does not match client id value");
                 }
                 if (FALSE === $storage->updateClient($id, $data)) {
                     throw new ApiException("invalid_request", "unable to update application");
                 }
             } catch (ClientRegistrationException $e) {
                 throw new ApiException("invalid_request", $e->getMessage());
             }
             $response->setContent(Json::enc(array("ok" => true)));
         });
         $request->matchRestDefault(function ($methodMatch, $patternMatch) use($request, $response) {
             if (in_array($request->getRequestMethod(), $methodMatch)) {
                 if (!$patternMatch) {
                     throw new ApiException("not_found", "resource not found");
                 }
             } else {
                 $response->setStatusCode(405);
                 $response->setHeader("Allow", implode(",", $methodMatch));
             }
         });
     } catch (ResourceServerException $e) {
         $response->setStatusCode($e->getResponseCode());
         if ("no_token" === $e->getMessage()) {
             // no authorization header is a special case, the client did not know
             // authentication was required, so tell it now without giving error message
             $hdr = 'Bearer realm="Resource Server"';
         } else {
             $hdr = sprintf('Bearer realm="Resource Server",error="%s",error_description="%s"', $e->getMessage(), $e->getDescription());
         }
         $response->setHeader("WWW-Authenticate", $hdr);
         $response->setContent(Json::enc(array("error" => $e->getMessage(), "error_description" => $e->getDescription())));
         if (NULL !== $this->_logger) {
             $this->_logger->logFatal($e->getLogMessage(TRUE) . PHP_EOL . $request . PHP_EOL . $response);
         }
     } catch (ApiException $e) {
         $response->setStatusCode($e->getResponseCode());
         $response->setContent(Json::enc(array("error" => $e->getMessage(), "error_description" => $e->getDescription())));
         if (NULL !== $this->_logger) {
             $this->_logger->logFatal($e->getLogMessage(TRUE) . PHP_EOL . $request . PHP_EOL . $response);
         }
     }
     return $response;
 }
Esempio n. 6
0
use RestService\Utils\Config;
use RestService\Http\IncomingHttpRequest;
use RestService\Http\HttpRequest;
use OAuth\Token;
use RestService\Utils\Logger;
use RestService\Utils\Json;
$logger = NULL;
$request = NULL;
$response = NULL;
try {
    $config = new Config(dirname(__DIR__) . DIRECTORY_SEPARATOR . "config" . DIRECTORY_SEPARATOR . "oauth.ini");
    $logger = new Logger($config->getSectionValue('Log', 'logLevel'), $config->getValue('serviceName'), $config->getSectionValue('Log', 'logFile'), $config->getSectionValue('Log', 'logMail', FALSE));
    $t = new Token($config, $logger);
    $request = HttpRequest::fromIncomingHttpRequest(new IncomingHttpRequest());
    $response = $t->handleRequest($request);
} catch (Exception $e) {
    $response = new HttpResponse(500, "application/json");
    $response->setContent(Json::enc(array("error" => $e->getMessage())));
    if (NULL !== $logger) {
        $logger->logFatal($e->getMessage() . PHP_EOL . $request . PHP_EOL . $response);
    }
}
if (NULL !== $logger) {
    $logger->logDebug($request);
}
if (NULL !== $logger) {
    $logger->logDebug($response);
}
if (NULL !== $response) {
    $response->sendResponse();
}
 public function handleRequest(HttpRequest $request)
 {
     $response = new HttpResponse(200);
     try {
         // hint the authentication layer about the user that wants to authenticate
         // if this information is available as a parameter to the authorize endpoint
         $resourceOwnerHint = $request->getQueryParameter("x_resource_owner_hint");
         if (null !== $resourceOwnerHint) {
             $this->_resourceOwner->setResourceOwnerHint($resourceOwnerHint);
         }
         switch ($request->getRequestMethod()) {
             case "GET":
                 $result = $this->_handleAuthorize($this->_resourceOwner, $request->getQueryParameters());
                 if (AuthorizeResult::ASK_APPROVAL === $result->getAction()) {
                     $loader = new \Twig_Loader_Filesystem(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . "views");
                     $twig = new \Twig_Environment($loader);
                     $redirectUri = new Uri($result->getClient()->getRedirectUri());
                     $output = $twig->render("askAuthorization.twig", array('serviceName' => $this->_config->getValue('serviceName'), 'serviceLogoUri' => $this->_config->getValue('serviceLogoUri', FALSE), 'serviceLogoWidth' => $this->_config->getValue('serviceLogoWidth', FALSE), 'serviceLogoHeight' => $this->_config->getValue('serviceLogoHeight', FALSE), 'resourceOwnerId' => $this->_resourceOwner->getId(), 'sslEnabled' => "https" === $request->getRequestUri()->getScheme(), 'contactEmail' => $result->getClient()->getContactEmail(), 'scopes' => $result->getScope()->getScopeAsArray(), 'clientDomain' => $redirectUri->getHost(), 'clientName' => $result->getClient()->getName(), 'clientId' => $result->getClient()->getId(), 'clientDescription' => $result->getClient()->getDescription(), 'clientIcon' => $result->getClient()->getIcon(), 'redirectUri' => $redirectUri->getUri()));
                     $response->setContent($output);
                 } elseif (AuthorizeResult::REDIRECT === $result->getAction()) {
                     $response->setStatusCode(302);
                     $response->setHeader("Location", $result->getRedirectUri()->getUri());
                 } else {
                     // should never happen...
                     throw new \Exception("invalid authorize result");
                 }
                 break;
             case "POST":
                 // CSRF protection, check the referrer, it should be equal to the
                 // request URI
                 $fullRequestUri = $request->getRequestUri()->getUri();
                 $referrerUri = $request->getHeader("HTTP_REFERER");
                 if ($fullRequestUri !== $referrerUri) {
                     throw new ResourceOwnerException("csrf protection triggered, referrer does not match request uri");
                 }
                 $result = $this->_handleApprove($this->_resourceOwner, $request->getQueryParameters(), $request->getPostParameters());
                 if (AuthorizeResult::REDIRECT !== $result->getAction()) {
                     // FIXME: this is dead code?
                     throw new ResourceOwnerException("approval not found");
                 }
                 $response->setStatusCode(302);
                 $response->setHeader("Location", $result->getRedirectUri()->getUri());
                 break;
             default:
                 // method not allowed
                 $response->setStatusCode(405);
                 $response->setHeader("Allow", "GET, POST");
                 break;
         }
     } catch (ClientException $e) {
         // tell the client about the error
         $client = $e->getClient();
         if ($client['type'] === "user_agent_based_application") {
             $separator = "#";
         } else {
             $separator = FALSE === strpos($client['redirect_uri'], "?") ? "?" : "&";
         }
         $parameters = array("error" => $e->getMessage(), "error_description" => $e->getDescription());
         if (NULL !== $e->getState()) {
             $parameters['state'] = $e->getState();
         }
         $response->setStatusCode(302);
         $response->setHeader("Location", $client['redirect_uri'] . $separator . http_build_query($parameters));
         if (NULL !== $this->_logger) {
             $this->_logger->logFatal($e->getLogMessage(TRUE) . PHP_EOL . $request . PHP_EOL . $response);
         }
     } catch (ResourceOwnerException $e) {
         // tell resource owner about the error (through browser)
         $response->setStatusCode(400);
         $loader = new \Twig_Loader_Filesystem(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . "views");
         $twig = new \Twig_Environment($loader);
         $output = $twig->render("error.twig", array("statusCode" => $response->getStatusCode(), "statusReason" => $response->getStatusReason(), "errorMessage" => $e->getMessage()));
         $response->setContent($output);
         if (NULL !== $this->_logger) {
             $this->_logger->logFatal($e->getMessage() . PHP_EOL . $request . PHP_EOL . $response);
         }
     }
     return $response;
 }
Esempio n. 8
0
 public function handleRequest(HttpRequest $request)
 {
     $response = new HttpResponse(200, "application/json");
     try {
         if ("POST" !== $request->getRequestMethod()) {
             // method not allowed
             $response->setStatusCode(405);
             $response->setHeader("Allow", "POST");
         } else {
             $response->setHeader('Content-Type', 'application/json');
             $response->setHeader('Cache-Control', 'no-store');
             $response->setHeader('Pragma', 'no-cache');
             $response->setContent(Json::enc($this->_handleToken($request->getPostParameters(), $request->getBasicAuthUser(), $request->getBasicAuthPass())));
         }
     } catch (TokenException $e) {
         if ($e->getResponseCode() === 401) {
             $response->setHeader("WWW-Authenticate", 'Basic realm="OAuth Server"');
         }
         $response->setStatusCode($e->getResponseCode());
         $response->setHeader('Cache-Control', 'no-store');
         $response->setHeader('Pragma', 'no-cache');
         $response->setContent(Json::enc(array("error" => $e->getMessage(), "error_description" => $e->getDescription())));
         if (NULL !== $this->_logger) {
             $this->_logger->logFatal($e->getLogMessage(TRUE) . PHP_EOL . $request . PHP_EOL . $response);
         }
     }
     return $response;
 }
Esempio n. 9
0
use RestService\Utils\Config;
use RestService\Http\IncomingHttpRequest;
use RestService\Http\HttpRequest;
use RestService\Utils\Logger;
use OAuth\Api;
use RestService\Utils\Json;
$logger = NULL;
$request = NULL;
$response = NULL;
try {
    $config = new Config(dirname(__DIR__) . DIRECTORY_SEPARATOR . "config" . DIRECTORY_SEPARATOR . "oauth.ini");
    $logger = new Logger($config->getSectionValue('Log', 'logLevel'), $config->getValue('serviceName'), $config->getSectionValue('Log', 'logFile'), $config->getSectionValue('Log', 'logMail', FALSE));
    $a = new Api($config, $logger);
    $request = HttpRequest::fromIncomingHttpRequest(new IncomingHttpRequest());
    $response = $a->handleRequest($request);
} catch (Exception $e) {
    $response = new HttpResponse(500, "application/json");
    $response->setContent(Json::enc(array("error" => "internal_server_error", "error_description" => $e->getMessage())));
    if (NULL !== $logger) {
        $logger->logFatal($e->getMessage() . PHP_EOL . $request . PHP_EOL . $response);
    }
}
if (NULL !== $logger) {
    $logger->logDebug($request);
}
if (NULL !== $logger) {
    $logger->logDebug($response);
}
if (NULL !== $response) {
    $response->sendResponse();
}