Beispiel #1
0
 public function __invoke(Request $request, Application $app)
 {
     /** @var EventDispatcherInterface $dispatcher */
     $dispatcher = $app['dispatcher'];
     $context = new Context(Context::CONTEXT_OAUTH2_TOKEN);
     $dispatcher->dispatch(PhraseaEvents::PRE_AUTHENTICATE, new PreAuthenticate($request, $context));
     $dispatcher->dispatch(PhraseaEvents::API_OAUTH2_START, new ApiOAuth2StartEvent());
     /** @var \API_OAuth2_Adapter $oauth2 */
     $oauth2 = $app['oauth2-server'];
     if (false === $this->verifyAccessToken($oauth2)) {
         $dispatcher->dispatch(PhraseaEvents::API_OAUTH2_END, new ApiOAuth2EndEvent());
         return null;
     }
     $token = $app['token'];
     if (!$token instanceof ApiOauthToken) {
         throw new NotFoundHttpException('Provided token is not valid.');
     }
     $this->getSession($app)->set('token', $token);
     $oAuth2Account = $token->getAccount();
     $oAuth2App = $oAuth2Account->getApplication();
     /** @var PropertyAccess $conf */
     $conf = $app['conf'];
     if ($oAuth2App->getClientId() == \API_OAuth2_Application_Navigator::CLIENT_ID && !$conf->get(['registry', 'api-clients', 'navigator-enabled'])) {
         return Result::createError($request, 403, 'The use of Phraseanet Navigator is not allowed')->createResponse();
     }
     if ($oAuth2App->getClientId() == \API_OAuth2_Application_OfficePlugin::CLIENT_ID && !$conf->get(['registry', 'api-clients', 'office-enabled'])) {
         return Result::createError($request, 403, 'The use of Office Plugin is not allowed.')->createResponse();
     }
     $authentication = $this->getAuthenticator($app);
     if ($authentication->isAuthenticated()) {
         $dispatcher->dispatch(PhraseaEvents::API_OAUTH2_END, new ApiOAuth2EndEvent());
         $this->registerClosingAccountCallback($dispatcher, $app);
         return null;
     }
     $authentication->openAccount($oAuth2Account->getUser());
     $oauth2->rememberSession($app['session']);
     $dispatcher->dispatch(PhraseaEvents::API_OAUTH2_END, new ApiOAuth2EndEvent());
     $this->registerClosingAccountCallback($dispatcher, $app);
     return null;
 }
 public function onSilexError(GetResponseForExceptionEvent $event)
 {
     $headers = [];
     $e = $event->getException();
     if ($e instanceof MethodNotAllowedHttpException) {
         $code = 405;
     } elseif ($e instanceof BadRequestHttpException) {
         $code = 400;
     } elseif ($e instanceof AccessDeniedHttpException) {
         $code = 403;
     } elseif ($e instanceof UnauthorizedHttpException) {
         $code = 401;
     } elseif ($e instanceof NotFoundHttpException) {
         $code = 404;
     } elseif ($e instanceof HttpExceptionInterface) {
         if (503 === $e->getStatusCode()) {
             $code = \API_V1_result::ERROR_MAINTENANCE;
         } else {
             if (406 === $e->getStatusCode()) {
                 $code = \API_V1_result::ERROR_UNACCEPTABLE;
             } else {
                 $code = 500;
             }
         }
     } else {
         $code = 500;
     }
     if ($e instanceof HttpExceptionInterface) {
         $headers = $e->getHeaders();
     }
     $response = Result::createError($event->getRequest(), $code, $e->getMessage())->createResponse();
     $response->headers->set('X-Status-Code', $response->getStatusCode());
     foreach ($headers as $key => $value) {
         $response->headers->set($key, $value);
     }
     $event->setResponse($response);
 }
 public function onSilexError(GetResponseForExceptionEvent $event)
 {
     $headers = [];
     $e = $event->getException();
     if ($e instanceof MethodNotAllowedHttpException) {
         $code = 405;
     } elseif ($e instanceof BadRequestHttpException) {
         $code = 400;
     } elseif ($e instanceof AccessDeniedHttpException) {
         $code = 403;
     } elseif ($e instanceof UnauthorizedHttpException) {
         $code = 401;
     } elseif ($e instanceof NotFoundHttpException) {
         $code = 404;
     } elseif ($e instanceof HttpExceptionInterface) {
         if (in_array($e->getStatusCode(), [400, 401, 403, 404, 405, 406, 503])) {
             $code = $e->getStatusCode();
         } else {
             $code = 500;
         }
     } else {
         $code = 500;
     }
     if ($code == 500) {
         $this->logger->error($e->getMessage(), ['code' => $e->getCode(), 'trace' => $e->getTrace()]);
     }
     if ($e instanceof HttpExceptionInterface) {
         $headers = $e->getHeaders();
     }
     $response = Result::createError($event->getRequest(), $code, $e->getMessage())->createResponse();
     $response->headers->set('X-Status-Code', $response->getStatusCode());
     foreach ($headers as $key => $value) {
         $response->headers->set($key, $value);
     }
     $event->setResponse($response);
 }
