evolution rest api

This commit is contained in:
afornerot 2020-09-24 16:18:15 +02:00
parent 68239f469d
commit 0c10081907
4 changed files with 412 additions and 71 deletions

View File

@ -0,0 +1,106 @@
<?php
namespace Cadoles\CoreBundle\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpKernel\KernelInterface;
use Doctrine\DBAL\Connection as DBALConnection;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Validator\Constraints\DateTime;
use Cadoles\CoreBundle\Entity\Registration;
class TestRestCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
private $byexec;
protected function configure()
{
$this
->setName('Core:TestRest')
->setDescription('Test REST API Ninegate')
->setHelp('Test REST API Ninegate')
->addArgument('login', InputArgument::OPTIONAL, 'uid du user à tester')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->container = $this->getApplication()->getKernel()->getContainer();
$this->em = $this->container->get('doctrine')->getEntityManager();
$this->output = $output;
// Récupérer le login à interroger
$login = $input->getArgument('login');
if($login=="") $login="admin";
// Récuper la clé d'API
$masterapikey = $this->container->getParameter('apikeyninegate');
// Recherche des élèments de masterIdentify
$headers = ['Accept' => 'application/json'];
// Localisation du ninegate
$url = "https://".$this->container->getParameter("weburl")."/".$this->container->getParameter("alias");
// rest/user/{login}
// Récupération des informations utilisateurs issus du masteridentity
// key = parametre obligatoire
// key = clé d'accès du l'api
// only = paramétre optionnel
// only = liste des informations désirés = user, items, bookmarks, groups, alerts
$apiurl = $url."/rest/user/".$login;
$this->writeln($apiurl);
$response = \Unirest\Request::post($apiurl,$headers,["key"=>$masterapikey,"only"=>"user,items"]);
dump($response->body);
$this->writeln('');
return 1;
// rest/bookmark/add
// Ajout d'un item ninegate existant comme bookmark d'un utilisateur
// key = parametre obligatoire
// key = clé d'accès du l'api
// login = parametre obligatoire
// login = uid de l'utilisateur sur lequel on souhaite ajouter un bookmark
// iditem = parametre obligatoire
// iditem = id de l'item ninegate qui doit etre ajouté en tant que bookmark
$apiurl = $url."/rest/bookmark/add";
$this->writeln($apiurl);
$response = \Unirest\Request::post($apiurl,$headers,["key"=>$masterapikey,"login"=>"admin","iditem"=>3]);
$idbookmark=$response->body;
dump($response->body);
// rest/bookmark/del
// Ajout d'un item ninegate existant comme bookmark d'un utilisateur
// key = parametre obligatoire
// key = clé d'accès du l'api
// idbookmark = parametre obligatoire
// idbookmark = id du bookmark à supprimer
$apiurl = $url."/rest/bookmark/del";
$this->writeln($apiurl);
$response = \Unirest\Request::post($apiurl,$headers,["key"=>$masterapikey,"idbookmark"=>$idbookmark]);
$idbookmark=$response->body;
dump($response->body);
$this->writeln('');
return 1;
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
}
private function writeln($string) {
$this->output->writeln($string);
}
}

View File

