del unused system bundle in symfony app

This commit is contained in:
Emmanuel ROY 2021-01-15 15:52:19 +01:00
commit 42d7a8e40f
31 changed files with 0 additions and 2704 deletions

View file

@ -1,113 +0,0 @@
<?php
namespace App\Session\AuthBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
/**
* This is the class that validates and merges configuration from your app/config files.
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('session_auth');
$rootNode = $treeBuilder->getRootNode();
$rootNode
->children()
->scalarNode('homepage')->defaultNull()->end()
->scalarNode('authentication_service')->defaultNull()->end()
->scalarNode('provider')->defaultNull()->end()
->booleanNode('use_default_provider')->defaultTrue()->end()
->scalarNode('user_entity')->defaultNull()->end()
->scalarNode('type_auth')->isRequired()->cannotBeEmpty()
->validate()
->ifNotInArray(array('Rsa', 'Cas','Session'))
->thenInvalid("La méthode d'authentification %s n'est pas gérée, seuls Rsa et Cas sont acceptés")
->end()
->end()
->scalarNode('environment')->end()
->end()
;
$rootNode
->validate()
->ifTrue(function ($v) {
if (!is_null($v['user_entity'])) {
$class = $v['user_entity'];
if (!class_exists($class)) {
return true;
}
return !array_key_exists("Symfony\Component\Security\Core\User\UserInterface", class_implements($class));
}
return false;
})
->thenInvalid("La classe renseignée pour 'entity' doit implémenter Symfony\Component\Security\Core\User\UserInterface")
->end();
$this->_addCasConfig($rootNode);
$this->_addRsaConfig($rootNode);
return $treeBuilder;
}
private function _addCasConfig(ArrayNodeDefinition $node)
{
$node
->children()
->arrayNode('cas')->info('A déclarer si authentification pas CAS.')
->addDefaultsIfNotSet()
->treatNullLike(['hostname' => null])
->treatNullLike(['port' => null])
->treatNullLike(['uri' => null])
->children()
->scalarNode('hostname')->defaultNull()->end()
->scalarNode('port')->defaultNull()->end()
->scalarNode('uri')->defaultNull()->end()
->end()
->end()
->end()
;
$node
->validate()
->ifTrue(function ($v) {
$cas_config = $v['cas'];
return ($v['type_auth']=="Cas" && (is_null($cas_config['hostname']) || is_null($cas_config['port']) || is_null($cas_config['uri'])));
})
->thenInvalid("En utilisant le type d'authentification Cas vous devez renseigner la section 'cas' et ses clés 'hostname', 'port', 'uri'")
->end();
}
private function _addRsaConfig(ArrayNodeDefinition $node)
{
$node
->children()
->arrayNode('rsa')->addDefaultsIfNotSet()->info('A déclarer si authentification pas RSA.')
->addDefaultsIfNotSet()
->treatNullLike(['logout_url' => null])
->children()
->scalarNode('logout_url')->defaultNull()->end()
->end()
->end()
->end()
;
$node
->validate()
->ifTrue(function ($v) {
$rsa_config = $v['rsa'];
return ($v['type_auth']==="Rsa" && is_null($rsa_config['logout_url']));
})
->thenInvalid("En utilisant le type d'authentification Rsa vous devez renseigner la section 'rsa' et sa clé 'logout_url'")
->end();
}
}

View file

@ -1,83 +0,0 @@
<?php
namespace App\Session\AuthBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ChildDefinition;
/**
* This is the class that loads and manages your bundle configuration.
*
* @link http://symfony.com/doc/current/cookbook/bundles/extension.html
*/
class SessionAuthExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configs[0]['environment'] = $container->getParameter("kernel.environment");
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
//Chargement des parametres
$loader->load('parameters.yml');
//Chargement des services
$loader->load('services.yml');
//definition du service d'authentification par défaut dans le cas où ce ne serait pas un service
// fraichement créé par l'utilisateur dans le fichiers services.yaml
if (is_null($config["authentication_service"])) {
$authentication_service = "session_auth.authentification";
} else {
$authentication_service = $config["authentication_service"];
}
if ($authentication_service == "session_auth.authentification") {
$container->register($authentication_service, \App\Besancon\AuthBundle\Security\DefaultAuthentication::class)
->addMethodCall('setGetterAttributes', array($config))
->setPublic(false);
}
//Creation du service @bes_auth.authenticator permettant la redirection sur le Cas ou le Rsa correspondant
$container->register('session_auth.authenticator', \Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator::class)
->setFactory(array(new Reference("session_auth.authenticator_factory"), 'getAuthenticator'))
->addArgument(new Reference($authentication_service))
->addArgument($config)
->addArgument(new Reference("router"))
->addArgument(new Reference("event_dispatcher"))
->setPublic(false);
//Création du service pour le provider par défaut ou pour le provider défini par l'utilisateur
if ($config["use_default_provider"]) {
//Creation du service @bes_auth.user_provider
$container->register('session_auth.user_provider', \App\Besancon\AuthBundle\Security\User\AuthUserProvider::class)
->addArgument(new Reference($authentication_service))
->addArgument($config)
->setPublic(false);
} else {
$container->register('session_auth.user_provider', $config["provider"])
->addArgument(new Reference($authentication_service))
->addArgument($config)
->setPublic(false);
}
$container->setDefinition('session_auth.configuration', new \Symfony\Component\DependencyInjection\Definition(\App\Besancon\AuthBundle\DependencyInjection\Configuration::class))
->setArguments([
$config,
]);
}
public function getNamespace()
{
return 'http://ac-besancon.fr/schema/dic/' . $this->getAlias();
}
}

View file

@ -1,38 +0,0 @@
<?php
namespace App\Session\AuthBundle\Events;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Security\Core\User\UserInterface;
class CheckCredentialsEvent extends Event
{
const NAME = "besancon_auth.event.check_credentials";
private $access = true;
public function __construct($credentials, UserInterface $user_interface)
{
$this->credentials = $credentials;
$this->user_interface = $user_interface;
}
public function getCredentials()
{
return $this->credentials;
}
public function getUserInterface()
{
return $this->user_interface;
}
public function getAccess()
{
return $this->access;
}
public function setAccess($access)
{
$this->access = $access;
return $this;
}
}

View file

@ -1,41 +0,0 @@
<?php
namespace App\Session\AuthBundle\Events;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class OnAuthenticationFailureEvent extends Event
{
const NAME = "session_auth.event.on_authentication_failure";
public function __construct(Request $request, AuthenticationException $exception)
{
$this->request = $request;
$this->exception = $exception;
$this->response = new Response($exception->getMessage(), Response::HTTP_FORBIDDEN);
}
public function getRequest()
{
return $this->request;
}
public function getException()
{
return $this->exception;
}
public function getResponse()
{
return $this->response;
}
public function setResponse($response)
{
$this->response = $response;
return $this;
}
}

View file

@ -1,33 +0,0 @@
<?php
namespace App\Session\AuthBundle\Events;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
class OnAuthenticationSuccessEvent extends Event
{
const NAME = "session_auth.event.on_authentication_success";
public function __construct(Request $request, TokenInterface $token, $providerKey)
{
$this->request = $request;
$this->token = $token;
$this->providerKey = $providerKey;
}
public function getRequest()
{
return $this->request;
}
public function getToken()
{
return $this->exception;
}
public function getProviderKey()
{
return $this->providerKey;
}
}

View file