Beispiel #4
0
 private function assertErrorMessage(Result $apiResult, $code, $type, $message, $detail)
 {
     $response = json_decode($apiResult->createResponse()->getContent());
     $this->checkResponseFieldMeta($response, 'http_code', $code, \PHPUnit_Framework_Constraint_IsType::TYPE_INT);
     if (is_null($type)) {
         $this->assertObjectHasAttribute('error_type', $response->meta);
         $this->assertNull($response->meta->error_type);
     } else {
         $this->checkResponseFieldMeta($response, 'error_type', $type, \PHPUnit_Framework_Constraint_IsType::TYPE_STRING);
     }
     if (is_null($message)) {
         $this->assertObjectHasAttribute('error_message', $response->meta);
         $this->assertNull($response->meta->error_message);
     } else {
         $this->checkResponseFieldMeta($response, 'error_message', $message, \PHPUnit_Framework_Constraint_IsType::TYPE_STRING);
     }
     if (is_null($detail)) {
         $this->assertObjectHasAttribute('error_details', $response->meta);
         $this->assertNull($response->meta->error_details);
     } else {
         $this->checkResponseFieldMeta($response, 'error_details', $detail, \PHPUnit_Framework_Constraint_IsType::TYPE_STRING);
     }
 }
Beispiel #5
0
            $request->setRequestFormat(Result::FORMAT_JSONP);
        } else {
            $request->setRequestFormat($request->getFormat($format->getValue()));
        }
        // tells whether asked format is extended or not
        $request->attributes->set('_extended', in_array($request->getRequestFormat(Result::FORMAT_JSON), array(Result::FORMAT_JSON_EXTENDED, Result::FORMAT_YAML_EXTENDED, Result::FORMAT_JSONP_EXTENDED)));
    }, PhraseaApplication::EARLY_EVENT);
    $app->after(function (Request $request, Response $response) use($app) {
        if ($request->getRequestFormat(Result::FORMAT_JSON) === Result::FORMAT_JSONP && !$response->isOk() && !$response->isServerError()) {
            $response->setStatusCode(200);
        }
        // set response content type
        if (!$response->headers->get('Content-Type')) {
            $response->headers->set('Content-Type', $request->getMimeType($request->getRequestFormat(Result::FORMAT_JSON)));
        }
    });
    $app->get('/api/', function (Request $request, SilexApplication $app) {
        return Result::create($request, ['name' => $app['conf']->get(['registry', 'general', 'title']), 'type' => 'phraseanet', 'description' => $app['conf']->get(['registry', 'general', 'description']), 'documentation' => 'https://docs.phraseanet.com/Devel', 'versions' => ['1' => ['number' => V1::VERSION, 'uri' => '/api/v1/', 'authenticationProtocol' => 'OAuth2', 'authenticationVersion' => 'draft#v9', 'authenticationEndPoints' => ['authorization_token' => '/api/oauthv2/authorize', 'access_token' => '/api/oauthv2/token']]]])->createResponse();
    });
    $app->mount('/api/oauthv2', new Oauth2());
    $app->mount('/api/v1', new V1());
    $app['dispatcher'] = $app->share($app->extend('dispatcher', function ($dispatcher, PhraseaApplication $app) {
        $dispatcher->addSubscriber(new ApiOauth2ErrorsSubscriber($app['phraseanet.exception_handler'], $app['translator']));
        return $dispatcher;
    }));
    $app->after(function (Request $request, Response $response) use($app) {
        $app['dispatcher']->dispatch(PhraseaEvents::API_RESULT, new ApiResultEvent($request, $response));
    });
    $app['dispatcher']->addSubscriber(new ApiCorsSubscriber($app));
    return $app;
}, isset($environment) ? $environment : PhraseaApplication::ENV_PROD);
Beispiel #6
0
 public function ensureCanMoveRecord(Request $request, Application $app)
 {
     $user = $app['session']->get('token')->getAccount()->getUser();
     $record = $app['phraseanet.appbox']->get_databox($request->attributes->get('databox_id'))->get_record($request->attributes->get('record_id'));
     if (!$app['acl']->get($user)->has_right('addrecord') && !$app['acl']->get($user)->has_right('deleterecord') || !$app['acl']->get($user)->has_right_on_base($record->get_base_id(), 'candeleterecord')) {
         return Result::createError($request, 401, 'You are not authorized')->createResponse();
     }
 }
Beispiel #7
0
 public function ensureCanMoveRecord(Request $request)
 {
     $user = $this->getApiAuthenticatedUser();
     $record = $this->findDataboxById($request->attributes->get('databox_id'))->get_record($request->attributes->get('record_id'));
     // TODO: Check comparison. seems to be a mismatch
     if (!$this->getAclForUser($user)->has_right('addrecord') && !$this->getAclForUser($user)->has_right('deleterecord') || !$this->getAclForUser($user)->has_right_on_base($record->getBaseId(), 'candeleterecord')) {
         return Result::createError($request, 401, 'You are not authorized')->createResponse();
     }
     return null;
 }