Skip to content

Commit

Permalink
Adds API configuration. Close #28
Browse files Browse the repository at this point in the history
  • Loading branch information
seballot committed Oct 26, 2018
1 parent 9499092 commit 35dd784
Show file tree
Hide file tree
Showing 8 changed files with 183 additions and 74 deletions.
1 change: 0 additions & 1 deletion app/config/security.yml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,5 @@ security:
- { path: ^/admin/, role: [ROLE_SONATA_ADMIN] }
- { path: ^/user/, role: IS_AUTHENTICATED_REMEMBERED }
- { path: ^/duplicates/, role: [ROLE_ADMIN] }
- { path: ^/api/$, role: IS_AUTHENTICATED_REMEMBERED }
- { path: ^/api/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
6 changes: 6 additions & 0 deletions src/Biopen/CoreBundle/Admin/ConfigurationAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ protected function configureFormFields(FormMapper $formMapper)
->with("Entrez du code du code HTML (iframe par exemple) qui sera affichée sur la page d'accueil de l'interface admin")
->add('customDashboard', 'textarea', array('label' => 'Custom HTML code', 'attr' => ['rows' => '15'], 'required' => false))
->end()
->end()
->tab('API')
->with("Configurer les API (Utilisateurs avancés)")
->add('api.protectPublicApiWithToken', 'checkbox', array('label' => "Protéger l'api publique avec des jetons utilisateurs (i.e. besoin de créer un compte pour utiliser l'api publique)", 'required' => false))
->add('api.internalApiAuthorizedDomains', 'text', array('label' => "Liste des domaines externe qui utiliseront l'API interne. Mettez * si vous voulez que n'importe quel domaine puisse y avoir accès. Cette option est nécessaire si vous voulez afficher vos données avec GoGoCartoJs mais sur un autre serveur.", 'required' => false))
->end()
->end();
}
}
33 changes: 32 additions & 1 deletion src/Biopen/CoreBundle/Document/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use Biopen\CoreBundle\Document\Configuration\ConfigurationUser;
use Biopen\CoreBundle\Document\Configuration\ConfigurationMenu;
use Biopen\CoreBundle\Document\Configuration\ConfigurationInfobar;

use Biopen\CoreBundle\Document\Configuration\ConfigurationApi;

/**
* Main Configuration
Expand Down Expand Up @@ -403,6 +403,13 @@ class Configuration
/** @MongoDB\Field(type="string") */
protected $customDashboard = '';

// -------------------------
// --------- API -----------
// -------------------------

/** @MongoDB\EmbedOne(targetDocument="Biopen\CoreBundle\Document\Configuration\ConfigurationApi") */
protected $api;


public function __toString()
{
Expand Down Expand Up @@ -444,6 +451,7 @@ public function __construct()
$this->user = new ConfigurationUser();
$this->menu = new ConfigurationMenu();
$this->infobar = new ConfigurationInfobar();
$this->api = new ConfigurationApi();
}

/**
Expand Down Expand Up @@ -2816,4 +2824,27 @@ public function getSearchElementsFeature()
{
return $this->searchElementsFeature;
}

/**
* Set api
*
* @param Biopen\CoreBundle\Document\Configuration\ConfigurationApi $api
* @return $this
*/
public function setApi(\Biopen\CoreBundle\Document\Configuration\ConfigurationApi $api)
{
$this->api = $api;
return $this;
}