@ -3,32 +3,17 @@
namespace Cadoles\CoreBundle\Controller; namespace Cadoles\CoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Form\FormError;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Cadoles\CoreBundle\Entity\User;
use Cadoles\CoreBundle\Entity\UserGroup;
use Cadoles\CoreBundle\Entity\UserModo;
use Cadoles\CoreBundle\Entity\Niveau01;
use Cadoles\CoreBundle\Entity\Niveau02;
use Cadoles\WebsocketBundle\Entity\Message;
use Cadoles\CoreBundle\Form\UserType;
use Cadoles\PortalBundle\Entity\Bookmark;
class RestController extends Controller class RestController extends Controller
{ {
// rest/login
// Permet de tester l'accès à ninegate
// key = parametre obligatoire
// key = clé d'accès de l'api
public function loginAction(Request $request) public function loginAction(Request $request)
{ {
$key=$request->get('key'); $key=$request->get('key');
@ -44,9 +29,16 @@ class RestController extends Controller
return new Response(json_encode($output), 200); return new Response(json_encode($output), 200);
} }
// rest/user/{login}
// Récupération des informations utilisateurs issus du masteridentity
// key = parametre obligatoire
// key = clé d'accès de l'api
// only = paramétre optionnel
// only = liste des informations désirés = user, items, bookmarks, groups, alerts
public function userAction($login, Request $request) public function userAction($login, Request $request)
{ {
$key=$request->get('key'); $key=$request->get('key');
$only=($request->get('only')?explode(",",$request->get('only')):"");
// Vérification de la clé // Vérification de la clé
$realkey = $this->getParameter("apikeyninegate"); $realkey = $this->getParameter("apikeyninegate");
@ -66,11 +58,13 @@ class RestController extends Controller
} }
// Format de sortie // Format de sortie
$output["user"] = []; if($only==""||in_array("user",$only)) $output["user"] = [];
$output["bookmarks"] = []; if($only==""||in_array("bookmarks",$only)) $output["bookmarks"] = [];
$output["items"] = []; if($only==""||in_array("items",$only)) $output["items"] = [];
$output["itemcategorys"] = []; if($only==""||in_array("items",$only)) $output["itemcategorys"] = [];
$output["groups"] = []; if($only==""||in_array("groups",$only)) $output["groups"] = [];
if($only==""||in_array("alerts",$only)) $output["alerts"] = [];
if($only==""||in_array("alerts",$only)) $output["alertcategorys"] = [];
$bookmarks=null; $bookmarks=null;
$items=null; $items=null;
@ -78,74 +72,112 @@ class RestController extends Controller
$weburl="https://".$this->getParameter("weburl")."/".$this->getParameter("alias")."/"; $weburl="https://".$this->getParameter("weburl")."/".$this->getParameter("alias")."/";
$em->getRepository("CadolesPortalBundle:Item")->getUserItems($user,$bookmarks,$items,$itemcategorys,null,3); $em->getRepository("CadolesPortalBundle:Item")->getUserItems($user,$bookmarks,$items,$itemcategorys,null,3);
$this->getDoctrine()->getRepository("CadolesPortalBundle:Page")->getPagesUser($user,null,$entity,$pagesuser,$pagesadmin,$groupsshared); //$this->getDoctrine()->getRepository("CadolesPortalBundle:Page")->getPagesUser($user,null,$entity,$pagesuser,$pagesadmin,$groupsshared);
// Construction de la réponse // Construction de la réponse
$output["user"]["firstname"] = $user->getFirstname(); if($only==""||in_array("user",$only)) {
$output["user"]["lastname"] = $user->getLastname(); $output["user"]["firstname"] = $user->getFirstname();
$output["user"]["email"] = $user->getEmail(); $output["user"]["lastname"] = $user->getLastname();
$output["user"]["avatar"] = $weburl."uploads/avatar/".$user->getAvatar(); $output["user"]["email"] = $user->getEmail();
$output["user"]["niveau01"] = $user->getNiveau01()->getLabel(); $output["user"]["avatar"] = $weburl."uploads/avatar/".$user->getAvatar();
$output["user"]["niveau02"] = ($user->getNiveau02()?$user->getNiveau02()->getLabel():null); $output["user"]["niveau01"] = $user->getNiveau01()->getLabel();
$output["user"]["role"] = $user->getRole(); $output["user"]["niveau02"] = ($user->getNiveau02()?$user->getNiveau02()->getLabel():null);
$output["user"]["role"] = $user->getRole();
}
if($bookmarks) { if($only==""||in_array("bookmarks",$only)) {
foreach($bookmarks as $bookmark) { if($bookmarks) {
$tmp=[]; foreach($bookmarks as $bookmark) {
$tmp["id"] = $bookmark->getId(); $tmp=[];
$tmp["title"] = $bookmark->getTitle(); $tmp["id"] = $bookmark->getId();
$tmp["url"] = $bookmark->getUrl(); $tmp["title"] = $bookmark->getTitle();
$tmp["target"] = $bookmark->getTarget(); $tmp["url"] = $bookmark->getUrl();
$tmp["order"] = 0; $tmp["target"] = $bookmark->getTarget();
$tmp["color"] = ($bookmark->getColor()?$bookmark->getColor():$this->get('session')->get('color')["main"]); $tmp["order"] = 0;
$tmp["icon"] = $weburl.($bookmark->getIcon()?$bookmark->getIcon()->getLabel():"uploads/icon/icon_pin.png"); $tmp["color"] = ($bookmark->getColor()?$bookmark->getColor():$this->get('session')->get('color')["main"]);
$tmp["icon"] = $weburl.($bookmark->getIcon()?$bookmark->getIcon()->getLabel():"uploads/icon/icon_pin.png");
array_push($output["bookmarks"],$tmp); array_push($output["bookmarks"],$tmp);
}
} }
} }
if($items) { if($only==""||in_array("items",$only)) {
foreach($items as $item) { if($items) {
$tmp=[]; foreach($items as $item) {
$tmp["id"] = $item->getId(); $tmp=[];
$tmp["title"] = $item->getTitle(); $tmp["id"] = $item->getId();
$tmp["url"] = $item->getUrl(); $tmp["title"] = $item->getTitle();
$tmp["target"] = $item->getTarget(); $tmp["url"] = $item->getUrl();
$tmp["order"] = $item->getRoworder(); $tmp["target"] = $item->getTarget();
$tmp["color"] = ($item->getColor()?$item->getColor():$this->get('session')->get('color')["main"]); $tmp["order"] = $item->getRoworder();
$tmp["icon"] = $weburl.($item->getIcon()?$item->getIcon()->getLabel():"uploads/icon/icon_pin.png"); $tmp["color"] = ($item->getColor()?$item->getColor():$this->get('session')->get('color')["main"]);
$tmp["essential"] = $item->getEssential(); $tmp["icon"] = $weburl.($item->getIcon()?$item->getIcon()->getLabel():"uploads/icon/icon_pin.png");
$tmp["category"] = $item->getItemcategory()->getId(); $tmp["essential"] = $item->getEssential();
$tmp["category"] = $item->getItemcategory()->getId();
array_push($output["items"],$tmp); array_push($output["items"],$tmp);
}
}
if($itemcategorys) {
foreach($itemcategorys as $itemcategory) {
$tmp=[];
$tmp["id"] = $itemcategory->getId();
$tmp["title"] = $itemcategory->getLabel();
$tmp["order"] = $itemcategory->getRoworder();
$tmp["color"] = ($itemcategory->getColor()?$itemcategory->getColor():$this->get('session')->get('color')["main"]);
array_push($output["itemcategorys"],$tmp);
}
} }
} }
if($itemcategorys) { if($only==""||in_array("groups",$only)) {
foreach($itemcategorys as $itemcategory) { foreach($user->getGroups() as $usergroup) {
$tmp=[]; $tmp=[];
$tmp["id"] = $itemcategory->getId(); $tmp["id"] = $usergroup->getGroup()->getId();
$tmp["title"] = $itemcategory->getLabel(); $tmp["title"] = $usergroup->getGroup()->getLabel();
$tmp["order"] = $itemcategory->getRoworder();
$tmp["color"] = ($itemcategory->getColor()?$itemcategory->getColor():$this->get('session')->get('color')["main"]);
array_push($output["itemcategorys"],$tmp); array_push($output["groups"],$tmp);
} }
} }
foreach($user->getGroups() as $usergroup) { if($only==""||in_array("alerts",$only)) {
$tmp=[]; $alerts=$em->getRepository("CadolesPortalBundle:Alert")->getUserAlerts($user,null,null);
$tmp["id"] = $usergroup->getGroup()->getId(); foreach($alerts as $alert) {
$tmp["title"] = $usergroup->getGroup()->getLabel(); $tmp=[];
$tmp["id"] = $alert->getId();
$tmp["title"] = $alert->getTitle();
$tmp["order"] = $alert->getRoworder();
$tmp["category"] = $alert->getAlertcategory()->getId();
$tmp["description"] = $alert->getContent();
array_push($output["groups"],$tmp); array_push($output["alerts"],$tmp);
}
$alertcategorys=$em->getRepository("CadolesPortalBundle:Alertcategory")->findAll();
foreach($alertcategorys as $alertcategory) {
$tmp=[];
$tmp["id"] = $alertcategory->getId();
$tmp["title"] = $alertcategory->getLabel();
$tmp["color"] = ($alertcategory->getColor()?$alertcategory->getColor():$this->get('session')->get('color')["main"]);
$tmp["icon"] = $weburl.($alertcategory->getIcon()?$alertcategory->getIcon()->getLabel():"uploads/icon/icon_pin.png");
array_push($output["alertcategorys"],$tmp);
}
} }
// Retour // Retour
return new Response(json_encode($output), 200); return new Response(json_encode($output), 200);
} }
// rest/users
// Liste l'ensemble des utilisateurs de ninegate et retourne ses attributs
// key = parametre obligatoire
// key = clé d'accès de l'api
public function usersAction(Request $request) public function usersAction(Request $request)
{ {
$key=$request->get('key'); $key=$request->get('key');
@ -179,6 +211,10 @@ class RestController extends Controller
return new Response(json_encode($output), 200); return new Response(json_encode($output), 200);
} }
// rest/groups
// Liste l'ensemble des groupes de ninegate et retourne ses attributs ainsi que les membres des groupes en question
// key = parametre obligatoire
// key = clé d'accès de l'api
public function groupsAction(Request $request) public function groupsAction(Request $request)
{ {
$key=$request->get('key'); $key=$request->get('key');
@ -212,4 +248,107 @@ class RestController extends Controller
// Retour // Retour
return new Response(json_encode($output), 200); return new Response(json_encode($output), 200);
} }
// rest/bookmark/add
// Ajout d'un item ninegate existant comme bookmark d'un utilisateur
// key = parametre obligatoire
// key = clé d'accès de l'api
// login = parametre obligatoire
// login = uid de l'utilisateur sur lequel on souhaite ajouter un bookmark
// iditem = parametre obligatoire
// iditem = id de l'item ninegate qui doit etre ajouté en tant que bookmark
public function bookmarkaddAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$key=$request->get('key');
$login=$request->get('login');
$iditem=$request->get('iditem');
// Vérification de la clé
$realkey = $this->getParameter("apikeyninegate");
if($key!=$realkey) {
$output["error"]="error key";
return new Response(json_encode($output), 400);
}
// Tester présence des parametres
if(is_null($login)||is_null($iditem)) {
$output["error"]="missing parameter : login - iditem";
return new Response(json_encode($output), 400);
}
// Tester l'existance du login
$user=$em->getRepository('CadolesCoreBundle:User')->findOneBy(["username"=>$login]);
if(!$user) {
$output["error"]="user not exist";
return new Response(json_encode($output), 400);
}
// Tester l'existance de l'item
$item=$em->getRepository('CadolesPortalBundle:Item')->find($iditem);
if(!$item) {
$output["error"]="item not exist";
return new Response(json_encode($output), 400);
}
$bookmark = $em->getRepository('CadolesPortalBundle:Bookmark')->findOneBy(["user"=>$user,"item"=>$item]);
if(!$bookmark) {
$bookmark = new Bookmark();
$bookmark->setTitle($item->getTitle());
$bookmark->setSubtitle($item->getSubtitle());
$bookmark->setUrl($item->getUrl());
$bookmark->setIcon($item->getIcon());
$bookmark->setColor($item->getColor());
$bookmark->setTarget($item->getTarget());
$bookmark->setItem($item);
$bookmark->setUser($user);
$em->persist($bookmark);
$em->flush();
}
$output=$bookmark->getId();
return new Response(json_encode($output), 200);
}
// rest/bookmark/del
// Suppression d'un bookmark
// key = parametre obligatoire
// key = clé d'accès de l'api
// idbookmark = parametre obligatoire
// idbookmark = id du bookmark à supprimer
public function bookmarkdelAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$key=$request->get('key');
$idbookmark=$request->get('idbookmark');
// Vérification de la clé
$realkey = $this->getParameter("apikeyninegate");
if($key!=$realkey) {
$output["error"]="error key";
return new Response(json_encode($output), 400);
}
// Tester présence des parametres
if(is_null($idbookmark)) {
$output["error"]="missing parameter : idbookmark";
return new Response(json_encode($output), 400);
}
// Tester l'existance du bookmark
$bookmark=$em->getRepository('CadolesPortalBundle:Bookmark')->find($idbookmark);
if(!$bookmark) {
$output["error"]="bookmark not exist";
return new Response(json_encode($output), 400);
}
$em->remove($bookmark);
$em->flush();
$output=[];
return new Response(json_encode($output), 200);
}
} }

