Commit 39556e9ac73e95b0bd6ff3a36142d3f14f2501fd

Authored by Gabriela Mayoli
Committed by gabrielamayoli
1 parent 07a057ab
Exists in master and in 1 other branch 3.1

Primeiros testes do primeiro controller da nova coleta.

src/Cacic/RelatorioBundle/Resources/views/Hardware/rel_wmi.html.twig
... ... @@ -37,7 +37,7 @@
37 37 <td><a href="{{ path('cacic_relatorio_hardware_wmi_detalhe', {'classe': classe, 'propriedade': reg.nmPropertyName, 'local': reg.idLocal}) }}" title="{{ "Lista de computadores"|trans }}" target="_blank">{{ reg.nmLocal }}</a></td>
38 38 <td><a href="{{ path('cacic_relatorio_hardware_wmi_detalhe', {'classe': classe, 'propriedade': reg.nmPropertyName, 'rede': reg.idRede}) }}" title="{{ "Lista de computadores"|trans }}" target="_blank">{{ reg.nmRede }} / {{ reg.teIpRede }}</a></td>
39 39 <td><a href="{{ path('cacic_relatorio_hardware_wmi_detalhe', {'classe': classe, 'propriedade': reg.nmPropertyName}) }}" title="{{ "Lista de computadores"|trans }}" target="_blank">{{ reg.nmPropertyName }}</a></td>
40   - <td><a href="{{ path('cacic_relatorio_hardware_wmi_detalhe', {'classe': classe, 'propriedade': reg.nmPropertyName}) }}" title="{{ "Lista de computadores"|trans }}" target="_blank">{{ reg.numComp }}</a></td>
  40 + <td><a href="{{ path('cacic_relatorio_hardware_wmi_detalhe', {'classe': classe, 'propriedade': reg.nmPropertyName, 'so': reg.idSo, 'local': reg.idLocal, 'rede': reg.idRede}) }}" title="{{ "Lista de computadores"|trans }}" target="_blank">{{ reg.numComp }}</a></td>
