From 004590f51090974dcce6628dd4eaf8f5ba6e83ce Mon Sep 17 00:00:00 2001
From: Antony Le Courtes <antony.lecourtes@unicaen.fr>
Date: Thu, 15 Apr 2021 10:35:44 +0000
Subject: [PATCH] =?UTF-8?q?Refactoring=20de=20HostLocalizationUnicaen=20po?=
 =?UTF-8?q?ur=20=C3=A9viter=20d'avoir=20les=20adresses=20des=20proxies=20e?=
 =?UTF-8?q?t=20reverse=20proxies=20en=20dur=20dans=20le=20code.=20Passage?=
 =?UTF-8?q?=20en=20fichier=20de=20config=20pour=20que=20chacun=20puisse=20?=
 =?UTF-8?q?configurer=20dans=20son=20application.?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 config/module.config.php                      | 50 +++++++--------
 config/unicaen-app.local.php.dist             | 20 ++++++
 doc/Services.md                               | 29 +++++----
 .../HostLocalization/HostLocalization.php     | 61 +++++++++++++++++++
 .../HostLocalizationFactory.php               | 22 +++++++
 .../HostLocalizationUnicaen.php               | 46 --------------
 .../HostLocalizationUnicaenFactory.php        | 15 -----
 7 files changed, 142 insertions(+), 101 deletions(-)
 create mode 100644 src/UnicaenApp/HostLocalization/HostLocalization.php
 create mode 100644 src/UnicaenApp/HostLocalization/HostLocalizationFactory.php
 delete mode 100644 src/UnicaenApp/HostLocalization/HostLocalizationUnicaen.php
 delete mode 100644 src/UnicaenApp/HostLocalization/HostLocalizationUnicaenFactory.php

diff --git a/config/module.config.php b/config/module.config.php
index 138d53e3..e2d83554 100644
--- a/config/module.config.php
+++ b/config/module.config.php
@@ -6,8 +6,8 @@ use UnicaenApp\Controller\CacheControllerFactory;
 use UnicaenApp\Controller\InstadiaControllerFactory;
 use UnicaenApp\Form\View\Helper\FormControlGroup;
 use UnicaenApp\Form\View\Helper\FormControlGroupFactory;
-use UnicaenApp\HostLocalization\HostLocalizationUnicaen;
-use UnicaenApp\HostLocalization\HostLocalizationUnicaenFactory;
+use UnicaenApp\HostLocalization\HostLocalization;
+use UnicaenApp\HostLocalization\HostLocalizationFactory;
 use UnicaenApp\Message\View\Helper\MessageHelper;
 use UnicaenApp\Message\View\Helper\MessageHelperFactory;
 use UnicaenApp\Service\InstadiaServiceFactory;
@@ -248,11 +248,11 @@ return [
             ],
         ],
     ],