View File

@ -527,4 +527,12 @@ cadoles_core_rest_users:
cadoles_core_rest_groups: cadoles_core_rest_groups:
path: /rest/groups path: /rest/groups
defaults: { _controller: CadolesCoreBundle:Rest:groups } defaults: { _controller: CadolesCoreBundle:Rest:groups }
cadoles_core_rest_bookmark_add:
path: /rest/bookmark/add
defaults: { _controller: CadolesCoreBundle:Rest:bookmarkadd }
cadoles_core_rest_bookmark_del:
path: /rest/bookmark/del
defaults: { _controller: CadolesCoreBundle:Rest:bookmarkdel }

View File

@ -3,6 +3,7 @@
namespace Cadoles\PortalBundle\Repository; namespace Cadoles\PortalBundle\Repository;
use Doctrine\ORM\EntityRepository; use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Collections\ArrayCollection;
class AlertRepository extends EntityRepository class AlertRepository extends EntityRepository
{ {
@ -38,4 +39,91 @@ class AlertRepository extends EntityRepository
->getResult() ->getResult()
; ;
} }
public function getUserAlerts($user,$idalertcategory,$alertcategoryfilter) {
// Profilage
$roles=($user?$user->getRoles():["ROLE_ANONYME"]);
$niveau01=($user?$user->getNiveau01():null);
$groups=($user?$user->getGroups():[]);
// Initialisation du calcul des alerts
$alerts=new ArrayCollection();
// Récupération des alerts par rôles
foreach($roles as $role) {
$qb = $this->createQueryBuilder('a');
$qb->select('alert')
->from("CadolesPortalBundle:Alert", 'alert')
->where($qb->expr()->like('alert.roles', $qb->expr()->literal("%$role%")))
->andWhere('alert.publishedat <= :today')
->andWhere($qb->expr()->orX(
$qb->expr()->gt('alert.unpublishedat', ':today'),
$qb->expr()->isNull('alert.unpublishedat')
))
->setParameter('today', date('Y-m-d'));
if($idalertcategory && $alertcategoryfilter) {
$qb->andWhere("alert.alertcategory=:alertcategory")
->setParameter("alertcategory",$alertcategoryfilter);
}
$alertsroles=$qb->getQuery()->getResult();
foreach($alertsroles as $alertrole) {
if(!$alerts->contains($alertrole)&&!$alertrole->getReaders()->contains($user)) $alerts->add($alertrole);
}
}
// Récupération par Niveau01
$qb = $this->createQueryBuilder('a');
$qb->select('alert')
->from("CadolesPortalBundle:Alert", 'alert')
->where(":niveau01 MEMBER OF alert.niveau01s")
->andWhere('alert.publishedat <= :today')
->andWhere($qb->expr()->orX(
$qb->expr()->gt('alert.unpublishedat', ':today'),
$qb->expr()->isNull('alert.unpublishedat')
))
->setParameter("niveau01",$niveau01)
->setParameter('today', date('Y-m-d'));
if($idalertcategory && $alertcategoryfilter) {
$qb->andWhere("alert.alertcategory=:alertcategory")
->setParameter("alertcategory",$alertcategoryfilter);
}
$alertsniveau01s=$qb->getQuery()->getResult();
foreach($alertsniveau01s as $alertniveau01) {
if(!$alerts->contains($alertniveau01)&&!$alertniveau01->getReaders()->contains($user)) $alerts->add($alertniveau01);
}
// Récupération des alerts par group
foreach($groups as $group) {
$qb = $this->createQueryBuilder('a');
$qb->select('alert')
->from("CadolesPortalBundle:Alert", 'alert')
->where(":group MEMBER OF alert.groups")
->andWhere('alert.publishedat <= :today')
->andWhere($qb->expr()->orX(
$qb->expr()->gt('alert.unpublishedat', ':today'),
$qb->expr()->isNull('alert.unpublishedat')
))
->setParameter("group",$group->getGroup())
->setParameter('today', date('Y-m-d'));
if($idalertcategory && $alertcategoryfilter) {
$qb->andWhere("alert.alertcategory=:alertcategory")
->setParameter("alertcategory",$alertcategoryfilter);
}
$alertsgroups=$qb->getQuery()->getResult();
foreach($alertsgroups as $alertgroup) {
if(!$alerts->contains($alertgroup)&&!$alertgroup->getReaders()->contains($user)) $alerts->add($alertgroup);
}
}
// Trie des alerts
$alertsordered = $alerts->getIterator();
$alertsordered->uasort(function ($first, $second) {
return (int) $first->getRowOrder() > (int) $second->getRowOrder() ? 1 : -1;
});
return $alertsordered;
}
} }