41 41 <td>{{ reg.teClassPropertyValue }}</td>
42 42 </tr>
43 43 {% else %}
... ...
src/Cacic/WSBundle/Controller/NeoController.php 0 → 100644
... ... @@ -0,0 +1,232 @@
  1 +<?php
  2 +/**
  3 + * Created by PhpStorm.
  4 + * User: gabi
  5 + * Date: 25/07/14
  6 + * Time: 12:24
  7 + */
  8 +
  9 +namespace Cacic\WSBundle\Controller;
  10 +
  11 +use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  12 +use Symfony\Component\HttpFoundation\Request;
  13 +use Symfony\Component\HttpFoundation\JsonResponse;
  14 +use Symfony\Component\HttpFoundation\Session\Session;
  15 +use Symfony\Component\Serializer\Serializer;
  16 +use Symfony\Component\Serializer\Encoder\JsonEncoder;
  17 +use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
  18 +use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag;
  19 +
  20 +
  21 +class NeoController extends Controller {
  22 +
  23 + /**
  24 + * Método que retorna 200 em requisição na raiz
  25 + */
  26 +
  27 +
  28 + public function __construct($maxIdleTime = 1800)
  29 + {
  30 + $this->maxIdleTime = $maxIdleTime;
  31 + }
  32 +
  33 + public function indexAction(Request $request)
  34 + {
  35 + $logger = $this->get('logger');
  36 + //$logger->debug("222222222222222222222222222222222222 ");
  37 +
  38 + $response = new JsonResponse();
  39 +
  40 +
  41 + if ( $request->isMethod('POST') ) {
  42 + $response->setStatusCode(200);
  43 + } else {
  44 + $response->setStatusCode(403);
  45 + }
  46 +
  47 + return $response;
  48 + }
  49 +
  50 + /**
  51 + * Faz login do agente
  52 + */
  53 + public function loginAction(Request $request)
  54 + {
  55 + $logger = $this->get('logger');
  56 + $data = $request->getContent();
  57 +
  58 + // JSON Serialization
  59 + //$usuario = $serializer->deserialize($data, 'Usuario', 'json');
  60 + $usuario = json_decode($data);
  61 + $logger->debug("JSON login received data".print_r($usuario, true));
  62 + $_SERVER['SERVER_ADDR'] = $this->getRequest()->getUri();
  63 +
  64 + $auth = $this->forward('CacicCommonBundle:Security:login', array(
  65 + 'username' => $usuario->user,
  66 + 'password' => $usuario->senha,
  67 + ));
  68 +
  69 + $session = $request->getSession();
  70 +
  71 + $auth->setContent(json_encode(array(
  72 + 'session' => $session->getId()
  73 + )));
  74 +
  75 + return $auth;
  76 + }
  77 +
  78 + /**
  79 + * Controller só para testar a validação da sessão
  80 + */
  81 +
  82 + public function checkSessionAction(Request $request)
  83 + {
  84 + $logger = $this->get('logger');
  85 + $data = $request->getContent();
  86 + $response = new JsonResponse();
  87 + $session = $request->getSession();
  88 + if (empty($session)) {
  89 + $response->setStatusCode('401');
  90 + }
  91 + $session_valid = $this->checkSession($session);
  92 + if ($session_valid) {
  93 + $response->setStatusCode('200');
  94 + } else {
  95 + $response->setStatusCode('401');
  96 + }
  97 +
  98 + return $response;
  99 + }
  100 +
  101 + public function getTestAction(Request $request)
  102 + {
  103 + //1 - Verificar se computador existe
  104 + $logger = $this->get('logger');
  105 + $status = $request->getContent();
  106 + $em = $this->getDoctrine()->getManager();
  107 +
  108 + $response = new JsonResponse();
  109 + $dados = json_decode($status);
  110 + $logger->debug("JSON get Test status".print_r($dados, true));
  111 +
  112 + $so_json = $dados['so'];
  113 +
  114 + $rede_json = $dados['rede'];
  115 + $rede1 = $rede_json[0];
  116 + $mac_json = $rede1['mac'];
  117 + $rede = $rede1['interface'];
  118 +
  119 + $so = $em->getRepository('CacicCommonBundle:So')->findOneBy(array('te_so' => $so_json));
  120 + $mac = $em->getRepository('CacicCommonBundle:Computador')->findOneBy(array('te_node_address'=> $mac_json));
  121 + $logger->debug("$so".print_r($so, true));
  122 + $logger->debug("$mac".print_r($mac, true));
  123 +
  124 + // Regra: MAC e SO são únicos e não podem ser nulos
  125 + $computador = $em->findOneBy( array( 'te_node_address'=> $mac, 'te_so'=> $so->getTeSo()) );
  126 + $data = new \DateTime('NOW'); //armazena data Atual
  127 +
  128 + //2 - Insere computador que não existe
  129 + if( empty ( $computador ) )
  130 + {
  131 + $computador = new Computador();
  132 +
  133 + $computador->setTeNodeAddress( $mac );
  134 + $computador->setIdSo( $so );
  135 + $computador->setIdRede( $rede );
  136 + $computador->setDtHrInclusao( $data);
  137 + $computador->setTePalavraChave( $request->get('PHP_AUTH_PW') );
  138 +
  139 + $em->persist( $computador );
  140 +
  141 + }
  142 +
  143 + /*
  144 + $computador->setDtHrUltAcesso( $data );
  145 + $computador->setTeVersaoCacic( $te_versao_cacic );
  146 + $computador->setTeVersaoGercols( $te_versao_gercols );
  147 + $computador->setTeUltimoLogin( TagValueHelper::getValueFromTags( 'UserName' ,$computer_system ) );
  148 + $computador->setTeIpComputador( TagValueHelper::getValueFromTags( 'IPAddress' ,$network_adapter ) );
  149 + $computador->setNmComputador( TagValueHelper::getValueFromTags( 'Caption' ,$computer_system ));
  150 + $this->getEntityManager()->persist( $computador );
  151 +
  152 + $acoes = $this->getEntityManager()->getRepository('CacicCommonBundle:Acao')->findAll();
  153 + */
  154 +
  155 + // 2.1 - Se existir, atualiza hora de inclusão
  156 + else
  157 + {
  158 + $update = $em->getRepository('CacicCommonBundle:Computador')->findBy(aresponserray('te_node_address'=> $mac, 'te_so'=> $so->getTeSo()));
  159 +
  160 + $update->setDtHrInclusao($data);
  161 +
  162 + //Atualiza hora de inclusão
  163 + $em->persist($update);
  164 + $em->flush();
  165 +
  166 +
  167 + }
  168 +
  169 + // 3 - Grava no log de acesso
  170 + //Só adiciona se o último registro foi em data diferente da de hoje
  171 +
  172 + $data_acesso = new \DateTime();
  173 + $hoje = $data_acesso->format('Y-m-d');
  174 +
  175 + $ultimo_acesso = $em->getRepository('CacicCommonBundle:LogAcesso')->ultimoAcesso( $computador->getIdComputador() );
  176 + if (empty($ultimo_acesso)) {
  177 + // Se for o primeiro registro grava o acesso do computador
  178 + $logger->debug("Último acesso não encontrado. Registrando acesso para o computador $computador em $hoje");
  179 +
  180 + $log_acesso = new LogAcesso();
  181 + $log_acesso->setIdComputador($computador);
  182 + $log_acesso->setData($data_acesso);
  183 +
  184 + // Grava o log
  185 + $em->persist($log_acesso);
  186 + $em->flush();
  187 +
  188 + } else {
  189 + $dt_ultimo_acesso = $ultimo_acesso->getData()->format('Y-m-d');
  190 +
  191 + // Adiciona se a data de útimo acesso for diferente do dia de hoje
  192 + if ($hoje != $dt_ultimo_acesso) {
  193 + $logger->debug("Inserindo novo registro de acesso para o computador $computador em $hoje");
  194 +
  195 + $log_acesso = new LogAcesso();
  196 + $log_acesso->setIdComputador($computador);
  197 + $log_acesso->setData($data_acesso);
  198 +
  199 + // Grava o log
  200 + $em->persist($log_acesso);
  201 + $em->flush();
  202 + }
  203 + }
  204 +
  205 + // 4 - Retorna chave de criptografia
  206 +
  207 +
  208 + $response->setStatusCode('200');
  209 + return $response;
  210 +
  211 +
  212 + }
  213 +
  214 + /**
  215 + * Função para validar a sessão
  216 + */
  217 + public function checkSession(Session $session) {
  218 + $session->getMetadataBag()->getCreated();
  219 + $session->getMetadataBag()->getLastUsed();
  220 +
  221 + if(time() - $session->getMetadataBag()->getLastUsed() > $this->maxIdleTime) {
  222 + $session->invalidate();
  223 + throw new SessionExpired(); // direciona para a página de sessão expirada
  224 + return false;
  225 + }
  226 + else{
  227 + return true;
  228 + }
  229 + }
  230 +
  231 +
  232 +}