/**
* Get api
*
* @return Biopen\CoreBundle\Document\Configuration\ConfigurationApi $api
*/
public function getApi()
{
if(!$this->api) $this->api = new ConfigurationApi();
return $this->api;
}
}
59 changes: 59 additions & 0 deletions src/Biopen/CoreBundle/Document/Configuration/ConfigurationApi.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace Biopen\CoreBundle\Document\Configuration;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/** @MongoDB\EmbeddedDocument */
class ConfigurationApi
{
/** @MongoDB\Field(type="string") */
protected $internalApiAuthorizedDomains = null;

/** @MongoDB\Field(type="bool") */
protected $protectPublicApiWithToken = true;

/**
* Set internalApiAuthorizedDomains
*
* @param string $internalApiAuthorizedDomains
* @return $this
*/
public function setInternalApiAuthorizedDomains($internalApiAuthorizedDomains)
{
$this->internalApiAuthorizedDomains = $internalApiAuthorizedDomains;
return $this;
}

/**
* Get internalApiAuthorizedDomains
*
* @return string $internalApiAuthorizedDomains
*/
public function getInternalApiAuthorizedDomains()
{
return $this->internalApiAuthorizedDomains;
}

/**
* Set protectPublicApiWithToken
*
* @param bool $protectPublicApiWithToken
* @return $this
*/
public function setProtectPublicApiWithToken($protectPublicApiWithToken)
{
$this->protectPublicApiWithToken = $protectPublicApiWithToken;
return $this;
}

/**
* Get protectPublicApiWithToken
*
* @return bool $protectPublicApiWithToken
*/
public function getProtectPublicApiWithToken()
{
return $this->protectPublicApiWithToken;
}
}
105 changes: 57 additions & 48 deletions src/Biopen/GeoDirectoryBundle/Controller/APIController.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,32 +48,42 @@ public function getElementsAction(Request $request, $id = null, $_format = 'json
$token = $request->get('token');
$ontology = $request->get('ontology') ? strtolower($request->get('ontology')) : "gogofull";
$fullRepresentation = $jsonLdRequest || $ontology != "gogocompact";
$elementId = $id ? $id : $request->get('id');

$elementId = $id ? $id : $request->get('id');
$config = $em->getRepository('BiopenCoreBundle:Configuration')->findConfiguration();
$protectWithToken = $config->getApi()->getProtectPublicApiWithToken();
$apiUiUrl = $this->generateUrl('biopen_api_ui', [], UrlGeneratorInterface::ABSOLUTE_URL);

// allow ajax request from same host
if ($request->isXmlHttpRequest() && $this->requestFromSameHost($request))
if ($request->isXmlHttpRequest())
{
$isAdmin = $this->isUserAdmin();
$includeContact = true;
$includePrivateFields = true;
}
else if ($token) // otherwise API is protected by user token
else if (!$protectWithToken || $token) // otherwise API is protected by user token
{
$user = $em->getRepository('BiopenCoreBundle:User')->findOneByToken($token);
if (!$user) return new Response("The token you provided does not correspond to any existing user. Please visit " . $this->generateUrl('biopen_api_ui', [], UrlGeneratorInterface::ABSOLUTE_URL));
if ($protectWithToken)
{
$user = $em->getRepository('BiopenCoreBundle:User')->findOneByToken($token);
if (!$user) {
$response = "The token you provided does not correspond to any existing user. Please visit " . $apiUiUrl;
return $this->createResponse($response, $config);
}
}
$isAdmin = false;
$includeContact = false;
$includePrivateFields = false;
}
else
{
return new Response("You need to provide a token to access to this API. Please visit " . $this->generateUrl('biopen_api_ui', [], UrlGeneratorInterface::ABSOLUTE_URL));
$response = "You need to provide a token to access to this API. Please visit " . $apiUiUrl;
return $this->createResponse($response, $config);
}

$elementRepo = $em->getRepository('BiopenGeoDirectoryBundle:Element');

if ($elementId)
{
$element = $elementRepo->findOneBy(array('id' => $elementId));
$elementsJson = $element->getJson($includeContact, $isAdmin);
$elementsJson = $element->getJson($includePrivateFields, $isAdmin);
}
else
{
Expand All @@ -92,7 +102,7 @@ public function getElementsAction(Request $request, $id = null, $_format = 'json
{
$elementsFromDB = $elementRepo->findAllPublics($fullRepresentation, $isAdmin, $request);
}
$elementsJson = $this->encodeElementArrayToJsonArray($elementsFromDB, $fullRepresentation, $isAdmin, $includeContact);
$elementsJson = $this->encodeElementArrayToJsonArray($elementsFromDB, $fullRepresentation, $isAdmin, $includePrivateFields);
}

if ($jsonLdRequest)
Expand All @@ -114,10 +124,8 @@ public function getElementsAction(Request $request, $id = null, $_format = 'json
// $responseSize = strlen($elementsJson);
// $date = date('d/m/Y');

$result = new Response($responseJson);
$result->headers->set('Content-Type', 'application/json');
return $result;
}
return $this->createResponse($responseJson, $config);
}

public function getTaxonomyAction(Request $request, $id = null, $_format = 'json')
{
Expand All @@ -138,7 +146,6 @@ public function getTaxonomyAction(Request $request, $id = null, $_format = 'json
{
$dataJson = $em->getRepository('BiopenGeoDirectoryBundle:Taxonomy')->findTaxonomyJson($jsonLdRequest);
}


if ($jsonLdRequest)
$responseJson = '{
Expand All @@ -148,20 +155,22 @@ public function getTaxonomyAction(Request $request, $id = null, $_format = 'json
else
$responseJson = $dataJson;

$response = new Response($responseJson);
$response->headers->set('Content-Type', 'application/json');
return $response;
$config = $em->getRepository('BiopenCoreBundle:Configuration')->findConfiguration();
return $this->createResponse($responseJson, $config);
}

private function isJsonLdRequest($request, $_format)
{
return $_format == 'jsonld' || $request->headers->get('Accept') == 'application/ld+json';
}

private function requestFromSameHost($request)
private function createResponse($text, $config)
{
if (!(isset($_SERVER['HTTP_REFERER']) || empty($_SERVER['HTTP_REFERER']))) return false;
return strtolower(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST)) == strtolower($_SERVER['HTTP_HOST']);
$response = new Response($text);
if ($config->getApi()->getInternalApiAuthorizedDomains())
$response->headers->set('Access-Control-Allow-Origin', $config->getApi()->getInternalApiAuthorizedDomains());
$response->headers->set('Content-Type', 'application/json');
return $response;
}

public function getElementsFromTextAction(Request $request)
Expand All @@ -172,42 +181,43 @@ public function getElementsFromTextAction(Request $request)

$isAdmin = $this->isUserAdmin();

$elements = $em->getRepository('BiopenGeoDirectoryBundle:Element')
->findElementsWithText($request->get('text'), true, $isAdmin);

// $elements = array_filter($elements, function($value) {
// return (float) $value['score'] >= 0;
// });
$elements = $em->getRepository('BiopenGeoDirectoryBundle:Element')->findElementsWithText($request->get('text'), true, $isAdmin);

$elementsJson = $this->encodeElementArrayToJsonArray($elements, true, $isAdmin, true);
$responseJson = '{ "data":'. $elementsJson . ', "ontology" : "gogofull"}';

$response = new Response($responseJson);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
else
{
return new Response("Access to the API is restricted and not allowed via the browser");
$config = $em->getRepository('BiopenCoreBundle:Configuration')->findConfiguration();
return $this->createResponse($responseJson, $config);
}
else { return new Response("Access to the API is restricted and not allowed via the browser"); }
}

public function apiUiAction()
{
$em = $this->get('doctrine_mongodb')->getManager();
$options = $em->getRepository('BiopenGeoDirectoryBundle:Option')->findAll();
$config = $em->getRepository('BiopenCoreBundle:Configuration')->findConfiguration();
$protectPublicApiWithToken = $config->getApi()->getProtectPublicApiWithToken();

$securityContext = $this->get('security.context');
$userLoggued = $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED');

$user = $this->get('security.context')->getToken()->getUser();
if (!$user->getToken())
if ($protectPublicApiWithToken && !$userLoggued) {
$this->getRequest()->getSession()->set('_security.main.target_path', 'api');
return $this->redirectToRoute('fos_user_security_login');
}

if ($protectPublicApiWithToken)
{
$user->createToken();
$em->flush();
$user = $securityContext->getToken()->getUser();
if (!$user->getToken()) { $user->createToken(); $em->flush(); }
}

$options = $em->getRepository('BiopenGeoDirectoryBundle:Option')->findAll();
return $this->render('BiopenGeoDirectoryBundle:api:api-ui.html.twig', array('options' => $options));
}

public function getManifestAction() {
public function getManifestAction()
{
$em = $this->get('doctrine_mongodb')->getManager();
$config = $em->getRepository('BiopenCoreBundle:Configuration')->findConfiguration();
$img = $config->getFavicon() ? $config->getFavicon() : $config->getLogo();
Expand All @@ -229,9 +239,9 @@ public function getManifestAction() {
"background_color" => $config->getBackgroundColor(),
"icons" => [
[
"src" => $imgUrl,
"sizes" => $imageData->height().'x'.$imageData->width(),
"type" => $imageData->mime()
"src" => $imgUrl,
"sizes" => $imageData->height().'x'.$imageData->width(),
"type" => $imageData->mime()
]
]
);
Expand All @@ -249,19 +259,18 @@ private function isUserAdmin()
$isAdmin = $user && $user->isAdmin();
return $isAdmin;
}
return false;

return false;
}

private function encodeElementArrayToJsonArray($array, $fullRepresentation, $isAdmin = false, $includeContact = false)
private function encodeElementArrayToJsonArray($array, $fullRepresentation, $isAdmin = false, $includePrivateFields = false)
{
$elementsJson = '[';
foreach ($array as $key => $value)
{
if ($fullRepresentation == 'true')
{
$elementJson = $value['baseJson'];
if ($includeContact && $value['privateJson'] != '{}') {
if ($includePrivateFields && $value['privateJson'] != '{}') {
$elementJson = substr($elementJson , 0, -1) . ',' . substr($value['privateJson'],1);
}
if ($isAdmin && $value['adminJson'] != '{}') {
Expand Down
Loading

0 comments on commit 35dd784

Please sign in to comment.