Bladeren bron

Role dans User Merchant

feature/ticket
Fab 2 jaren geleden
bovenliggende
commit
091aa87feb
10 gewijzigde bestanden met toevoegingen van 342 en 21 verwijderingen
  1. +11
    -8
      Controller/AbstractAdminController.php
  2. +64
    -0
      Controller/User/UserAdminController.php
  3. +25
    -0
      DependencyInjection/Configuration.php
  4. +18
    -9
      DependencyInjection/LcCaracoleExtension.php
  5. +3
    -3
      EventSubscriber/MerchantSectionPropertyEventSubscriber.php
  6. +59
    -0
      EventSubscriber/User/InitUserMerchantEventSubscriber.php
  7. +95
    -0
      EventSubscriber/User/UserRolesEventSubscriber.php
  8. +22
    -0
      Factory/User/UserMerchantFactory.php
  9. +29
    -1
      Model/User/UserMerchantModel.php
  10. +16
    -0
      Resources/config/services.yaml

+ 11
- 8
Controller/AbstractAdminController.php Bestand weergeven

use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpFoundation\Session\SessionInterface;



//TODO ce fichier ne devrait plus exister
abstract class AbstractAdminController extends SovAbstractAdminController abstract class AbstractAdminController extends SovAbstractAdminController
{ {
protected $session; protected $session;
protected $merchantResolver; protected $merchantResolver;
protected $sectionResolver; protected $sectionResolver;


public function __construct(SessionInterface $session, RequestStack $request, EntityManager $em, TranslatorAdmin $translatorAdmin, SectionResolver $sectionResolver, MerchantResolver $merchantResolver)

public static function getSubscribedServices()
{ {
parent::__construct($session, $request, $em, $translatorAdmin);
$this->merchantResolver = $merchantResolver;
$this->sectionResolver = $sectionResolver;
return array_merge(parent::getSubscribedServices(), [
'merchant_resolver' => MerchantResolver::class,
'section_resolver' => SectionResolver::class,


]);
} }

public function createIndexQueryBuilder( public function createIndexQueryBuilder(
SearchDto $searchDto, SearchDto $searchDto,
EntityDto $entityDto, EntityDto $entityDto,
$filters $filters
); );


//TODO Gérer depuis les événements


if ($this->isInstanceOf(FilterMerchantInterface::class)) { if ($this->isInstanceOf(FilterMerchantInterface::class)) {
$queryBuilder->andWhere('entity.merchant = :merchant'); $queryBuilder->andWhere('entity.merchant = :merchant');
$queryBuilder->setParameter('merchant', $this->merchantResolver->getCurrent());
$queryBuilder->setParameter('merchant', $this->get('merchant_resolver')->getCurrent());
} }


if ($this->isInstanceOf(FilterSectionInterface::class)) { if ($this->isInstanceOf(FilterSectionInterface::class)) {
$queryBuilder->andWhere('entity.section = :section'); $queryBuilder->andWhere('entity.section = :section');
$queryBuilder->setParameter('section', $this->sectionResolver->getCurrent());
$queryBuilder->setParameter('section', $this->get('section_resolver')->getCurrent());
} }


dump($queryBuilder);
return $queryBuilder; return $queryBuilder;
} }



+ 64
- 0
Controller/User/UserAdminController.php Bestand weergeven

<?php

namespace Lc\CaracoleBundle\Controller\User;

use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\EmailField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Lc\CaracoleBundle\Resolver\MerchantResolver;
use Lc\CaracoleBundle\Resolver\SectionResolver;
use Lc\SovBundle\Controller\AbstractAdminController;
use Lc\SovBundle\Definition\RolesDefinition;
use Lc\SovBundle\Definition\RolesDefinitionInterface;
use Lc\SovBundle\Doctrine\EntityManager;
use Lc\SovBundle\Model\User\UserInterface;
use Lc\SovBundle\Translation\TranslatorAdmin;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Lc\SovBundle\Controller\User\UserAdminController as SovUserAdminController;

abstract class UserAdminController extends SovUserAdminController
{
public static function getSubscribedServices()
{
return array_merge(parent::getSubscribedServices(), [
'merchant_resolver' => MerchantResolver::class,
'section_resolver' => SectionResolver::class,

]);
}
public function __construct(
SessionInterface $session,
RequestStack $request,
EntityManager $em,
TranslatorAdmin $translatorAdmin,
RolesDefinitionInterface $rolesDefinition,
MerchantResolver $merchantResolver
) {
parent::__construct($session, $request, $em, $translatorAdmin, $rolesDefinition);
}

public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$this->updateUserMerchantRoles($entityManager, $entityInstance);
parent::updateEntity($entityManager,$entityInstance);
}

/* public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$this->updateUserMerchantRoles($entityManager,$entityInstance);
parent::updateEntity($entityManager,$entityInstance);
}*/

protected function updateUserMerchantRoles($entityManager, UserInterface $user){
$userMerchant = $this->get('merchant_resolver')->getUserMerchant($user);

if($userMerchant !== null){
$userMerchant->setRoles($user->getRoles());
//$entityManager->update($userMerchant);
}
}

}