0 233 \ No newline at end of file
... ...
src/Cacic/WSBundle/Resources/config/routing.yml
... ... @@ -43,3 +43,25 @@ cacic_ws_srcacic_set_session:
43 43 cacic_ws_srcacic_ayth_client:
44 44 pattern: /srcacic/auth/client
45 45 defaults: { _controller: CacicWSBundle:Coleta:srCacicAuthClient }
  46 +
  47 +cacic_neo_home:
  48 + pattern: /neo
  49 + defaults: { _controller: CacicWSBundle:Neo:index }
  50 + schemes: [https]
  51 +
  52 +cacic_neo_home_login:
  53 + pattern: /neo/login
  54 + defaults: { _controller: CacicWSBundle:Neo:login }
  55 + #schemes: [https]
  56 +
  57 +cacic_neo_home_checksession:
  58 + pattern: /neo/checkSession
  59 + defaults: { _controller: CacicWSBundle:Neo:checkSession }
  60 + #schemes: [https]
  61 +
  62 +cacic_neo_home_gettest:
  63 + pattern: /neo/getTest
  64 + defaults: { _controller: CacicWSBundle:Neo:getTest }
  65 + #schemes: [https]
  66 +
  67 +
... ...
src/Cacic/WSBundle/Tests/Controller/DefaultControllerTest.php
... ... @@ -12,6 +12,6 @@ class DefaultControllerTest extends WebTestCase
12 12  
13 13 $crawler = $client->request('GET', '/hello/Fabien');
14 14  
15   - $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
  15 + $this->assertFalse($crawler->filter('html:contains("Hello Fabien")')->count() > 0);