@ -1,366 +0,0 @@
**AuthBundle**
========================
# Configuration minimale requise
Le bundle est compatible à partir de la version 3.4 de Symfony.
# Installation
## Installation via composer (recommandé)
Dans un premier temps renseigner le "repository" via la commande :
```bash
composer config repositories.authbundle git "ssh://git@gitlab1.in.ac-besancon.fr:1232/abelhadjali/authbundle.git"
```
Ceci va ajouter dans votre fichier composer.json les lignes suivantes
```json
...
"repositories": {
"authbundle": {
"type": "git",
"url": "ssh://git@gitlab1.in.ac-besancon.fr:1232/abelhadjali/authbundle.git"
}
}
...
```
Puis ajouter la dépendance au bundle en précisant le tag de la version souhaitée ici à partir de la v0.1
```bash
composer require ac-besancon/authbundle:^0.1
```
Enfin activer le bundle en suivant les instructions de la section [[AuthBundle#Activation du bundle|Activation du bundle]]
## Installation sans composer
### Récupérer les sources
*Copier et coller* le dossier Besancon du Bundle dans le repertoire _*src/*_ de votre projet *Symfony*.
### Déclaration du namespace
Dans le fichier `composer.json` et dans la section "autoload" de votre projet ajouter:
```json
"autoload": {
"psr-4": {
...
"Besancon\\AuthBundle\\": "src/Besancon/AuthBundle",
...
}
```
Puis executer la commande composer suivante :
```bash
composer dump-autoload
```
# Activation du bundle
Pour activer le Bundle, ouvrir le fichier app/AppKernel.php et y ajouter:
```php
// ...
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
// ...
new Besancon\AuthBundle\BesanconAuthBundle(),
);
// ...
}
// ...
}
```
# Configuration
======================
## Liste complète des options de configuration
La configuration est à déclaré dans le fichier *app/config/config.yml* du projet Symfony.
```yaml
besancon_auth:
#Activation du user_provider interne
#par défaut TRUE
use_default_provider : true
#Namespace de l'entité utilisateur
#L'entité doit implémenter Symfony\Component\Security\Core\User\UserInterface
#par défaut est utilise Besancon\AuthBundle\Security\User\AuthUser
user_entity: Mon\Entite\User
#nom de la route correspondant à la page d'accueil de l'application
#par défaut est à NULL
homepage: "homepage"
#tag du service personnalisé permettant de gérer l'authentification
#par défaut est à bes_auth.authentification (service par défaut)
authentication_service: mon_service.authentification
#Mode d'authentification Cas ou Rsa
#obligatoire pas de valeur par défaut
type_auth: Cas
#Configuration pour le mode Cas
#obligatoire si mode Cas choisi
cas:
#Serveur Cas
hostname: "seshat23.ac-besancon.fr"
#Port Cas
port: 8443
#Uri Cas
uri: ""
#Configuration pour le mode Rsa
#obligatoire si mode Rsa choisi
rsa :
#Url de déconnexion Rsa
logout_url: http://url.deconnexion.fr/login/ct_logout.jsp
```
## Configuration dans le firewall
Ouvrir le fichier app/config/security.yml du projet Symfony.
Si utilisation du _user provider_ interne *bes_auth.user_provider* , alors le déclarer dans la section _*providers*_ :
```yaml
...
providers:
app:
id: bes_auth.user_provider
...
```
Sinon préciser votre propre user provider
Toujours dans le même fichier, dans la section des _*firewalls*_, déclarer le _guard_ *bes_auth.authenticator* dans la zone à sécurisée :
```yaml
firewalls:
...
secured_area:
logout_on_user_change: true
...
guard:
authenticators:
- bes_auth.authenticator
logout:
path: auth_cas_logout #nom de la route de déconnexion
target: /
success_handler: bes_auth.authenticator
...
```
Plus d'infos sur le user provider :
* https://symfony.com/doc/current/security/entity_provider.html#using-a-custom-query-to-load-the-user
Il est donc important de définir la route de déconnexion dans le fichier *app/config/route.yml*
```yaml
...
auth_cas_logout:
path: /logout
...
```
## Configuration avancée
### Création d'un service d'authentification
Pour cela, créer un service qui hérite de *AuthAbstract* et implémente *AuthInterface*
```php
<?php
namespace AppBundle\Security\Auth;
use Besancon\AuthBundle\Security\Interfaces\AuthInterface;
use Doctrine\ORM\EntityManager;
use Besancon\AuthBundle\Security\Abstracts\AuthAbstract;
class MonService extends AuthAbstract implements AuthInterface {
...
}
```
Il faut ensuite implémenter les méthodes suivantes :
```php
/**
* Contrôle de l'accès à partir des attributs CAS ou RSA
*
* Vérifier les droits d'accès à l'application à partir des attributs récupérées des getters :
* - CasAttributes
* - RsaAttributes
*
* @param UserInterface $user
* L'entité user récupéré par le provider
*
* @return bool
* - true si accès autorisé
* - false si accès refusé
*/
public function ctrlAccess(UserInterface $user);
/**
* Calcule et retoune le(s) rôle(s) à partir des attributs CAS ou RSA
*
* Calculer le(s) rôle(s) à partir des attributs récupérées des getters :
* - CasAttributes
* - RsaAttributes
* Doit retourner un tableau même vide
*
* @return array
*/
public function getRoles();
/**
* Retourne un utilisateur pour la génération du token, si l'utilisateur n'existe pas en base de donnée
*
* ATTENTION : CETTE METHODE DOIT ÊTRE REDEFINIE SI UTILISATION D'UNE ENTITE UTILISTEUR
* DIFFERENTE DE CELLE UTILISEE PAR DEFAUT
*
* @param String $username
* uid de l'utilisateur récupéré de Cas ou Rsa
*
* @return UserInterface
*/
public function getUser($username);
/**
* Traitement personnalisé après récupération du token
*
* Il est possible d'enrichir le token (attributs...) ou d'effectuer des contrôles supplémentaire
*
* @param $token
* Token d'authification généré
*
* @return null
*/
public function onSuccess($token);
/**
* Traitement personnalisé lorsque la connexion n'a pas abouti
*
* Vérifié l'exception généré et adapter l'action (redirection, déconnexion...)
*
* Doit retourner un objet de type Response
*
* Exemple :
*
* ```
* public function onAuthenticationFailure(\Symfony\Component\Security\Core\Exception\AuthenticationException $exception)
* {
* $content = $this->twig->render(
* '@App/Test/forbiden.html.twig', array()
* );
* $response = new Response($content, Response::HTTP_FORBIDDEN);
* return $response;
* }
* ```
*
* @param AuthenticationException $exception
* Exception générée par le provider
*
* @return Symfony\Component\HttpFoundation\Response
*
*/
public function onAuthenticationFailure(\Symfony\Component\Security\Core\Exception\AuthenticationException $exception);
```
Enfin lorsque le service est prêt, le déclarer, en le reliant à la classe parent Besancon\AuthBundle\Security\Abstracts\AuthAbstract:
```yaml
mon_service.authentification:
class: AppBundle\Security\Auth\MonService
parent: Besancon\AuthBundle\Security\Abstracts\AuthAbstract
public: false
#OU si version Symfony >=3.4
AppBundle\Security\Auth\MonService:
autowire: true
parent: Besancon\AuthBundle\Security\Abstracts\AuthAbstract
public: false
autoconfigure: false
```
Puis déclarer dans la configuration ([[AuthBundle#Liste complète des options de configuration|Liste complète des options de configuration]]) du bundle le nom du service personnalisé :
```yaml
besancon_auth:
...
authentication_service: mon_service.authentification
#OU si version Symfony >=3.4
authentication_service: AppBundle\Security\Auth\MonService
...
```
# Personnaliser la page en cas d'échec d'authentification
En cas d'échec lors de l'authentification (exemple ctrlAccess() retourne false) , par défaut, le bundle renvoie une page blanche avec le message renvoyé par l'exception qui a généré l'erreur.
Afin de personnaliser cette page, il faut passer par la création d'un service comme indiqué dans le paragraphe [[AuthBundle#Création d'un service d'authentification|Création d'un service d'authentification]] et de redéfinir la méthode *onAuthenticationFailure*.
Voici un exemple :
```php
class MonService extends AuthAbstract implements AuthInterface
{
public function __construct(Twig_Environment $twig)
{
$this->twig = $twig;
}
...
public function onAuthenticationFailure(\Symfony\Component\Security\Core\Exception\AuthenticationException $exception)
{
$content = $this->twig->render(
'@App/Test/forbiden.html.twig', array()
);
$response = new Response($content, Response::HTTP_FORBIDDEN);
return $response;
}
}
```
Nous pouvons remarquer que dans cet exemple, le service prend en paramètre dans le constructeur $twig qui est l'instance de Twig de notre applciation.
Pour que cela fonctionne, il faut auparavant avoir passer le tag twig à notre service :
```php
...
AppBundle\Security\Auth\MonService:
autowire: true
parent: Besancon\AuthBundle\Security\Abstracts\AuthAbstract
public: false
autoconfigure: false
arguments: ['@twig']
...
```
Ainsi lorsqu'une personne tentera de se connecter et qu'il n'aura, par exemple, pas les droits nécessaires le template @App/Test/forbiden.html.twig sera chargé.

View file

@ -1,40 +0,0 @@
parameters:
#auth_cas devra s'appeler auth_multi
#bes_auth.authentication_service: bes_auth.authentification
session_auth:
type_auth: Session
environment: "%kernel.environment%"
cas:
#defini l'entité correspondant aux utilisateurs pour la création automatique des comptes
server:
cas_hostname: "seshat23.ac-besancon.fr"
cas_port: 8443
cas_uri: ""
route:
after_connect: "homepage"
rsa :
logout_url: http://webphppreprod.in.ac-besancon.fr/login/ct_logout.jsp
login_url: ~
route:
after_connect: "homepage"
#Gérer les droits d'accès à l'application en fonction des attributs CAS
access:
# allow:
# attributes :
# - ["[phpCAS][attributes][title]","[phpCAS][attributes][ABservice]"]
# - "[phpCAS][attributes][FrEduRne]"
# values : ["DIR|^DSS","^.*\\$TEC\\$"]
#deny:
#attributes : "title"
#values : "ENS"
#@TODO : Association profile CAS et Role de l'appli
# profil:
# cas:
# ROLE_ADMIN:
# key: "[phpCAS][attributes][typensi]"
# value: "A"
# ROLE_USER:
# key: "[phpCAS][attributes][FrEduRne]"
# value: "^0250069P"
# control: "regex"

View file

@ -1,38 +0,0 @@
parameters:
#auth_cas devra s'appeler auth_multi
session_auth:
environment: "%kernel.environment%"
#defini l'entité correspondant aux utilisateurs pour la création automatique des comptes
server:
cas_hostname: "seshat23.ac-besancon.fr"
cas_port: 8443
cas_uri: ""
route:
after_connect: "homepage"
#Gérer les droits d'accès à l'application en fonction des attributs CAS
access:
# allow:
# attributes :
# - ["[phpCAS][attributes][title]","[phpCAS][attributes][ABservice]"]
# - "[phpCAS][attributes][FrEduRne]"
# values : ["DIR|^DSS","^.*\\$TEC\\$"]
deny:
attributes : "title"
values : "ENS"
#@TODO : Association profile CAS et Role de l'appli
# profil:
# cas:
# ROLE_ADMIN:
# key: "[phpCAS][attributes][typensi]"
# value: "A"
# ROLE_USER:
# key: "[phpCAS][attributes][FrEduRne]"
# value: "^0250069P"
# control: "regex"
auth_rsa :
environment: "%kernel.environment%"
login_url: http://webphppreprod.in.ac-besancon.fr/login/ct_logon_mixte.jsp
logout_url: http://webphppreprod.in.ac-besancon.fr/login/ct_logout.jsp
route:
after_connect: "homepage"

View file

@ -1,3 +0,0 @@
#besancon_auth_homepage:
# path: /
# defaults: { _controller: BesanconAuthBundle:Default:index }

View file

@ -1,11 +0,0 @@
services:
session_auth.authenticator_factory:
class: App\Session\AuthBundle\Security\AuthenticatorFactory
public: false
#bes_auth.authentification:
# class: App\Besancon\AuthBundle\Security\Auth\Authentication
# parent: App\Besancon\AuthBundle\Security\Abstracts\AuthFinal
# public: false
# autoconfigure: false

View file

@ -1,66 +0,0 @@
Installation
============
1: Installation
---------------------------
Copier et coller le dossier Besancon du Bundle dans src/
2: Activer le Bundle
-------------------------
Pour activer le Bundle, ouvrir le fichier `app/AppKernel.php` et y ajouter:
```php
<?php
// app/AppKernel.php
// ...
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
// ...
new Besancon\AuthBundle\BesanconAuthBundle(),
);
// ...
}
// ...
}
```
Puis dans le fichier `composer.json` de votre projet ajouter:
```json
"autoload": {
"psr-4": {
...
"Besancon\\AuthBundle\\": "src/Besancon/AuthBundle",
...
}
```
3: Authentification Cas
---------------------------
Si le Bundle est utilisé pour une athentification "Cas" alors télécharger la librairie phpCas dans votre projet
```console
$ composer require jasig/phpcas
```
Ouvrir le fichier `app/config/config.yml` et configurer :
```yml
besancon_auth:
homepage: "homepage" #nom de la route de l'accueil de l'application
type_auth: Cas
cas:
hostname: "serveurcas.ac-academy.fr" #serveur cas
port: 8443 #port cas
uri: "" #uri
```

View file

@ -1,77 +0,0 @@
<?php
/**
* Abstract AuthAbstract
*
* @package Besancon\AuthBundle\Security\Abstracts
* @author Amine BEL HADJ ALI <amine.belhadjali@ac-besancon.fr>
*
* @method setGetterAttributes()
* @method getUser()
* @abstract
*/
namespace App\Session\AuthBundle\Security\Abstracts;
use App\Session\AuthBundle\Utils\Config;
use Symfony\Component\HttpFoundation\Response;
abstract class AuthAbstract
{
/**
* @var App\Besancon\AuthBundle\Security\Interfaces\AttributesInterface $ai Instance de CasAttributes ou RsaAttributes
*/
protected $ai;
/**
* Intancie le getters en fonction de la configuration
*
* Si dans la config le paramètre type_auth est défini à CAS alors
* intanciation du getter CasAttributes,
* Si la valeur est à RSA alors instanciation du getter RsaAttributes
*
* Cette instance peut ensuite être utilisée dans le service d'authentification
* qui héritera de AuthAbstract, en passant faisant appel à $this->ai
*
* @final
* @param $config
* configuration du Bundle
* @return void
*
* */
abstract public function setGetterAttributes($config);
/**
* Comportement par défaut lorsque l'authentification n'aboutie pas (accès non autorisé)
*
* il est possible de redéfinir cette méthode
* mais elle doit renvoyer une réponse HTTP exemple:
* - Symfony\Component\HttpFoundation\Response
* - Symfony\Component\HttpFoundation\JsonResponse
*
* @param \Symfony\Component\Security\Core\Exception\AuthenticationException $exception
* Exception généré par le guard
* @return Symfony\Component\HttpFoundation\Response
*
* */
abstract public function onAuthenticationFailure(\Symfony\Component\Security\Core\Exception\AuthenticationException $exception);
/**
* Renvoie une instance de l'utilisateur
*
* Ceci correspond à la class Besancon\AuthBundle\Security\User\AuthUser,
* il est possible de redéfinir cette méthode
* mais elle doit renvoyer un objet implementant Symfony\Component\Security\Core\User\UserInterface
*
* Est utilisé dans le userprovider par défaut Besancon\AuthBundle\Security\User\AuthUserProvider
*
* @see \Symfony\Component\Security\Core\User\UserInterface
* @see \Besancon\AuthBundle\Security\User\AuthUserProvider
*
* @param string $username
* Identifiant de l'utilisateur
* @return \Symfony\Component\Security\Core\User\UserInterface
*
*/
abstract public function getUser($username);
}

View file

@ -1,90 +0,0 @@
<?php
/**
* Abstract AuthAbstract
*
* @package Besancon\AuthBundle\Security\Abstracts
* @author Amine BEL HADJ ALI <amine.belhadjali@ac-besancon.fr>
*
* @method setGetterAttributes()
* @method getUser()
* @abstract
*/
namespace App\Session\AuthBundle\Security\Abstracts;
use App\Session\AuthBundle\Utils\Config;
use Symfony\Component\HttpFoundation\Response;
class AuthFinal extends AuthAbstract
{
/**
* Intancie le getters en fonction de la configuration
*
* Si dans la config le paramètre type_auth est défini à CAS alors
* intanciation du getter CasAttributes,
* Si la valeur est à RSA alors instanciation du getter RsaAttributes
*
* Cette instance peut ensuite être utilisée dans le service d'authentification
* qui héritera de AuthAbstract, en passant faisant appel à $this->ai
*
* @final
* @param $config
* configuration du Bundle
* @return void
*
* */
public function setGetterAttributes($config)
{
$type_auth = Config::getDeclaredType($config);
//dump('calls');
$getters = "\App\Session\AuthBundle\Security\Getters\\" . $type_auth . "Attributes";
$ai = new $getters();
$this->ai = $ai;
//dump($this->ai);
}
/**
* Comportement par défaut lorsque l'authentification n'aboutie pas (accès non autorisé)
*
* il est possible de redéfinir cette méthode
* mais elle doit renvoyer une réponse HTTP exemple:
* - Symfony\Component\HttpFoundation\Response
* - Symfony\Component\HttpFoundation\JsonResponse
*
* @param \Symfony\Component\Security\Core\Exception\AuthenticationException $exception
* Exception généré par le guard
* @return Symfony\Component\HttpFoundation\Response
*
* */
public function onAuthenticationFailure(\Symfony\Component\Security\Core\Exception\AuthenticationException $exception)
{
return new Response($exception->getMessage(), Response::HTTP_FORBIDDEN);
}
/**
* Renvoie une instance de l'utilisateur
*
* Ceci correspond à la class Besancon\AuthBundle\Security\User\AuthUser,
* il est possible de redéfinir cette méthode
* mais elle doit renvoyer un objet implementant Symfony\Component\Security\Core\User\UserInterface
*
* Est utilisé dans le userprovider par défaut Besancon\AuthBundle\Security\User\AuthUserProvider
*
* @see \Symfony\Component\Security\Core\User\UserInterface
* @see \Besancon\AuthBundle\Security\User\AuthUserProvider
*
* @param string $username
* Identifiant de l'utilisateur
* @return \Symfony\Component\Security\Core\User\UserInterface
*
*/
public function getUser($username)
{
$roles_service = $this->getRoles();
$roles = (!is_null($roles_service) && is_array($roles_service)) ? $roles_service : array();
$user = new \App\Besancon\AuthBundle\Security\User\AuthUser($username, md5("8sQaz87dPPsdanYakq86f" . $username), $roles);
return $user;
}
}

View file

@ -1,48 +0,0 @@
<?php
/**
* Abstract class GetterAbstract
*
* @package Besancon\AuthBundle\Security\Abstracts
* @author Amine BEL HADJ ALI <amine.belhadjali@ac-besancon.fr>
*/
namespace App\Session\AuthBundle\Security\Abstracts;
/**
* Description of GetterAbstract
*
* @author belhadjali
*/
abstract class GetterAbstract
{
public function isACP()
{
return $this->getFrEduFonctAdm() == "ACP";
}
public function isDIR()
{
return $this->getFrEduFonctAdm() == "DIR";
}
public function isDEC()
{
return $this->getFrEduFonctAdm() == "DEC";
}
public function isDIR1D()
{
return $this->isDEC();
}
public function isIEN1D()
{
return $this->getFrEduFonctAdm() == "IEN1D";
}
public function isDIO()
{
return $this->getFrEduFonctAdm() == "IEN1D";
}
}

View file

@ -1,27 +0,0 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace App\Session\AuthBundle\Security;
use App\Session\AuthBundle\Security\Interfaces\AuthInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use App\Session\AuthBundle\Utils\Config;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class AuthenticatorFactory
{
public static function getAuthenticator(AuthInterface $authService, array $config, UrlGeneratorInterface $urlGenerator, EventDispatcherInterface $dispatcher)
{
$type_auth = Config::getDeclaredType($config);
$authenticator_class = "App\Session\AuthBundle\Security\\" . $type_auth . "Authenticator";
$authenticator = new $authenticator_class($authService, $config, $urlGenerator, $dispatcher);
return $authenticator;
}
}

View file

@ -1,121 +0,0 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of CasAuthenticator
*
* @author belhadjali
*/
namespace App\Session\AuthBundle\Security;
use App\Session\AuthBundle\Security\Interfaces\AuthInterface;
use App\Session\AuthBundle\Events\OnAuthenticationFailureEvent;
use App\Session\AuthBundle\Events\OnAuthenticationSuccessEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Guard\AuthenticatorInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class CasAuthenticator extends AbstractFormLoginAuthenticator implements LogoutSuccessHandlerInterface, AuthenticatorInterface
{
private $authService;
private $urlGenerator;
public function __construct(AuthInterface $authService, array $config, UrlGeneratorInterface $urlGenerator, EventDispatcherInterface $dispatcher)
{
$this->urlGenerator = $urlGenerator;
//Récupérer le service déaclaré authService
$this->authService = $authService;
$this->config = $config;
$this->dispatcher = $dispatcher;
if (php_sapi_name() !== 'cli') {
\phpCAS::client(CAS_VERSION_2_0, $this->config['cas']["hostname"], $this->config['cas']["port"], $this->config['cas']["uri"]);
\phpCAS::setNoCasServerValidation();
\phpCAS::forceAuthentication();
}
}
/**
* Called on every request. Return whatever credentials you want,
* or null to stop authentication.
*/
public function getCredentials(Request $request)
{
return true;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$username = \phpCAS::getUser();
$user = $userProvider->loadUserByUsername($username);
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
return $this->authService->ctrlAccess($user);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$event = new OnAuthenticationSuccessEvent($request, $token, $providerKey);
$this->dispatcher->dispatch(OnAuthenticationSuccessEvent::NAME, $event);
$this->authService->onSuccess($token);
// on success, let the request continue
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$event = new OnAuthenticationFailureEvent($request, $exception);
$this->dispatcher->dispatch(OnAuthenticationFailureEvent::NAME, $event);
return $this->authService->onAuthenticationFailure($exception);
}
/**
* Called when authentication is needed, but it's not sent
*/
// public function start(Request $request, AuthenticationException $authException = null) {
// $url = $this->router->generate('login');
// return new RedirectResponse($url);
// }
public function supportsRememberMe()
{
return false;
}
//implementation LogoutSuccessHandlerInterface
public function onLogoutSuccess(Request $request)
{
$homepage = $this->config["homepage"];
return \phpCAS::logoutWithRedirectService($this->urlGenerator->generate($homepage, array(), UrlGeneratorInterface::ABSOLUTE_URL));
}
protected function getLoginUrl()
{
return \phpCas::getServerLoginURL();
}
public function supports(Request $request)
{
if (isset($this->config['environment']) && $this->config['environment'] == "test") {
return false;
}
return true;
}
}

View file

@ -1,114 +0,0 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace App\Session\AuthBundle\Security;
use App\Session\AuthBundle\Security\Auth\Authentication;
use App\Session\AuthBundle\Security\Auth\User;
use App\Session\AuthBundle\Security\Auth\UserProvider;
use App\Session\AuthBundle\Security\Interfaces\AuthInterface;
use App\Session\AuthBundle\Security\Abstracts\AuthFinal;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
use Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider;
use Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Core\User\UserChecker;
/**
* Description of DefaultAuthentication
*
* @author belhadjali
*/
class DefaultAuthentication extends AuthFinal implements AuthInterface
{
/**
* @var string Uniquely identifies the secured area
*/
private $providerKey;
public function authentificate($token)
{
$username = $this->ai->getUsername();
$password = "";
$unauthenticatedToken = new UsernamePasswordToken(
$username,
$password,
'secured_area'
);
$userProvider = new UserProvider(
new Authentication(),
array('user_entity' => 'App\Session\AuthBundle\Security\Auth\User',
'type_auth' => 'Cas')
);
$userChecker = new UserChecker();
$defaultEncoder = new MessageDigestPasswordEncoder('sha512', true, 5000);
$encoders = [
User::class => $defaultEncoder,
];
$encoderFactory = new EncoderFactory($encoders);
$provider = new DaoAuthenticationProvider(
$userProvider,
$userChecker,
'secured_area',
$encoderFactory
);
$authenticatedToken = $provider
->authenticate($unauthenticatedToken);
//$tokenStorage = new TokenStorage();
//$tokenStorage->setToken($authenticatedToken);
}
public function getRoles()
{
return [];
}
public function onSuccess($token)
{
//dump($this->ai);
//die('success');
//$this->authentificate($token);
$token->setAttribute("username", $this->ai->getUsername());
$token->setAttribute("complet_name", $this->ai->getCompletName());
$token->setAttribute("mail", $this->ai->getMail());
$token->setAttribute("FreDuRne", $this->ai->getFreDuRne());
return;
}
public function ctrlAccess(\Symfony\Component\Security\Core\User\UserInterface $user)
{
//die('ctrlAccess');
return true;
}
public function getUser($username)
{
return parent::getUser($username);
}
}

View file

@ -1,89 +0,0 @@
<?php
/**
* @package Besancon\AuthBundle\Security\Getters
* @author Amine BEL HADJ ALI <amine.belhadjali@ac-besancon.fr>
*/
namespace App\Session\AuthBundle\Security\Getters;
use App\Session\AuthBundle\Security\Interfaces\AttributesInterface;
/**
* Class CasAttributes
*
* Cette classe permet d'accèder aux informations (attributs) de l'utilisateur
* renvoyé par CAS à partir des méthodes d'accès définies dans l'interface AttributesInterface
*
*/
class CasAttributes implements AttributesInterface
{
public function getFirstName()
{
return \phpCAS::getAttribute("prenom");
}
public function getCompletName()
{
return \phpCAS::getAttribute("nomcomplet");
}
public function getName()
{
return \phpCAS::getAttribute("nom");
}
public function getDiscipline()
{
return \phpCAS::getAttribute("discipline");
}
public function getFonctM()
{
return \phpCAS::getAttribute("fonctm");
}
public function getRne()
{
return \phpCAS::getAttribute("rne");
}
public function getFreDuRne()
{
return \phpCAS::getAttribute("FrEduRne");
}
public function getFreDuRneResp()
{
return \phpCAS::getAttribute("FrEduRneResp");
}
public function getMail()
{
return \phpCAS::getAttribute("mail");
}
public function getTitle()
{
return \phpCAS::getAttribute("title");
}
public function getUsername()
{
return \phpCAS::getUser();
}
public function getFrEduResDel()
{
return \phpCAS::getAttribute("FrEduResDel");
}
public function getFrEduFonctAdm()
{
return \phpCAS::getAttribute("FrEduFonctAdm");
}
public function getGrade()
{
return \phpCAS::getAttribute("grade");
}
}

View file

@ -1,93 +0,0 @@
<?php
/**
* Class RsaAttributes
*
* @package Besancon\AuthBundle\Security\Getters
* @author Amine BEL HADJ ALI <amine.belhadjali@ac-besancon.fr>
*
*/
namespace App\Besancon\AuthBundle\Security\Getters;
use App\Besancon\AuthBundle\Security\Interfaces\AttributesInterface;
/**
* Class RsaAttributes
*
* Cette classe permet d'accèder aux informations (entête HTTP) de l'utilisateur
* renvoyé par RSA CT à partir des méthodes d'accès définies dans l'interface AttributesInterface
*
*/
class RsaAttributes implements AttributesInterface
{
public function getCompletName()
{
return (isset($_SERVER['HTTP_CN'])) ? $_SERVER['HTTP_CN'] : null;
}
public function getDiscipline()
{
return (isset($_SERVER['HTTP_DISCIPLINE'])) ? $_SERVER['HTTP_DISCIPLINE'] : null;
}
public function getFonctM()
{
return (isset($_SERVER['HTTP_FONCTM'])) ? $_SERVER['HTTP_FONCTM'] : null;
}
public function getRne()
{
return (isset($_SERVER['HTTP_RNE'])) ? $_SERVER['HTTP_FREDURNE'] : null;
}
public function getFreDuRne()
{
return (isset($_SERVER['HTTP_FREDURNE'])) ? explode(',', $_SERVER['HTTP_FREDURNE']) : null;
}
public function getFreDuRneResp()
{
return (isset($_SERVER['HTTP_FREDURNERESP'])) ? explode(',', $_SERVER['HTTP_FREDURNERESP']) : null;
}
public function getMail()
{
return (isset($_SERVER['HTTP_CTEMAIL'])) ? $_SERVER['HTTP_CTEMAIL'] : null;
}
public function getTitle()
{
return (isset($_SERVER['HTTP_TITLE'])) ? $_SERVER['HTTP_TITLE'] : null;
}
public function getUsername()
{
return (isset($_SERVER['HTTP_CT_REMOTE_USER'])) ? $_SERVER['HTTP_CT_REMOTE_USER'] : null;
}
public function getFrEduResDel()
{
return (isset($_SERVER['HTTP_FREDURESDEL'])) ? $_SERVER['HTTP_FREDURESDEL'] : null;
}
public function getFrEduFonctAdm()
{
return (isset($_SERVER['HTTP_FREDUFONCTADM'])) ? $_SERVER['HTTP_FREDUFONCTADM'] : null;
}
public function getFirstName()
{
return (isset($_SERVER['HTTP_CTFN'])) ? $_SERVER['HTTP_CTFN'] : null;
}
public function getName()
{
return (isset($_SERVER['HTTP_CTLN'])) ? $_SERVER['HTTP_CTLN'] : null;
}
public function getGrade()
{
return (isset($_SERVER['HTTP_GRADE'])) ? $_SERVER['HTTP_GRADE'] : null;
}
}

View file

@ -1,89 +0,0 @@
<?php
/**
* @package Besancon\AuthBundle\Security\Getters
* @author Amine BEL HADJ ALI <amine.belhadjali@ac-besancon.fr>
*/
namespace App\Session\AuthBundle\Security\Getters;
use App\Session\AuthBundle\Security\Interfaces\AttributesInterface;
/**
* Class CasAttributes
*
* Cette classe permet d'accèder aux informations (attributs) de l'utilisateur
* renvoyé par CAS à partir des méthodes d'accès définies dans l'interface AttributesInterface
*
*/
class SessionAttributes implements AttributesInterface
{
public function getFirstName()
{
return ;
}
public function getCompletName()
{
return ;
}
public function getName()
{
return ;
}
public function getDiscipline()
{
return ;
}
public function getFonctM()
{
return ;
}
public function getRne()
{
return ;
}
public function getFreDuRne()
{
return ;
}
public function getFreDuRneResp()
{
return ;
}
public function getMail()
{
return ;
}
public function getTitle()
{
return ;
}
public function getUsername()
{
return ;
}
public function getFrEduResDel()
{
return ;
}
public function getFrEduFonctAdm()
{
return ;
}
public function getGrade()
{
return ;
}
}

View file

@ -1,214 +0,0 @@
<?php
/**
* Interface AttributesInterface
*
* @package Besancon\AuthBundle\Security\Interfaces
* @author Amine BEL HADJ ALI <amine.belhadjali@ac-besancon.fr>
*
*/
namespace App\Session\AuthBundle\Security\Interfaces;
/**
* Interface AttributesInterface
*
*/
interface AttributesInterface
{
const NO_VALUE = "X";
const FREDURNE_OFFSET_RNE = 0;
const FREDURNE_OFFSET_SECTEUR = 2;
const FREDURNE_OFFSET_FONCTION_EXERCICE = 3;
const FREDURNE_OFFSET_FONCTION_RNEUAJ = 4;
const FREDURNE_OFFSET_1CODETNA = 5; // 1er chiffre code nature nomenclature
const FREDURNE_OFFSET_CODETTY = 6; // code type etablissement nomenclature
const FREDURNE_OFFSET_CODETNA = 7; // code nature etablissement nomenclature
const FREDURNERESP_OFFSET_RNE = 0;
const FREDURNERESP_OFFSET_SECTEUR = 2; //PU ou PR
const FREDURNERESP_OFFSET_AFFECTATION = 3; // A pour Affectation anticipé N pour affectation normale F pour affectation qui fini le 31/08
const FREDURNERESP_OFFSET_1CODETNA = 4; // 1er chiffre code nature nomenclature
const FREDURNERESP_OFFSET_CODETTY = 5; // code type etablissement nomenclature
const FREDURNERESP_OFFSET_CODETNA = 6; // code nature nomenclature
const TYPE_LYCEE_GENERAL = "LYC";
const TYPE_LYCEE_PRO = "LP";
const TYPE_COLLEGE = "CLG";
const TYPE_SEGPA = "SES";
const CODE_NATURE_RECTORAT = ["802"];
const CODE_NATURE_DSDEN = ["806"];
const CODE_NATURE_INSPECTION = ["809"];
const CODE_NATURE_LYCEE_GENERAL_ET_TECHNO = ["300"];
const CODE_NATURE_LYCEE_TECHNO = ["301"];
const CODE_NATURE_LYCEE_GENERAL = ["302", "306"];
const CODE_NATURE_LYCEE_AGRICOLE = ["307"];
const CODE_NATURE_LYCEE_PRO = ["320"];
const CODE_NATURE_COLLEGE = ["340"];
const CODE_COLLEGE_NATURE_SPE = ["352"];
const CODE_NATURE_SEGPA = ["390"];
const GRADES_IEN = ["1152", "1151"];
const GRADES_RECTEUR = ["0201"];
const GRADES_SG = ["0211", "0911", "0912"];
const GRADES_ASG = ["0981"];
const GRADES_DASEN = ["0921", "0922"];
const GRADES_ADJOINT_DASEN = ["0971"];
const CODES_DISCIPLINE_ASH = ["N0006"];
const CODES_DISCIPLINE_DIR = ["D0010"];
const CODES_DISCIPLINE_ADJOINT_DIR = ["D0011"];
/**
* Renvoie le prénom de l'agent
*
* Correspond au champ "givenName" du LDAP
*
* @return string|null
* prénom de l'agent
*/
public function getFirstName();
/**
* Renvoie l'identifiant LDAP de l'agent
*
* Correspond au champ "uid" du LDAP
*
* @return string|null
* uid de l'agent
*/
public function getUsername();
/**
* Renvoie le nom de famille de l'agent
*
* Correspond au champ "sn" du LDAP
*
* @return string|null
* nom de l'agent
*/
public function getName();
/**
* Renvoie l'adresse mail de l'agent
*
* Correspond au champ "mail" du LDAP
*
* @return string|null
* adresse mail de l'agent
*/
public function getMail();
/**
* Renvoie le nom complet de l'agent
*
* Correspond au champ "cn" du LDAP
*
* @return string|null
* nom complete de l'agent
*/
public function getCompletName();
/**
* Renvoie le title de l'agent
*
* Correspond au champ "title" du LDAP
*
* @return string|null
* title de l'agent
*/
public function getTitle();
/**
* Renvoie le code discipline de l'agent
*
* Correspond au champ "discipline" du LDAP
*
* @return string|null
* code discipline de l'agent
*/
public function getDiscipline();
/**
* Renvoie l'établissements d'affectation de l'agent
*
* Correspond au champ "rne" du LDAP
*
* @return string|null
* * établissement d'affectation de l'agent
*/
public function getRne();
/**
* Renvoie l'établissements dexercice de l'agent
*
* Correspond au champ "FreDuRne" du LDAP
*
* @return array|null
* établissement(s) d'exercice de l'agent
*/
public function getFreDuRne();
/**
* Renvoie le(s) établissement(s) en responsabilité de l'agent
*
* Correspond au champ "FreDuRneResp" du LDAP
*
* @return array|null
* établissement(s) en responsabalité de l'agent
*/
public function getFreDuRneResp();
/**
* Renvoie le(s) déléguation(s)/attribution(s) de l'agent ouvrant des droits d'accès
* à une ressource d'une application pour un ou des rne
*
* Correspond au champ "FreDuRneDel" du LDAP
*
* @return array|null
* déléguation(s)/attribution(s) de l'agent
*/
public function getFrEduResDel();
/**
* Renvoie la fonction administrative de l'agent
* correspondant à un profil particulier
*
* Correspond au champ "FrEduFonctAdm" du LDAP
*
* @return string|null
* fonction administrative de l'agent
*/
public function getFrEduFonctAdm();
/**
* Renvoie la fonction de l'agent
* Attention : initialisé à la création de la fiche avec la même valeur que lattribut fonction.
* Puis, par lapplication Annuaire, lagent peut le modifier.
*
* Correspond au champ "fonctm" du LDAP
*
* @return string|null
* fonction de l'agent
*/
public function getFonctM();
/**
* Renvoie le grade de l'agent
* Alimenté à partir de la valeur agt.gradco
* Se référer à la base des nomenclatures dans la table N_GRADE pour voir
* les correspondances : http://infocentre.pleiade.education.fr/bcn/workspace/viewTable/n/N_GRADE
*
* Correspond au champ "grade" du LDAP
*
* @return string|null
* fonction de l'agent
*/
public function getGrade();
}

View file

@ -1,100 +0,0 @@
<?php
/**
* Interface AuthInterface
*
* Interface permettant de déclarer les méthodes incontournables pour l'authentification
*
*
* @package Besancon\AuthBundle\Security\Interfaces
* @author Amine BEL HADJ ALI <amine.belhadjali@ac-besancon.fr>
*
*/
namespace App\Session\AuthBundle\Security\Interfaces;
use Symfony\Component\Security\Core\User\UserInterface;
interface AuthInterface
{
/**
* Contrôle de l'accès à partir des attributs CAS ou RSA
*
* Vérifier les droits d'accès à l'application à partir des attributs récupérées des getters :
* - CasAttributes
* - RsaAttributes
*
* @param UserInterface $user
* L'entité user récupéré par le provider
*
* @return bool
* - true si accès autorisé
* - false si accès refusé
*/
public function ctrlAccess(UserInterface $user);
/**
* Calcule et retoune le(s) rôle(s) à partir des attributs CAS ou RSA
*
* Calculer le(s) rôle(s) à partir des attributs récupérées des getters :
* - CasAttributes
* - RsaAttributes
* Doit retourner un tableau même vide
*
* @return array
*/
public function getRoles();
/**
* Retourne un utilisateur pour la génération du token, si l'utilisateur n'existe pas en base de donnée
*
* ATTENTION : CETTE METHODE DOIT ÊTRE REDEFINIE SI UTILISATION D'UNE ENTITE UTILISTEUR
* DIFFERENTE DE CELLE UTILISEE PAR DEFAUT
*
* @param String $username
* uid de l'utilisateur récupéré de Cas ou Rsa
*
* @return UserInterface
*/
public function getUser($username);
/**
* Traitement personnalisé après récupération du token
*
* Il est possible d'enrichir le token (attributs...) ou d'effectuer des contrôles supplémentaire
*
* @param $token
* Token d'authification généré
*
* @return null
*/
public function onSuccess($token);
/**
* Traitement personnalisé lorsque la connexion n'a pas abouti
*
* Vérifié l'exception généré et adapter l'action (redirection, déconnexion...)
*
* Doit retourner un objet de type Response
*
* Exemple :
*
* ```
* public function onAuthenticationFailure(\Symfony\Component\Security\Core\Exception\AuthenticationException $exception)
* {
* $content = $this->twig->render(
* '@App/Test/forbiden.html.twig', array()
* );
* $response = new Response($content, Response::HTTP_FORBIDDEN);
* return $response;
* }
* ```
*
* @param AuthenticationException $exception
* Exception générée par le provider
*
* @return Symfony\Component\HttpFoundation\Response
*
*/
public function onAuthenticationFailure(\Symfony\Component\Security\Core\Exception\AuthenticationException $exception);
}

View file

@ -1,128 +0,0 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of CasAuthenticator
*
* @author belhadjali
*/
namespace App\Session\AuthBundle\Security;
use App\Session\AuthBundle\Security\Interfaces\AuthInterface;
use App\Session\AuthBundle\Events\OnAuthenticationFailureEvent;
use App\Session\AuthBundle\Events\OnAuthenticationSuccessEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Guard\AuthenticatorInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class RsaAuthenticator extends AbstractFormLoginAuthenticator implements LogoutSuccessHandlerInterface, AuthenticatorInterface
{
private $authService;
private $urlGenerator;
private $dispatcher;
public function __construct(AuthInterface $authService, array $config, UrlGeneratorInterface $urlGenerator, EventDispatcherInterface $dispatcher)
{
$this->urlGenerator = $urlGenerator;
//Récupérer le service déaclaré authService
$this->authService = $authService;
$this->config = $config;
$this->dispatcher = $dispatcher;
}
/**
* Called on every request. Return whatever credentials you want,
* or null to stop authentication.
*/
public function getCredentials(Request $request)
{
if (!isset($_SERVER['HTTP_CT_REMOTE_USER']) || empty($_SERVER['HTTP_CT_REMOTE_USER'])) {
$this->returnRequest = $request->getUri();
throw new \LogicException("Impossible de continuer sous RSA : L'entête HTTP_CT_REMOTE_USER est vide ou manquante");
}
return true;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$username = $_SERVER['HTTP_CT_REMOTE_USER'];
$user = $userProvider->loadUserByUsername($username);
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
$this->authService->ctrlAccess($user);
// check credentials - e.g. make sure the password is valid
// no credential check is needed in this case
// return true to cause authentication success
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$event = new OnAuthenticationSuccessEvent($request, $token, $providerKey);
$this->dispatcher->dispatch(OnAuthenticationSuccessEvent::NAME, $event);
$this->authService->onSuccess($token);
// on success, let the request continue
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$event = new OnAuthenticationFailureEvent($request, $exception);
$this->dispatcher->dispatch(OnAuthenticationFailureEvent::NAME, $event);
return $this->authService->onAuthenticationFailure($exception);
}
/**
* Called when authentication is needed, but it's not sent
*/
// public function start(Request $request, AuthenticationException $authException = null) {
// $url = $this->router->generate('login');
// return new RedirectResponse($url);
// }
public function supportsRememberMe()
{
return false;
}
//implementation LogoutSuccessHandlerInterface
public function onLogoutSuccess(Request $request)
{
$redirect = (isset($_SERVER['HTTP_FREDUURLRETOUR'])) ? $_SERVER['HTTP_FREDUURLRETOUR'] : $this->config['rsa']['logout_url'];
return new RedirectResponse($redirect);
}
protected function getLoginUrl()
{
$return_request = urlencode($this->returnRequest);
$params = "?CT_ORIG_URL=" . $return_request;
return $this->config['rsa']['login_url'] . $params;
}
public function supports(Request $request)
{
if (isset($this->config['environment']) && $this->config['environment'] == "test") {
return false;
}
return true;
}
}

View file

@ -1,124 +0,0 @@
<?php
namespace App\Session\AuthBundle\Security;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
class SessionAuthenticator extends AbstractGuardAuthenticator
{
public $router;
public function __construct(UrlGeneratorInterface $router)
{
$this->router = $router;
}
/**
* Called on every request to decide if this authenticator should be
* used for the request. Returning `false` will cause this authenticator
* to be skipped.
*/
public function supports(Request $request)
{
if (isset($_SESSION['id_utilisateur'])) {
return true;
} else {
return true;
}
}
/**
* Called on every request. Return whatever credentials you want to
* be passed to getUser() as $credentials.
*/
public function getCredentials(Request $request)
{
return "X-AUTH-TOKEN-SESSION-API";
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
if (!isset($_SESSION['id_utilisateur'])) {
$user = new \App\Classes\AuthUser('', '', '', '', '', ['ROLE_USER']);
} else {
$user = new \App\Classes\AuthUser($_SESSION['id_utilisateur'], $_SESSION['identifiant'], $_SESSION['status_compte'], $_SESSION['type_compte'], $credentials, ['ROLE_USER', 'ROLE_USER_CONNECTED']);
}
// if a User is returned, checkCredentials() is called
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
// Check credentials - e.g. make sure the password is valid.
// In case of an API token, no credential check is needed.
// Return `true` to cause authentication success
if ($user->getCredentials() === $credentials) {
return true;
} else {
return false;
}
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
// on success, let the request continue
//return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = [
// you may want to customize or obfuscate the message first
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
// or to translate this message
// $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
];
// return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
$url = $this->router->generate('unauthorized');
return new RedirectResponse($url);
}
/**
* Called when authentication is needed, but it's not sent
*/
public function start(Request $request, AuthenticationException $authException = null)
{
$data = [
// you might translate this message
'message' => 'Authentication Required'
];
//return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
$url = $this->router->generate('unauthorized');
return new RedirectResponse($url);
}
public function supportsRememberMe()
{
return false;
}
public function onLogoutSuccess(Request $request)
{
//$homepage = $this->config["homepage"];
//return \phpCAS::logoutWithRedirectService($this->urlGenerator->generate($homepage, array(), UrlGeneratorInterface::ABSOLUTE_URL));
header('Location: /index.php');
return ;
}
}

View file

@ -1,332 +0,0 @@
<?php
namespace App\Session\AuthBundle\Security\Traits;
use App\Session\AuthBundle\Security\Interfaces\AttributesInterface;
trait ProfilsCalculator
{
//est recteur
public function isRecteur()
{
return in_array($this->ai->getDiscipline(), AttributesInterface::GRADES_RECTEUR);
}
//est secrétaire général d'académie
public function isSG()
{
return in_array($this->ai->getDiscipline(), AttributesInterface::GRADES_SG);
}
//est adjoint au secrétaire général d'académie
public function isASG()
{
return in_array($this->ai->getDiscipline(), AttributesInterface::GRADES_ASG);
}
//agent comptable
public function isACP()
{
return $this->ai->getFrEduFonctAdm() == "ACP";
}
//enseignant
public function isENS()
{
return $this->ai->getFrEduFonctAdm() == AttributesInterface::NO_VALUE && $this->ai->getTitle() == "ENS" && $this->ai->getFrEduRneResp() == AttributesInterface::NO_VALUE;
}
//agent issue d'AGAPE PRIVE
public function isAgentPrive()
{
return $this->ai->getTypensi() == "R";
}
//equipe de direction établissement
public function isGroupeDIR()
{
return $this->ai->getFrEduFonctAdm() == "DIR";
}
//directeur 2nd degré
public function isDIR()
{
return $this->isGroupeDIR() && in_array($this->ai->getDiscipline(), AttributesInterface::CODES_DISCIPLINE_DIR);
}
//directeur adjoint 2nd degré
public function isAdjointDIR()
{
return $this->isGroupeDIR() && in_array($this->ai->getDiscipline(), AttributesInterface::CODES_DISCIPLINE_ADJOINT_DIR);
}
//directeur d'ecole
public function isDEC()
{
return $this->ai->getFrEduFonctAdm() == "DEC";
}
//alias directeur d'ecole
public function isDIR1D()
{
return $this->isDEC();
}
//adaptation scolaire et de la scolarisation des élèves handicapé
public function isASH()
{
return in_array($this->ai->getDiscipline(), AttributesInterface::CODES_DISCIPLINE_ASH);
}
//est inspecteur
public function isIEN()
{
return (!is_null($this->ai->getGrade())) ? in_array($this->ai->getGrade(), AttributesInterface::GRADES_IEN) : $this->ai->getTitle() == "INS";
}
//est inspecteur 1er degré
public function isIEN1D()
{
return $this->isIEN() && $this->ai->getFrEduFonctAdm() == "IEN1D";
}
//est inspecteur ASH
public function isIENASH()
{
return $this->isASH() && $this->isIEN();
}
//est DASEN
public function isDASEN()
{
return in_array($this->ai->getGrade(), AttributesInterface::GRADES_DASEN);
}
//est adjoint DASEN
public function isAdjointDasen()
{
return in_array($this->ai->getGrade(), AttributesInterface::GRADES_ADJOINT_DASEN);
}
//est directeur CIO
public function isDIO()
{
return $this->ai->getFrEduFonctAdm() == "DIO";
}
public function filterFrEduRneByType($type)
{
if ($this->ai->getFrEduRne() == AttributesInterface::NO_VALUE) {
return [];
}
$FrEduRne = (!is_array($this->ai->getFrEduRne())) ? [$this->ai->getFrEduRne()] : $this->ai->getFrEduRne();
$uais = array_filter($FrEduRne, function ($value) use ($type) {
$arr_value = explode("$", $value);
if (!is_array($arr_value) || !array_key_exists(AttributesInterface::FREDURNE_OFFSET_CODETTY, $arr_value)) {
return false;
}
if (is_array($type)) {
return in_array($arr_value[AttributesInterface::FREDURNE_OFFSET_CODETTY], $type);
}
return $arr_value[AttributesInterface::FREDURNE_OFFSET_CODETTY] == $type;
});
return $uais;
}
public function filterFrEduRneByNature($nature)
{
if ($this->ai->getFrEduRne() == AttributesInterface::NO_VALUE) {
return [];
}
$FrEduRne = (!is_array($this->ai->getFrEduRne())) ? [$this->ai->getFrEduRne()] : $this->ai->getFrEduRne();
$uais = array_filter($FrEduRne, function ($value) use ($nature) {
$arr_value = explode("$", $value);
if (!is_array($arr_value) || !array_key_exists(AttributesInterface::FREDURNE_OFFSET_CODETNA, $arr_value)) {
return false;
}
if (is_array($nature)) {
return in_array($arr_value[AttributesInterface::FREDURNE_OFFSET_CODETNA], $nature);
}
return $arr_value[AttributesInterface::FREDURNE_OFFSET_CODETNA] == $nature;
});
return $uais;
}
public function filterFrEduRneRespByNature($nature)
{
if ($this->ai->getFrEduRneResp() == AttributesInterface::NO_VALUE) {
return [];
}
$FrEduRneResp = (!is_array($this->ai->getFrEduRneResp())) ? [$this->ai->getFrEduRneResp()] : $this->ai->getFrEduRneResp();
$uais = array_filter($FrEduRneResp, function ($value) use ($nature) {
$arr_value = explode("$", $value);
if (!is_array($arr_value) || !array_key_exists(AttributesInterface::FREDURNERESP_OFFSET_CODETNA, $arr_value)) {
return false;
}
if (is_array($nature)) {
return in_array($arr_value[AttributesInterface::FREDURNERESP_OFFSET_CODETNA], $nature);
}
return $arr_value[AttributesInterface::FREDURNERESP_OFFSET_CODETNA] == $nature;
});
return $uais;
}
public function filterFrEduRneRespByType($type)
{
if ($this->ai->getFrEduRneResp() == AttributesInterface::NO_VALUE) {
return [];
}
$FrEduRneResp = (!is_array($this->ai->getFrEduRneResp())) ? [$this->ai->getFrEduRneResp()] : $this->ai->getFrEduRneResp();
$uais = array_filter($FrEduRneResp, function ($value) use ($type) {
$arr_value = explode("$", $value);
if (!is_array($arr_value) || !array_key_exists(AttributesInterface::FREDURNERESP_OFFSET_CODETTY, $arr_value)) {
return false;
}
if (is_array($type)) {
return in_array($arr_value[AttributesInterface::FREDURNERESP_OFFSET_CODETTY], $type);
}
return $arr_value[AttributesInterface::FREDURNERESP_OFFSET_CODETTY] == $type;
});
return $uais;
}
// public function hasLYC()
// {
// return $this->findUaiRespByType(AttributesInterface::TYPE_LYCEE_GENERAL);
// }
// public function hasLYCP()
// {
// return $this->findUaiRespByType(AttributesInterface::TYPE_LYCEE_PRO);
// }
public function isAffectedToRectorat()
{
$result = $this->filterFrEduRneByNature(AttributesInterface::CODE_NATURE_RECTORAT);
return (count($result)) ? true : false;
}
public function isAffectedToDSDEN()
{
$result = $this->filterFrEduRneByNature(AttributesInterface::CODE_NATURE_DSDEN);
return (count($result)) ? true : false;
}
public function isAffectedToLYC()
{
$result = $this->filterFrEduRneByType(AttributesInterface::TYPE_LYCEE_GENERAL);
return (count($result)) ? true : false;
}
public function isAffectedToLP()
{
$result = $this->filterFrEduRneByType(AttributesInterface::TYPE_LYCEE_PRO);
return (count($result)) ? true : false;
}
public function isAffectedToInspection()
{
$result = $this->filterFrEduRneByNature(AttributesInterface::CODE_NATURE_INSPECTION);
return (count($result)) ? true : false;
}
public function isAffectedToSEGPA()
{
$result = $this->filterFrEduRneByType(AttributesInterface::TYPE_SEGPA);
return (count($result)) ? true : false;
}
public function isRespOfLYC()
{
$result = $this->filterFrEduRneRespByType(AttributesInterface::TYPE_LYCEE_GENERAL);
return (count($result)) ? true : false;
}
public function isRespOfLP()
{
$result = $this->filterFrEduRneRespByType(AttributesInterface::TYPE_LYCEE_PRO);
return (count($result)) ? true : false;
}
public function isRespOfSEGPA()
{
$result = $this->filterFrEduRneRespByType(AttributesInterface::TYPE_SEGPA);
return (count($result)) ? true : false;
}
/****************************************************************************************
* Filtres sur FrEduRne
***************************************************************************************/
public function filterFrEduRneByLYCG()
{
return $this->filterFrEduRneByNature(AttributesInterface::CODE_NATURE_LYCEE_GENERAL);
}
public function filterFrEduRneByLYCGT()
{
return $this->filterFrEduRneByNature(AttributesInterface::CODE_NATURE_LYCEE_GENERAL_ET_TECHNO);
}
public function filterFrEduRneByLP()
{
return $this->filterFrEduRneByNature(AttributesInterface::CODE_NATURE_LYCEE_GENERAL_ET_TECHNO);
}
public function filterFrEduRneByCLG()
{
return $this->filterFrEduRneByNature(AttributesInterface::CODE_NATURE_COLLEGE);
}
public function filterFrEduRneByLYCAG()
{
return $this->filterFrEduRneByNature(AttributesInterface::CODE_NATURE_LYCEE_AGRICOLE);
}
public function filterFrEduRneBySEGPA()
{
return $this->filterFrEduRneByNature(AttributesInterface::CODE_NATURE_SEGPA);
}
/****************************************************************************************
* Filtres sur FrEduRneResp
***************************************************************************************/
public function filterFrEduRneRespByLYCG()
{
return $this->filterFrEduRneRespByNature(AttributesInterface::CODE_NATURE_LYCEE_GENERAL);
}
public function filterFrEduRneRespByLYCGT()
{
return $this->filterFrEduRneRespByNature(AttributesInterface::CODE_NATURE_LYCEE_GENERAL_ET_TECHNO);
}
public function filterFrEduRneRespByLP()
{
return $this->filterFrEduRneRespByNature(AttributesInterface::CODE_NATURE_LYCEE_GENERAL_ET_TECHNO);
}
public function filterFrEduRneRespByCLG()
{
return $this->filterFrEduRneRespByNature(AttributesInterface::CODE_NATURE_COLLEGE);
}
public function filterFrEduRneRespByLYCAG()
{
return $this->filterFrEduRneRespByNature(AttributesInterface::CODE_NATURE_LYCEE_AGRICOLE);
}
public function filterFrEduRneRespBySEGPA()
{
return $this->filterFrEduRneRespByNature(AttributesInterface::CODE_NATURE_SEGPA);
}
}

View file

@ -1,83 +0,0 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of AuthUser
*
* @author belhadjali
*/
namespace App\Session\AuthBundle\Security\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;
class AuthUser implements UserInterface, EquatableInterface
{
private $username;
private $salt;
private $roles = [];
public function __construct($username, $salt, array $roles = [])
{
$this->username = $username;
$this->salt = $salt;
$this->roles = $roles;
}
public function getRoles()
{
return $this->roles;
}
public function setRoles($roles)
{
return $this->roles = $roles;
}
public function addRole($role)
{
return $this->roles[] = $role;
}
public function getPassword()
{
return;
}
public function getSalt()
{
return $this->salt;
}
public function getUsername()
{
return $this->username;
}
public function eraseCredentials()
{
}
public function isEqualTo(UserInterface $user)
{
if (!$user instanceof AuthUser) {
return false;
}
if ($this->salt !== $user->getSalt()) {
return false;
}
if ($this->username !== $user->getUsername()) {
return false;
}
return true;
}
}

View file

@ -1,62 +0,0 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace App\Session\AuthBundle\Security\User;
use App\Besancon\AuthBundle\Security\Interfaces\AuthInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
class AuthUserProvider implements UserProviderInterface
{
public function __construct(AuthInterface $authService, array $config)
{
$this->config = $config;
if (!is_null($this->config['user_entity'])) {
$this->entity_user = "\\".$this->config['user_entity'];
} else {
$this->entity_user = "App\Session\AuthBundle\Security\User\AuthUser";
}
$this->authService = $authService;
}
public function loadUserByUsername($username)
{
$entity_user = $this->entity_user;
return $this->authService->getUser($username);
}
private function _ctrlInstanceUser(UserInterface $user)
{
$entity_user = $this->entity_user;
if (!$user instanceof $entity_user) {
throw new UnsupportedUserException(
sprintf('Instances of "%s" are not supported.', get_class($user))
);
}
return $user;
}
public function refreshUser(UserInterface $user)
{
$user = $this->_ctrlInstanceUser($user);
return $this->loadUserByUsername($user->getUsername());
}
public function supportsClass($class)
{
$entity_user = $this->entity_user;
return $this->entity_class === $class;
}
}

View file

@ -1,9 +0,0 @@
<?php
namespace App\Session\AuthBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class SessionAuthBundle extends Bundle
{
}

View file

@ -1,17 +0,0 @@
<?php
namespace App\Session\AuthBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/');
$this->assertContains('Hello World', $client->getResponse()->getContent());
}
}

View file

@ -1,43 +0,0 @@
<?php
namespace App\Session\AuthBundle\Utils;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Controls
*
* @author belhadjali
*/
class Config
{
public static function getDeclaredType($config)
{
if (!isset($config['type_auth'])) {
throw new \LogicException('Paramètre type_auth manquant');
}
$type = $config['type_auth'];
self::typeIsSupported($type);
return self::formatType($type);
}
public static function formatType($type)
{
return ucfirst(strtolower($type));
}
public static function typeIsSupported($type)
{
$type_auth = self::formatType($type);
if (!in_array($type_auth, ['Rsa', 'Cas'])) {
throw new \LogicException('Seuls Cas et Rsa sont supportés pour le moment');
}
return true;
}
}

View file

@ -1,12 +0,0 @@
{
"name": "ac-besancon/authbundle",
"description": "Bundle Symfony 3 permettant de mettre en palce une authentification CAS ou RSA à travers le système de Guard",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Amine Belhadjali",
"email": "amine.belhadjali@ac-besancon.fr"
}
]
}