+ 25
- 0
DependencyInjection/Configuration.php Bestand weergeven

<?php

namespace Lc\CaracoleBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
* 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/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('lc_carac');
$rootNode = $treeBuilder->getRootNode();

return $treeBuilder;
}
}

+ 18
- 9
DependencyInjection/LcCaracoleExtension.php Bestand weergeven

use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface; use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;


class LcCaracoleExtension extends Extension implements PrependExtensionInterface
class LcCaracoleExtension extends Extension implements PrependExtensionInterface
{ {
public function load(array $configs, ContainerBuilder $container)
{


}
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);


public function prepend(ContainerBuilder $container)
{
/*$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config/easy_admin'));
$loader->load('base.yaml');
$loader->load('entities/merchant.yaml');*/
foreach ($config as $parameter => $value) {
$container->setParameter(sprintf('lc_carac.%s', $parameter), $value);
} }

$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yaml');
}

public function prepend(ContainerBuilder $container)
{
/*$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config/easy_admin'));
$loader->load('base.yaml');
$loader->load('entities/merchant.yaml');*/
}
} }

EventSubscriber/CreateEntityEventSubscriber.php → EventSubscriber/MerchantSectionPropertyEventSubscriber.php Bestand weergeven

use Lc\SovBundle\Event\EntityManager\EntityManagerEvent; use Lc\SovBundle\Event\EntityManager\EntityManagerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface;