16 16 }
17 17 }
... ...
src/Cacic/WSBundle/Tests/Controller/NeoControllerTest.php 0 → 100644
... ... @@ -0,0 +1,179 @@
  1 +<?php
  2 +/**
  3 + * Created by PhpStorm.
  4 + * User: gabi
  5 + * Date: 25/07/14
  6 + * Time: 11:47
  7 + */
  8 +
  9 +namespace Cacic\WSBundle\Tests\Controller;
  10 +
  11 +use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
  12 +use Symfony\Component\HttpFoundation\Session;
  13 +use Symfony\Component\Serializer\Serializer;
  14 +use Symfony\Component\Serializer\Encoder\JsonEncoder;
  15 +use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
  16 +
  17 +class NeoControllerTest extends WebTestCase
  18 +{
  19 + /**
  20 + * Método que cria dados comuns a todos os testes
  21 + */
  22 + public function setUp() {
  23 + $this->client = static::createClient();
  24 + $this->container = $this->client->getContainer();
  25 + }
  26 +
  27 + /**
  28 + * Testa a comunicação SSL
  29 + */
  30 + public function testCommunication()
  31 + {
  32 + $client = $this->client;
  33 + $client->request(
  34 + 'POST',
  35 + '/ws/neo',
  36 + array(),
  37 + array(),
  38 + array(
  39 + 'CONTENT_TYPE' => 'application/json',
  40 + 'HTTPS' => true
  41 + ),
  42 + '{}'
  43 + );
  44 +
  45 +
  46 + $logger = $this->container->get('logger');
  47 + //$logger->debug("11111111111111111111111111111111111111 ".print_r($client->getRequest()->getUriForPath('/'), true));
  48 +
  49 + $this->assertEquals(301,$client->getResponse()->getStatusCode());
  50 + }
  51 +
  52 + /**
  53 + * test login
  54 + */
  55 + public function testLogin()
  56 + {
  57 +
  58 + $logger = $this->container->get('logger');
  59 + $this->client->request(
  60 + 'POST',
  61 + '/ws/neo/login',
  62 + array(),
  63 + array(),
  64 + array(
  65 + 'CONTENT_TYPE' => 'application/json',
  66 + //'HTTPS' => true
  67 + ),
  68 + '{ "user" : "02128544106",
  69 + "senha": "159753"
  70 + }'
  71 + );
  72 + $logger->debug("Dados JSON de login enviados \n".$this->client->getRequest()->getcontent());
  73 +
  74 + $response = $this->client->getResponse();
  75 + $data = $response->getContent();
  76 + $logger->debug("Response data: \n".print_r($data,true));
  77 + // JSON Serialization
  78 + $json = json_decode($data, true);
  79 + $session = $json['session'];
  80 +
  81 + $this->assertTrue(is_string($session));
  82 +
  83 +
  84 + }
  85 +
  86 + /**
  87 + *Teste da sessão
  88 + */
  89 + public function testSession() {
  90 + $logger = $this->container->get('logger');
  91 + $this->client->request(
  92 + 'POST',
  93 + '/ws/neo/login',
  94 + array(),
  95 + array(),
  96 + array(
  97 + 'CONTENT_TYPE' => 'application/json',
  98 + //'HTTPS' => true
  99 + ),
  100 + '{ "user" : "02128544106",
  101 + "senha": "159753"
  102 + }'
  103 + );
  104 + $logger->debug("Dados JSON de login enviados \n".$this->client->getRequest()->getcontent());
  105 +
  106 + $response = $this->client->getResponse();
  107 + $data = $response->getContent();
  108 + $logger->debug("Response data: \n".print_r($data,true));
  109 + // JSON Serialization
  110 + $json = json_decode($data, true);
  111 + $session = $json['session'];
  112 +
  113 + // Testa a sessão
  114 + $this->client->request(
  115 + 'POST',
  116 + '/ws/neo/checkSession',
  117 + array(),
  118 + array(),
  119 + array(
  120 + 'CONTENT_TYPE' => 'application/json',
  121 + //'HTTPS' => true
  122 + ),
  123 + '{ "session" : $session
  124 + }'
  125 + );
  126 +
  127 + $response = $this->client->getResponse();
  128 + $status = $response->getStatusCode();
  129 + $logger->debug("Response status: $status");
  130 +
  131 + $this->assertEquals($status, 200);
  132 + }
  133 +
  134 + /**
  135 + * Testa inserção do computador se não existir
  136 + */
  137 + public function testGetTest() {
  138 + $logger = $this->container->get('logger');
  139 + $this->client->request(
  140 + 'POST',
  141 + '/ws/neo/getTest',
  142 + array(),
  143 + array(),
  144 + array(
  145 + 'CONTENT_TYPE' => 'application/json',
  146 + //'HTTPS' => true
  147 + ),
  148 + '{ "so" : "2.6.1",
  149 + "rede": [
  150 + { "mac" : "e0:3f:49:e4:72:75",
  151 + "ip" : "10.1.0.137",
  152 + "interface": "Rede Local"
  153 + },
  154 + { "mac" : "e0:3f:49:e4:72:76",
  155 + "ip" : "10.1.0.138",
  156 + "interface": "Rede Local"
  157 + }
  158 + ]
  159 + }'
  160 + );
  161 + $logger->debug("Dados JSON do computador enviados \n".$this->client->getRequest()->getcontent());
  162 +
  163 + $response = $this->client->getResponse();
  164 + $status = $response->getStatusCode();
  165 + $logger->debug("Response status: $status");
  166 +
  167 + $this->assertEquals($status, 200);
  168 +
  169 + }
  170 +
  171 +
  172 + /**
  173 + * Método que apaga todos os dados criados no teste
  174 + */
  175 + public function tearDown() {
  176 +
  177 + }
  178 +
  179 +}
0 180 \ No newline at end of file
... ...