-    'console' => [
-        'router' => [
+    'console'         => [
+        'router'       => [
             'routes' => [
                 'run-sql-script' => [
-                    'type' => Simple::class,
+                    'type'    => Simple::class,
                     'options' => [
                         'route'    => 'run-sql-script --path= [--logfile=] [--connection=]',
                         'defaults' => [
@@ -261,8 +261,8 @@ return [
                         ],
                     ],
                 ],
-                'run-sql-query' => [
-                    'type' => Simple::class,
+                'run-sql-query'  => [
+                    'type'    => Simple::class,
                     'options' => [
                         'route'    => 'run-sql-query --sql= [--logfile=] [--connection=]',
                         'defaults' => [
@@ -276,7 +276,7 @@ return [
         'view_manager' => [
             'display_not_found_reason' => true,
             'display_exceptions'       => true,
-        ]
+        ],
     ],
     'service_manager' => [
         'factories'          => [
@@ -323,12 +323,12 @@ return [
             'MouchardCompleterHttp'        => 'UnicaenApp\Mouchard\MouchardCompleterHttpFactory',
             'MouchardCompleterMvc'         => 'UnicaenApp\Mouchard\MouchardCompleterMvcFactory',
 
-            MailerService::class => MailerServiceFactory::class,
-            RunSQLService::class => RunSQLServiceFactory::class,
-            'instadia'                      => InstadiaServiceFactory::class,
-            HostLocalizationUnicaen::class => HostLocalizationUnicaenFactory::class,
+            MailerService::class    => MailerServiceFactory::class,
+            RunSQLService::class    => RunSQLServiceFactory::class,
+            'instadia'              => InstadiaServiceFactory::class,
+            HostLocalization::class => HostLocalizationFactory::class,
         ],
-        'shared' => [
+        'shared'             => [
             'MouchardListenerErrorHandler' => false,
             'MouchardListenerException'    => false,
             'MouchardListenerMessenger'    => false,
@@ -347,10 +347,10 @@ return [
             ServiceLocatorAwareInitializer::class,
             'UnicaenApp\Service\EntityManagerAwareInitializer',
         ],
-        'aliases' => [
-            'MailerService' => MailerService::class,
-            'HostLocalization'  => HostLocalizationUnicaen::class,
-        ]
+        'aliases'            => [
+            'MailerService'    => MailerService::class,
+            'HostLocalization' => HostLocalization::class,
+        ],
     ],
     'form_elements'   => [
         'invokables'   => [
@@ -366,10 +366,10 @@ return [
         ],
     ],
     'view_helpers'    => [
-        'shared' => [
+        'shared'       => [
             'formControlGroup' => false,
         ],
-        'aliases' => [
+        'aliases'      => [
             'appInfos'          => AppInfos::class,
             'appLink'           => AppLink::class,
             'userProfileSelect' => UserProfileSelect::class,
@@ -386,7 +386,7 @@ return [
             'uploader'          => UploaderHelper::class,
             'Uploader'          => UploaderHelper::class,
         ],
-        'factories' => [
+        'factories'    => [
             AppInfos::class               => AppInfosFactory::class,
             AppLink::class                => AppLinkFactory::class,
             UserProfileSelect::class      => UserProfileSelectFactory::class,
@@ -454,11 +454,11 @@ return [
         'initializers' => [
             'UnicaenApp\Service\EntityManagerAwareInitializer',
         ],
-        'factories' => [
-            'UnicaenApp\Controller\Cache' => CacheControllerFactory::class,
+        'factories'    => [
+            'UnicaenApp\Controller\Cache'    => CacheControllerFactory::class,
             'UnicaenApp\Controller\Instadia' => InstadiaControllerFactory::class,
-            ConsoleController::class => ConsoleControllerFactory::class,
-        ]
+            ConsoleController::class         => ConsoleControllerFactory::class,
+        ],
     ],
 
     'doctrine' => [
@@ -510,7 +510,7 @@ return [
         'strategies'               => [
             'ViewJsonStrategy', // register JSON renderer strategy
             'ViewCsvStrategy', // register CSV renderer strategy
-//            'ViewXmlStrategy', // register XML renderer strategy
+            //            'ViewXmlStrategy', // register XML renderer strategy
             //            'ViewFeedStrategy', // register Feed renderer strategy
         ],
     ],
diff --git a/config/unicaen-app.local.php.dist b/config/unicaen-app.local.php.dist
index b21c74bb..6377ce78 100644
--- a/config/unicaen-app.local.php.dist
+++ b/config/unicaen-app.local.php.dist
@@ -7,6 +7,24 @@
  */
 return [
     'unicaen-app' => [
+         /**
+         * Paramétrage pour utilisation pour autorisation ou non à la connexion à
+         * une app de l'exterieur de l'établissement
+         */
+         hostlocalization'       => [
+             'activated' => false,
+
+             'proxies' => [
+                 //xxx.xx.xx.xxx
+             ],
+
+             'reverse-proxies' => [
+                 //xxx.xx.xx.xxx
+             ],
+
+             'masque-ip' => '',
+
+         ],
         /**
          * Connexion à l'annuaire LDAP (NB: compte admin requis)
          */
@@ -59,5 +77,7 @@ return [
                 // ['195.220.135.97', '194.199.107.33'], // Via proxy
             ],
         ],
+
+
     ],
 ];
\ No newline at end of file
diff --git a/doc/Services.md b/doc/Services.md
index 94e20cd8..bc3afecf 100644
--- a/doc/Services.md
+++ b/doc/Services.md
@@ -6,8 +6,7 @@ LDAP
 
 ### Group
 
-Service d\'accès aux groupes de l\'annuaire LDAP. Avec le gestionnaire
-de service, ce service est accessible ainsi :
+Service d\'accès aux groupes de l\'annuaire LDAP. Avec le gestionnaire de service, ce service est accessible ainsi :
 
 ``` {.php}
 $service = $sm->get('ldap_group_service'); /* @var $service \UnicaenApp\Service\Ldap\Group */
@@ -15,8 +14,7 @@ $service = $sm->get('ldap_group_service'); /* @var $service \UnicaenApp\Service\
 
 ### People
 
-Service d\'accès aux individus de l\'annuaire LDAP. Avec le gestionnaire
-de service, ce service est accessible ainsi :
+Service d\'accès aux individus de l\'annuaire LDAP. Avec le gestionnaire de service, ce service est accessible ainsi :
 
 ``` {.php}
 $service = $sm->get('ldap_people_service'); /* @var $service \UnicaenApp\Service\Ldap\People */
@@ -24,8 +22,7 @@ $service = $sm->get('ldap_people_service'); /* @var $service \UnicaenApp\Service
 
 ### Structure
 
-Service d\'accès aux structures de l\'annuaire LDAP. Avec le
-gestionnaire de service, ce service est accessible ainsi :
+Service d\'accès aux structures de l\'annuaire LDAP. Avec le gestionnaire de service, ce service est accessible ainsi :
 
 ``` {.php}
 $service = $sm->get('ldap_structure_service'); /* @var $service \UnicaenApp\Service\Ldap\Structure */
@@ -35,16 +32,17 @@ $service = $sm->get('ldap_structure_service'); /* @var $service \UnicaenApp\Serv
 
 Le service HostLocalization a pour but de déterminer si le poste client est situé dans le réseau de l'Etablissement ou non.
 
-En standard, seul un mécanisme de détection pour l'Université de Caen est disponible.
-Pour Caen, l'idée est la suivante : la méthode inEtablissement du service renverra true si la machine de l'utilisateur est dans les cas suivants :
+En standard, seul un mécanisme de détection pour l'Université de Caen est disponible. Pour Caen, l'idée est la suivante : la
+méthode inEtablissement du service renverra true si la machine de l'utilisateur est dans les cas suivants :
+
 * En direct et en interne sans passer par le proxy (pas de redirection)
 * En interne, que l'on sort puis on re-rentre en passant par le reverse proxy
-* En interne, que l'on passe par le proxy en interne
-Sinon false.
+* En interne, que l'on passe par le proxy en interne Sinon false.
 
 Il est cependant possible d'ajouter votre propre mécanisme de localisation.
 
-Attention : en mode développement, sur votre machine et avec l'appli en localhost, vous ne serez pas considéré comme sur le réseau de l'établissement.
+Attention : en mode développement, sur votre machine et avec l'appli en localhost, vous ne serez pas considéré comme sur le
+réseau de l'établissement.
 
 #### Récupération et utilisation du service
 
@@ -63,14 +61,15 @@ if ($hl->inEtablissement()){
 }
 ```
 
-Un Trait [HostLocalizationAwareTrait](../src/UnicaenApp/HostLocalization/HostLocalizationAwareTrait.php) est dispo avec un getter et un setter pour pouvoir injecter proprement la dépendance dans votre code.
+Un Trait [HostLocalizationAwareTrait](../src/UnicaenApp/HostLocalization/HostLocalizationAwareTrait.php) est dispo avec un
+getter et un setter pour pouvoir injecter proprement la dépendance dans votre code.
 
 ### Créer votre propre système de localization
 
 Pour utiliser votre propre système de HostLocalization, il vous faut :
 
 Créer une classe implémentant [HostLocalizationInterface](../src/UnicaenApp/HostLocalization/HostLocalizationInterface.php).
-La rendre dispo comme service dans votre config du ServiceManager.
-Modifier l'alias de service 'HostLocalization' pour le faire pointer sur votre propre classe.
+La rendre dispo comme service dans votre config du ServiceManager. Modifier l'alias de service 'HostLocalization' pour le
+faire pointer sur votre propre classe.
 
-Vous pourrez au besoin vous inspirer de [HostLocalizationUnicaen](../src/UnicaenApp/HostLocalization/HostLocalizationUnicaen.php).
\ No newline at end of file
+Vous pourrez au besoin vous inspirer de [HostLocalization](../src/UnicaenApp/HostLocalization/HostLocalization.php).
\ No newline at end of file
diff --git a/src/UnicaenApp/HostLocalization/HostLocalization.php b/src/UnicaenApp/HostLocalization/HostLocalization.php
new file mode 100644
index 00000000..9d845f1d
--- /dev/null
+++ b/src/UnicaenApp/HostLocalization/HostLocalization.php
@@ -0,0 +1,61 @@
+<?php
+
+namespace UnicaenApp\HostLocalization;
+
+
+class HostLocalization implements HostLocalizationInterface
+{
+
+    protected $activated;
+
+    protected $proxies;
+
+    protected $reverseProxies;
+
+    protected $masqueIp;
+
+
+
+    /**
+     * Renvoie true si le'utilisateur utilise une machine connectée au réseau de l'établissement
+     * ou bien si la machine est hors réseau
+     *
+     * @return bool
+     */
+
+    public function __construct($activated, $masqueIp, $proxies, $reverseProxies)
+    {
+        $this->activated      = $activated;
+        $this->proxies        = $proxies;
+        $this->reverseProxies = $reverseProxies;
+        $this->masqueIp       = $masqueIp;
+    }
+
+
+
+    /**
+     * Retourne selon les règles définies en config si on est dans l'établissement ou à l'extérieur.
+     *
+     * @return bool
+     */
+    public function inEtablissement(): bool
+    {
+        if (!$this->activated || empty($this->masqueIp)) {
+            return true;
+        }
+        $ip        = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
+        $forwarded = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
+
+        // Si on est en direct et en interne sans passer par le proxy (pas de redirection)
+        if (0 === strpos($ip, $this->masqueIp) && $forwarded === '') return true;
+
+        // Si on est en interne, que l'on sort puis on re-rentre en passant par le reverse proxy
+        if (in_array($ip, $this->reverseProxies) && 0 === strpos($forwarded, $this->masqueIp)) return true;
+
+        // Si on est en interne, que l'on passe par le proxy en interne
+        if (in_array($ip, $this->proxies) && 0 === strpos($forwarded, $this->masqueIp)) return true;
+
+        // Sinon, on vient de l'extérieur
+        return false;
+    }
+}
\ No newline at end of file
diff --git a/src/UnicaenApp/HostLocalization/HostLocalizationFactory.php b/src/UnicaenApp/HostLocalization/HostLocalizationFactory.php
new file mode 100644
index 00000000..67f1c018
--- /dev/null
+++ b/src/UnicaenApp/HostLocalization/HostLocalizationFactory.php
@@ -0,0 +1,22 @@
+<?php
+
+namespace UnicaenApp\HostLocalization;
+
+use Interop\Container\ContainerInterface;
+
+class HostLocalizationFactory
+{
+    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
+    {
+        $config         = $container->get('config');
+        $activated      = $config['hostlocalization']['activated'];
+        $proxies        = $config['hostlocalization']['proxies'];
+        $reverseProxies = $config['hostlocalization']['reverse-proxies'];
+        $masqueIp       = $config['hostlocalization']['masque-ip'];
+
+        $service = new HostLocalization($activated, $masqueIp, $proxies, $reverseProxies);
+
+
+        return $service;
+    }
+}
\ No newline at end of file
diff --git a/src/UnicaenApp/HostLocalization/HostLocalizationUnicaen.php b/src/UnicaenApp/HostLocalization/HostLocalizationUnicaen.php
deleted file mode 100644
index 92e27179..00000000
--- a/src/UnicaenApp/HostLocalization/HostLocalizationUnicaen.php
+++ /dev/null
@@ -1,46 +0,0 @@
-<?php
-
-namespace UnicaenApp\HostLocalization;
-
-class HostLocalizationUnicaen implements HostLocalizationInterface
-{
-    /**
-     * Renvoie true si le'utilisateur utilise une machine connectée au réseau de l'établissement
-     * ou bien si la machine est hors réseau
-     *
-     * @return bool
-     */
-    public function inEtablissement(): bool
-    {
-        $ip        = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
-        $forwarded =  isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
-
-        $ipInterne = '10.';
-
-        $proxies = [
-            '10.14.128.39',
-            '10.14.128.100',
-            '10.14.128.100',
-            '10.14.128.101',
-            '10.14.128.137',
-        ];
-
-        $reverseProxies = [
-            '193.55.120.23',
-            '193.55.120.24',
-            '193.55.120.25',
-        ];
-
-        // Si on est en direct et en interne sans passer par le proxy (pas de redirection)
-        if (0 === strpos($ip,$ipInterne) && $forwarded === '') return true;
-
-        // Si on est en interne, que l'on sort puis on re-rentre en passant par le reverse proxy
-        if (in_array($ip,$reverseProxies) && 0 === strpos($forwarded,$ipInterne)) return true;
-
-        // Si on est en interne, que l'on passe par le proxy en interne
-        if (in_array($ip,$proxies) && 0 === strpos($forwarded,$ipInterne)) return true;
-
-        // Sinon, on vient de l'extérieur
-        return false;
-    }
-}
\ No newline at end of file
diff --git a/src/UnicaenApp/HostLocalization/HostLocalizationUnicaenFactory.php b/src/UnicaenApp/HostLocalization/HostLocalizationUnicaenFactory.php
deleted file mode 100644
index b6b690f6..00000000
--- a/src/UnicaenApp/HostLocalization/HostLocalizationUnicaenFactory.php
+++ /dev/null
@@ -1,15 +0,0 @@
-<?php
-
-namespace UnicaenApp\HostLocalization;
-
-use Interop\Container\ContainerInterface;
-
-class HostLocalizationUnicaenFactory
-{
-    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
-    {
-        $service = new HostLocalizationUnicaen();
-
-        return $service;
-    }
-}
\ No newline at end of file
-- 
GitLab