class CreateEntityEventSubscriber implements EventSubscriberInterface
class MerchantSectionPropertyEventSubscriber implements EventSubscriberInterface
{ {
protected $em; protected $em;
protected $merchantResolver; protected $merchantResolver;
public static function getSubscribedEvents() public static function getSubscribedEvents()
{ {
return [ return [
EntityManagerEvent::CREATE_EVENT => ['createEntity'],
EntityManagerEvent::PRE_CREATE_EVENT => ['setMerchantAndSectionProperties'],
]; ];
} }


public function createEntity(EntityManagerEvent $event)
public function setMerchantAndSectionProperties(EntityManagerEvent $event)
{ {
$entity = $event->getEntity(); $entity = $event->getEntity();
$entityRepository = $this->em->getRepository(get_class($entity)); $entityRepository = $this->em->getRepository(get_class($entity));

+ 59
- 0
EventSubscriber/User/InitUserMerchantEventSubscriber.php Bestand weergeven

<?php

namespace Lc\CaracoleBundle\EventSubscriber\User;

use Doctrine\ORM\EntityManagerInterface;

use Lc\CaracoleBundle\Factory\User\UserMerchantFactory;
use Lc\SovBundle\Doctrine\EntityInterface;
use Lc\SovBundle\Doctrine\Extension\SortableInterface;
use Lc\SovBundle\Doctrine\Extension\StatusInterface;
use Lc\SovBundle\Doctrine\Extension\TreeInterface;
use Lc\SovBundle\Event\EntityManager\EntityManagerEvent;
use Lc\SovBundle\Model\User\UserInterface;
use Lc\SovBundle\Repository\AbstractRepositoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class InitUserMerchantEventSubscriber implements EventSubscriberInterface
{
protected $em;
protected $userMerchantFactory;

public function __construct(EntityManagerInterface $entityManager, UserMerchantFactory $userMerchantFactory)
{
$this->em = $entityManager;
$this->userMerchantFactory = $userMerchantFactory;
}

public static function getSubscribedEvents()
{
return [
EntityManagerEvent::PRE_CREATE_EVENT => ['createUserMerchant'],
];
}

public function createUserMerchant(EntityManagerEvent $event)
{
$user = $event->getEntity();
$entityRepository = $this->em->getRepository(get_class($user));
if ($user instanceof UserInterface) {
$existingUser = $entityRepository->findOneByEmail($user->getEmail());

//Le user n'existe pas, on le créer et on lui créer un user_merchant
if ($existingUser == null) {
$userMerchant = $this->userMerchantFactory->create(
[
'active' => true,
'roles' => $user->getRoles(),
'user' => $user
]
);
$this->em->create($userMerchant);
}
}
}


}

+ 95
- 0
EventSubscriber/User/UserRolesEventSubscriber.php Bestand weergeven

<?php

namespace Lc\CaracoleBundle\EventSubscriber\User;

use Doctrine\ORM\EntityManagerInterface;
use Lc\CaracoleBundle\Doctrine\Extension\FilterMerchantInterface;
use Lc\CaracoleBundle\Doctrine\Extension\FilterMultipleMerchantsInterface;
use Lc\CaracoleBundle\Doctrine\Extension\FilterSectionInterface;
use Lc\CaracoleBundle\Model\User\UserMerchantInterface;
use Lc\CaracoleBundle\Resolver\MerchantResolver;
use Lc\CaracoleBundle\Resolver\SectionResolver;
use Lc\SovBundle\Event\EntityManager\EntityManagerEvent;
use Lc\SovBundle\Model\User\UserInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Guard\Token\PostAuthenticationGuardToken;

class UserRolesEventSubscriber implements EventSubscriberInterface
{
protected $em;
protected $tokenStorage;
protected $security;
protected $merchantResolver;
protected $sectionResolver;

public function __construct(
TokenStorageInterface $tokenStorage,
EntityManagerInterface $entityManager,
Security $security,
MerchantResolver $merchantResolver,
SectionResolver $sectionResolver
) {
$this->em = $entityManager;
$this->tokenStorage = $tokenStorage;
$this->security = $tokenStorage;
$this->merchantResolver = $merchantResolver;
$this->sectionResolver = $sectionResolver;
}

public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['setUserRoles'],
];
}

public function setUserRoles(RequestEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}

if ($this->tokenStorage && $this->tokenStorage->getToken()) {
$token = $this->tokenStorage->getToken();
$sessionUser = $token->getUser();
if($sessionUser instanceof UserInterface) {
$roles = $this->merchantResolver->getUserMerchant($sessionUser)->getRoles();

if($roles != $sessionUser->getRoles()) {
$sessionUser->setRoles($roles);
$this->em->update($sessionUser);
$this->em->flush();

$token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken(
$sessionUser,
null,
'main',
$sessionUser->getRoles()
);
$this->security->setToken($token);
}

}
/*
// This check can be just `is_object` like in symfony core
// we're explicit about the class used
if ($sessionUser instanceof UserInterface) {
/* if ($this->merchantResolver->getCurrent()->getId() == 2) {
$sessionUser->setRoles(array('ROLE_ADMIN', 'ROLE_BEST_USER'));
}
$this->tokenStorage->setToken(
new PostAuthenticationGuardToken($sessionUser, 'main', $sessionUser->getRoles())
);
}*/
}
}


}

+ 22
- 0
Factory/User/UserMerchantFactory.php Bestand weergeven



namespace Lc\CaracoleBundle\Factory\User; namespace Lc\CaracoleBundle\Factory\User;


use Doctrine\ORM\EntityManagerInterface;
use Lc\CaracoleBundle\Model\User\UserMerchantInterface; use Lc\CaracoleBundle\Model\User\UserMerchantInterface;
use Lc\CaracoleBundle\Resolver\MerchantResolver;
use Lc\SovBundle\Factory\AbstractFactory; use Lc\SovBundle\Factory\AbstractFactory;


class UserMerchantFactory extends AbstractFactory class UserMerchantFactory extends AbstractFactory
{ {
protected $merchantResolver;

public function __construct(EntityManagerInterface $em, MerchantResolver $merchantResolver)
{
parent::__construct($em);
$this->merchantResolver = $merchantResolver;
}

public function getEntityClass() public function getEntityClass()
{ {
return UserMerchantInterface::class; return UserMerchantInterface::class;
} }

public function create($params = array())
{
if(!isset($params['merchant'])){
$params['merchant'] = $this->merchantResolver->getCurrent();
}

if(!isset($params['creditActive'])){
$params['creditActive'] =false;
}
return parent::create($params); // TODO: Change the autogenerated stub
}
} }

+ 29
- 1
Model/User/UserMerchantModel.php Bestand weergeven

use Lc\CaracoleBundle\Doctrine\Extension\FilterMerchantInterface; use Lc\CaracoleBundle\Doctrine\Extension\FilterMerchantInterface;
use Lc\CaracoleBundle\Model\Merchant\MerchantInterface; use Lc\CaracoleBundle\Model\Merchant\MerchantInterface;
use Lc\CaracoleBundle\Model\Section\SectionInterface; use Lc\CaracoleBundle\Model\Section\SectionInterface;
use Lc\SovBundle\Doctrine\EntityInterface;


/** /**
* @ORM\MappedSuperclass() * @ORM\MappedSuperclass()
* *
*/ */
abstract class UserMerchantModel implements FilterMerchantInterface
abstract class UserMerchantModel implements FilterMerchantInterface, EntityInterface
{ {
/** /**
* @ORM\ManyToOne(targetEntity="Lc\SovBundle\Model\User\UserInterface", inversedBy="userMerchants") * @ORM\ManyToOne(targetEntity="Lc\SovBundle\Model\User\UserInterface", inversedBy="userMerchants")
*/ */
protected $active; protected $active;


/**
* @ORM\Column(type="json")
*/
protected $roles = [];

public function __construct() public function __construct()
{ {
$this->creditHistories = new ArrayCollection(); $this->creditHistories = new ArrayCollection();


return $this; return $this;
} }


public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';

return array_unique($roles);
}

public function setRoles(array $roles): self
{
$this->roles = $roles;

return $this;
}

public function hasRole($role)
{
return in_array(strtoupper($role), $this->getRoles(), true);
}
} }

+ 16
- 0
Resources/config/services.yaml Bestand weergeven

services:
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

Lc\CaracoleBundle\:
resource: '../../'
exclude:
- '../../DependencyInjection/'
- '../../Entity/'
- '../../Kernel.php'
- '../../Tests/'

Lc\CaracoleBundle\Controller\:
resource: '../../Controller/'
tags: [ 'controller.service_arguments' ]

Laden…
Annuleren
Opslaan