Commit 41937918 by Julien Jorry

Choix du rôle : modifications de la logique + correction pour fonctionner sur…

Choix du rôle : modifications de la logique + correction pour fonctionner sur sonata admin + fix carte presta avec image + fix icon sonata
parent 59f37ed0
......@@ -101,7 +101,9 @@ security:
guard:
authenticators:
- App\Security\EmailTokenAuthenticator
- App\Security\LoginAuthenticator
provider: fos_userbundle
entry_point: App\Security\LoginAuthenticator
remember_me:
secret: "%kernel.secret%"
lifetime: 31536000
......
......@@ -79,12 +79,12 @@ services:
redirect.after.login:
class: App\Listener\AfterLoginRedirection
autowire: false
arguments: ['@router']
arguments: ['@router', '@doctrine.orm.entity_manager', '@security.token_storage']
app.twig.main.extension:
class: App\Twig\AppExtension
autowire: false
arguments: ["@service_container", "@security.helper", "@doctrine.orm.entity_manager", "@knp_paginator", "@session", "@app.rolecheck"]
arguments: ["@service_container", "@security.helper", "@doctrine.orm.entity_manager", "@knp_paginator", "@session"]
app.twig.mlc.globals.extension:
class: App\Twig\MlcGlobalsExtension
......@@ -157,7 +157,6 @@ services:
- [ROLE_SUPER_ADMIN]
calls:
- [setManager, ['@doctrine.orm.entity_manager']]
- [setRolecheck, ['@app.rolecheck']]
admin.block.dashboard:
class: App\Block\DashboardKohinosBlock
......@@ -197,7 +196,6 @@ services:
public: true
calls:
- [ setSecurity, ['@security.helper']]
- [ setRoleCheck, ['@app.rolecheck']]
admin.adherent.cotisations:
class: App\Admin\CotisationAdherentAdmin
......@@ -210,7 +208,6 @@ services:
public: true
calls:
- [ setSecurity, ['@security.helper']]
- [ setRoleCheck, ['@app.rolecheck']]
admin.prestataire.gerer:
class: App\Admin\PrestataireAdmin
......@@ -238,7 +235,6 @@ services:
public: true
calls:
- [ setSecurity, ['@security.helper']]
- [ setRoleCheck, ['@app.rolecheck']]
admin.groupe.gerer:
class: App\Admin\GroupeAdmin
......@@ -360,9 +356,6 @@ services:
- [ setSubClasses, [{transaction: 'App\Entity\Transaction', transfert: 'App\Entity\Transfert', cotisation: 'App\Entity\Cotisation'}]]
- [ setSecurity, ['@security.helper']]
app.rolecheck:
class: App\Tools\RoleCheck
admin.transfert.gerer:
class: App\Admin\TransfertAdmin
arguments: [~, App\Entity\Transfert, ~]
......@@ -376,7 +369,6 @@ services:
calls:
- [ setSecurity, ['@security.helper']]
- [ setSession, ['@session']]
- [ setRoleCheck, ['@app.rolecheck']]
admin.transaction.gerer:
class: App\Admin\TransactionAdmin
......
......@@ -71,8 +71,6 @@ App\Entity\Comptoir:
comptoir{1..10}:
name (unique): '<text(10)>'
enabled: true
tel: '<phoneNumber()>'
email: '<email()>'
compte: '<randomFloat(2, 1000, 2000)>'
groupe: '@groupe<numberBetween(1,10)>'
geoloc (unique): '@geoloc<numberBetween(5,15)>'
......@@ -238,13 +236,15 @@ App\Entity\User:
email: 'julien.jorry@gmail.com'
plainPassword: 'test'
enabled: true
groups: ['@usergroup_superadmin', '@usergroup_prestataire']
possiblegroups: ['@usergroup_superadmin', '@usergroup_prestataire']
groups: ['@usergroup_superadmin']
roles: ['ROLE_SUPER_ADMIN', 'ROLE_PRESTATAIRE']
usercontact:
username: 'user_contact'
email: 'contact@kohinos.test'
plainPassword: 'test'
enabled: true
possiblegroups: ['@usergroup_contact']
groups: ['@usergroup_contact']
roles: ['ROLE_CONTACT']
groupesgeres: ['@groupe1']
......@@ -253,6 +253,7 @@ App\Entity\User:
email: 'comptoir@kohinos.test'
plainPassword: 'test'
enabled: true
possiblegroups: ['@usergroup_comptoir']
groups: ['@usergroup_comptoir']
roles: ['ROLE_COMPTOIR']
comptoirsgeres: ['@comptoir1']
......@@ -261,6 +262,7 @@ App\Entity\User:
email: 'groupe@kohinos.test'
plainPassword: 'test'
enabled: true
possiblegroups: ['@usergroup_gestiongroupe']
groups: ['@usergroup_gestiongroupe']
roles: ['ROLE_GESTION_GROUPE']
groupesgeres: ['@groupe1']
......@@ -269,6 +271,7 @@ App\Entity\User:
email: 'tresorier@kohinos.test'
plainPassword: 'test'
enabled: true
possiblegroups: ['@usergroup_tresorier']
groups: ['@usergroup_tresorier']
roles: ['ROLE_TRESORIER']
userredacteur:
......@@ -276,6 +279,7 @@ App\Entity\User:
email: 'redacteur@kohinos.test'
plainPassword: 'test'
enabled: true
possiblegroups: ['@usergroup_redacteur']
groups: ['@usergroup_redacteur']
roles: ['ROLE_REDACTEUR']
usercontroleur:
......@@ -283,6 +287,7 @@ App\Entity\User:
email: 'controleur@kohinos.test'
plainPassword: 'test'
enabled: true
possiblegroups: ['@usergroup_controleur']
groups: ['@usergroup_controleur']
roles: ['ROLE_CONTROLEUR']
useradminsiege:
......@@ -290,6 +295,7 @@ App\Entity\User:
email: 'siege@kohinos.test'
plainPassword: 'test'
enabled: true
possiblegroups: ['@usergroup_adminsiege']
groups: ['@usergroup_adminsiege']
roles: ['ROLE_ADMIN_SIEGE']
userprestataire:
......@@ -297,6 +303,7 @@ App\Entity\User:
email: 'prestataire@kohinos.test'
plainPassword: 'test'
enabled: true
possiblegroups: ['@usergroup_prestataire']
groups: ['@usergroup_prestataire']
roles: ['ROLE_PRESTATAIRE']
prestataires: ['@prestataire1']
......@@ -308,6 +315,7 @@ App\Entity\User:
email: 'adherent@kohinos.test'
plainPassword: 'test'
enabled: true
possiblegroups: ['@usergroup_adherent']
groups: ['@usergroup_adherent']
roles: ['ROLE_ADHERENT']
adherent: '@adherent1'
......@@ -316,6 +324,7 @@ App\Entity\User:
email: <email()>
plainPassword: 'test'
enabled: true
possiblegroups: ['@usergroup_adherent']
groups: ['@usergroup_adherent']
roles: ['ROLE_ADHERENT']
adherent: '@adherent<current()>'
......@@ -324,6 +333,7 @@ App\Entity\User:
email: <email()>
plainPassword: 'test'
enabled: true
possiblegroups: ['@usergroup_prestataire']
groups: ['@usergroup_prestataire']
roles: ['ROLE_PRESTATAIRE']
prestataires: ['@prestataire<current()>']
......
......@@ -125,7 +125,8 @@ class AdherentAdmin extends AbstractAdmin
$user = $this->userManager->createUser();
$groupe = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Adherent');
$user->setEnabled(true);
$user->addGroup($groupe);
$user->addPossiblegroup($groupe);
$user->setGroups([$groupe]);
$user->addRole('ROLE_ADHERENT');
$adherent->setEcompte('0');
$user->setAdherent($adherent);
......
......@@ -8,7 +8,6 @@ use App\Entity\Prestataire;
use App\Entity\Siege;
use App\Entity\User;
use App\Enum\MoyenEnum;
use App\Tools\RoleCheck;
use Doctrine\ORM\EntityManagerInterface;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
......@@ -37,7 +36,6 @@ class CotisationAdmin extends AbstractAdmin
protected $baseRouteName = 'cotisation';
protected $baseRoutePattern = 'cotisation';
protected $security;
protected $rolecheck;
protected $translator;
protected $datagridValues = [
......@@ -50,11 +48,6 @@ class CotisationAdmin extends AbstractAdmin
$this->security = $security;
}
public function setRoleCheck(RoleCheck $rolecheck)
{
$this->rolecheck = $rolecheck;
}
/**
* {@inheritdoc}
*/
......@@ -91,7 +84,7 @@ class CotisationAdmin extends AbstractAdmin
'em' => $em
))
->add('role', HiddenType::class, array(
'data' => $this->rolecheck->getCurrentRole()->__toString()
'data' => $this->security->getUser()->getGroups()[0]->__toString()
))
->add('destinataire', HiddenType::class, array(
'data' => $em->getRepository(Prestataire::class)->findOneBy(array('mlc' => true))->getId(),
......@@ -170,7 +163,8 @@ class CotisationAdmin extends AbstractAdmin
'label' => 'Expire le'
))
->add('cotisationInfos.recu', null, array(
'label' => 'Reçu ?'
'label' => 'Reçu ?',
'editable' => true
))
->add('operateurAndRole', null, array(
'label' => 'Opérateur'
......
......@@ -334,8 +334,8 @@ class PrestataireAdmin extends AbstractAdmin
$user->setAdherent($adh);
$groupeAdh = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Adherent');
$groupePresta = $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository(Usergroup::class)->findOneByName('Prestataire');
$user->addGroup($groupeAdh);
$user->addGroup($groupePresta);
$user->addPossiblegroup($groupeAdh);
$user->addPossiblegroup($groupePresta);
$this->userManager->updateUser($user);
// $user->addRole('ROLE_PRESTATAIRE');
// $user->addRole('ROLE_ADHERENT');
......
......@@ -6,7 +6,6 @@ use App\Admin\FluxAdmin;
use App\Entity\User;
use App\Entity\Flux;
use App\Entity\Prestataire;
use App\Tools\RoleCheck;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
......@@ -29,7 +28,6 @@ class TransfertAdmin extends FluxAdmin
{
protected $security;
protected $session;
protected $rolecheck;
protected $datagridValues = [
'_sort_order' => 'DESC',
'_sort_by' => 'createdAt',
......@@ -45,11 +43,6 @@ class TransfertAdmin extends FluxAdmin
$this->session = $session;
}
public function setRoleCheck(RoleCheck $rolecheck)
{
$this->rolecheck = $rolecheck;
}
protected function configureRoutes(RouteCollection $collection)
{
$collection->clearExcept(array('list', 'export'));
......@@ -67,7 +60,7 @@ class TransfertAdmin extends FluxAdmin
$em = $this->getConfigurationPool()->getContainer()->get('doctrine')->getManager();
$fluxtable = $em->getMetadataFactory()->getMetadataFor(Flux::class)->getTableName();
if ($this->rolecheck->isGranted('ROLE_GESTION_GROUPE') || $this->rolecheck->isGranted('ROLE_CONTACT') || $user->isGranted('ROLE_TRESORIER')) {
if ($this->security->getUser()->isGranted('ROLE_GESTION_GROUPE') || $this->security->getUser()->isGranted('ROLE_CONTACT') || $this->security->getUser()->isGranted('ROLE_TRESORIER')) {
if (empty($this->getRequest()->getSession()->get('_groupegere'))) {
$query->andWhere('false = true');
} else {
......@@ -82,7 +75,7 @@ class TransfertAdmin extends FluxAdmin
->setParameter('ids', $ids)
;
}
} elseif ($this->rolecheck->isGranted('ROLE_COMPTOIR')) {
} elseif ($this->security->getUser()->isGranted('ROLE_COMPTOIR')) {
if (empty($this->getRequest()->getSession()->get('_comptoirgere'))) {
$query->andWhere('false = true');
} else {
......
......@@ -97,7 +97,7 @@ class UserAdmin extends BaseUserAdmin
->add('email')
->end()
->with('Groups')
->add('groups')
->add('possiblegroups')
->end()
->with('Profile')
// ->add('dateOfBirth')
......@@ -218,11 +218,18 @@ class UserAdmin extends BaseUserAdmin
}
$formMapper
->with('Groups')
->add('groups', ModelType::class, [
->add('possiblegroups', ModelType::class, [
'label' => 'Groupes de rôles possibles',
'required' => false,
'expanded' => true,
'multiple' => true,
])
// @TODO : Si on veut voir le groupe choisit par l'utilisateur
// ->add('groups', null, [
// 'label' => 'Rôle actuel',
// 'required' => false,
// 'disabled' => true
// ])
->add('groupesgeres', null, [
'required' => false,
'label' => 'Groupe local géré (obligatoire)',
......
......@@ -8,7 +8,6 @@ use App\Entity\CotisationPrestataire;
use App\Enum\MoyenEnum;
use App\Form\Type\CotiserFormType;
use App\Form\Type\UserInfosFormType;
use App\Tools\RoleCheck;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
......@@ -16,18 +15,19 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Security\Core\Security;
class UserController extends AbstractController
{
private $em;
private $translator;
private $rolecheck;
private $security;
public function __construct(EntityManagerInterface $em, TranslatorInterface $translator, RoleCheck $rolecheck)
public function __construct(EntityManagerInterface $em, TranslatorInterface $translator, Security $security)
{
$this->em = $em;
$this->translator = $translator;
$this->rolecheck = $rolecheck;
$this->security = $security;
}
/**
......@@ -37,9 +37,9 @@ class UserController extends AbstractController
public function cotiserAction(Request $request)
{
$options = [];
if ($this->rolecheck->isGranted('ROLE_ADHERENT')) {
if ($this->security->getUser()->isGranted('ROLE_ADHERENT')) {
$options['data_class'] = CotisationAdherent::class;
} elseif ($this->rolecheck->isGranted('ROLE_PRESTATAIRE')) {
} elseif ($this->security->getUser()->isGranted('ROLE_PRESTATAIRE')) {
$options['data_class'] = CotisationPrestataire::class;
}
......@@ -55,6 +55,7 @@ class UserController extends AbstractController
}
if ($form->isValid()) {
if ($form->get('payMLC')->isClicked()) {
$cotisation->setRecu(true);
$this->em->persist($cotisation);
$this->em->flush();
$this->addFlash(
......
......@@ -71,7 +71,6 @@ class CotisationInfos
*/
private $recu;
/**
* Constructeur
*/
......
......@@ -13,6 +13,7 @@ use Symfony\Component\Validator\Constraints as Assert;
use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\GroupInterface;
/**
* ApiResource(
......@@ -124,7 +125,7 @@ class User extends BaseUser
protected $prestataires;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Groupe", mappedBy="gestionnaires", cascade={"persist"}, fetch="LAZY")
* @ORM\ManyToMany(targetEntity="App\Entity\Groupe", mappedBy="gestionnaires", cascade={"persist"}, fetch="EAGER")
* @ORM\JoinTable(name="user_groupe",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="groupe_id", referencedColumnName="id")}
......@@ -133,7 +134,7 @@ class User extends BaseUser
private $groupesgeres;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Comptoir", mappedBy="gestionnaires", cascade={"persist"}, fetch="LAZY")
* @ORM\ManyToMany(targetEntity="App\Entity\Comptoir", mappedBy="gestionnaires", cascade={"persist"}, fetch="EAGER")
* @ORM\JoinTable(name="user_comptoir",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="comptoir_id", referencedColumnName="id")}
......@@ -160,7 +161,7 @@ class User extends BaseUser
private $pages;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Usergroup")
* @ORM\ManyToMany(targetEntity="App\Entity\Usergroup", cascade={"persist"}, fetch="EXTRA_LAZY")
* @ORM\JoinTable(name="user_usergroup",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
......@@ -168,6 +169,16 @@ class User extends BaseUser
* @Groups({"user"})
*/
protected $groups;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Usergroup", fetch="EAGER")
* @ORM\JoinTable(name="user_possiblegroup",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
* @Groups({"user"})
*/
protected $possiblegroups;
/**
* Alerte email à chaque transaction concernant l'utilisateur
......@@ -192,6 +203,7 @@ class User extends BaseUser
$this->faqs = new ArrayCollection();
$this->news = new ArrayCollection();
$this->pages = new ArrayCollection();
$this->possiblegroups = new ArrayCollection();
$this->alertemailflux = true;
$this->createApiKey();
$this->createEmailToken();
......@@ -596,6 +608,52 @@ class User extends BaseUser
}
/**
* Get possiblegroups
* @return
*/
public function getPossiblegroups()
{
return $this->possiblegroups;
}
/**
* Set possiblegroups
* @return $this
*/
public function setPossiblegroups($possiblegroups)
{
$this->possiblegroups = $possiblegroups;
return $this;
}
/**
* addPossibleGroup
* @param GroupInterface $possiblegroups [description]
*/
public function addPossibleGroup(GroupInterface $possiblegroups)
{
if (!$this->getPossiblegroups()->contains($possiblegroups)) {
$this->getPossiblegroups()->add($possiblegroups);
}
return $this;
}
/**
* removePossibleGroup
* @param GroupInterface $possiblegroups [description]
* @return [type] [description]
*/
public function removePossibleGroup(GroupInterface $possiblegroups)
{
if ($this->getPossiblegroups()->contains($possiblegroups)) {
$this->getPossiblegroups()->removeElement($possiblegroups);
}
return $this;
}
/**
* Get alertemailflux
* @return
*/
......@@ -613,4 +671,18 @@ class User extends BaseUser
$this->alertemailflux = $alertemailflux;
return $this;
}
/**
* Quand on appelle setGroups sur le user, on réinitialise ses groupes avant ! Pour pouvoir se connecter sur un seul groupe, les groupes possibles sont dans possiblegroups !
* {@inheritdoc}
*/
public function setGroups($groups)
{
$this->groups = new ArrayCollection();
foreach ($groups as $group) {
$this->addGroup($group);
}
return $this;
}
}
<?php
namespace App\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
class SwitchUserSubscriber implements EventSubscriberInterface
{
private $router;
private $em;
/**
* SwitchUserSubscriber constructor.
*
* @param RouterInterface $router
*/
public function __construct(RouterInterface $router)
public function __construct(RouterInterface $router, EntityManagerInterface $em)
{
$this->router = $router;
$this->em = $em;
}
public function onSwitchUser(SwitchUserEvent $event)
......@@ -30,31 +35,75 @@ class SwitchUserSubscriber implements EventSubscriberInterface
$request->getSession()->remove('_prestagere');
$request->getSession()->remove('_comptoirgere');
$request->getSession()->remove('_groupegere');
if ($request->hasSession() && $request->getSession()->has('_groupId') &&
!$user->getGroups()->contains($request->getSession()->get('_groupId'))) {
$request->getSession()->remove('_groupId');
}
if (!$request->getSession()->has('_groupId')) {
if (count($user->getGroups()) > 1) {
$request->getSession()->set('_choixGroup', 'true');
if ($user->getPossiblegroups()->count() == 1) {
if (count($user->getGroups()) != 1) {
$groupe = $user->getPossiblegroups()->first();
if (in_array('ROLE_PRESTATAIRE', $groupe->getRoles()) && count($user->getPrestataires()) >= 1) {
$request->getSession()->set('_prestagere', $user->getPrestataires()[0]);
} elseif (in_array('ROLE_COMPTOIR', $groupe->getRoles()) && count($user->getComptoirsGeres()) >= 1) {
$request->getSession()->set('_comptoirgere', $user->getComptoirsGeres()[0]);
} elseif ((in_array('ROLE_TRESORIER', $groupe->getRoles()) || in_array('ROLE_CONTACT', $groupe->getRoles()) || in_array('ROLE_GESTION_GROUPE', $groupe->getRoles())) && count($user->getGroupesGeres()) >= 1) {
$request->getSession()->set('_groupegere', $user->getGroupesGeres()[0]);
}
$user->setGroups([$groupe]);
$this->em->persist($user);
$this->em->flush();
$this->updateToken($event, $user, $token);
} else {
$request->getSession()->set('_groupId', $user->getGroups()[0]);
foreach ($user->getGroups() as $groupe) {
$groupe = $user->getGroups()->first();
if (in_array('ROLE_PRESTATAIRE', $groupe->getRoles()) && count($user->getPrestataires()) >= 1) {
$request->getSession()->set('_prestagere', $user->getPrestataires()[0]);
} elseif (in_array('ROLE_COMPTOIR', $groupe->getRoles()) && count($user->getComptoirsGeres()) >= 1) {
$request->getSession()->set('_comptoirgere', $user->getComptoirsGeres()[0]);
} elseif ((in_array('ROLE_TRESORIER', $groupe->getRoles()) || in_array('ROLE_CONTACT', $groupe->getRoles()) || in_array('ROLE_GESTION_GROUPE', $groupe->getRoles())) && count($user->getGroupesGeres()) >= 1) {
$request->getSession()->set('_groupegere', $user->getGroupesGeres()[0]);
}
}
} elseif ($user->getPossiblegroups()->count() > 1) {
if ($user->getGroups()->count() != 1) {
$hasSuperAdminRole = false;
foreach ($user->getPossiblegroups() as $groupe) {
if (in_array('ROLE_SUPER_ADMIN', $groupe->getRoles())) {
$request->getSession()->remove('_choixGroup');
}
if (in_array('ROLE_PRESTATAIRE', $groupe->getRoles()) && count($user->getPrestataires()) >= 1) {
$request->getSession()->set('_prestagere', $user->getPrestataires()[0]);
} elseif (in_array('ROLE_COMPTOIR', $groupe->getRoles()) && count($user->getComptoirsGeres()) >= 1) {
$request->getSession()->set('_comptoirgere', $user->getComptoirsGeres()[0]);
} elseif ((in_array('ROLE_TRESORIER', $groupe->getRoles()) || in_array('ROLE_CONTACT', $groupe->getRoles()) || in_array('ROLE_GESTION_GROUPE', $groupe->getRoles())) && count($user->getGroupesGeres()) >= 1) {
$request->getSession()->set('_groupegere', $user->getGroupesGeres()[0]);
$hasSuperAdminRole = true;
$user->setGroups([]);
$this->em->persist($user);
$this->em->flush();
$user->setGroups([$groupe]);
$this->em->persist($user);
$this->em->flush();
$this->updateToken($event, $user, $token);
}
}
if (!$hasSuperAdminRole) {
$user->setGroups([]);
$user->setRoles(['ROLE_USER']);
$this->em->persist($user);
$this->em->flush();
$this->updateToken($event, $user, $token);
}
} else {
$groupe = $user->getGroups()->first();
if (in_array('ROLE_PRESTATAIRE', $groupe->getRoles()) && count($user->getPrestataires()) >= 1) {
$request->getSession()->set('_prestagere', $user->getPrestataires()[0]);
} elseif (in_array('ROLE_COMPTOIR', $groupe->getRoles()) && count($user->getComptoirsGeres()) >= 1) {
$request->getSession()->set('_comptoirgere', $user->getComptoirsGeres()[0]);
} elseif ((in_array('ROLE_TRESORIER', $groupe->getRoles()) || in_array('ROLE_CONTACT', $groupe->getRoles()) || in_array('ROLE_GESTION_GROUPE', $groupe->getRoles())) && count($user->getGroupesGeres()) >= 1) {
$request->getSession()->set('_groupegere', $user->getGroupesGeres()[0]);
}
}
}
}
private function updateToken($event, $user, $token)
{
$roles = $user->getRoles();
$roles[] = new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $token, false);
$token = new SwitchUserToken($user, $user->getPassword(), 'main', $roles, $event->getToken()->getOriginalToken());
$event->setToken($token);
}
public static function getSubscribedEvents()
{
return [
......
......@@ -9,7 +9,6 @@ use App\Entity\Prestataire;
use App\Entity\User;
use App\Entity\GlobalParameter;
use App\Enum\MoyenEnum;
use App\Tools\RoleCheck;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
......@@ -30,14 +29,12 @@ class CotiserFormType extends AbstractType
{
protected $em;
protected $security;
protected $rolecheck;
protected $session;
public function __construct(EntityManagerInterface $em, Security $security, RoleCheck $rolecheck, SessionInterface $session)
public function __construct(EntityManagerInterface $em, Security $security, SessionInterface $session)
{
$this->em = $em;
$this->security = $security;
$this->rolecheck = $rolecheck;
$this->session = $session;
}
......@@ -49,10 +46,10 @@ class CotiserFormType extends AbstractType
$now = new \DateTime();
$montant = 0;
$canPayWithMlc = false;
if ($this->rolecheck->isGranted('ROLE_ADHERENT')) {
if ($this->security->getUser()->isGranted('ROLE_ADHERENT')) {
$montant = floatval($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::COTISATION_ADHERENT));
$canPayWithMlc = ($this->security->getUser()->getAdherent()->getEcompte() >= $montant);
} elseif ($this->rolecheck->isGranted('ROLE_PRESTATAIRE')) {
} elseif ($this->security->getUser()->isGranted('ROLE_PRESTATAIRE')) {
$montant = floatval($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::COTISATION_PRESTATAIRE));
$canPayWithMlc = ($this->session->get('_prestagere')->getEcompte() >= $montant);
}
......@@ -65,7 +62,7 @@ class CotiserFormType extends AbstractType
'data' => $this->security->getUser()->getId()
))
->add('role', HiddenType::class, array(
'data' => $this->rolecheck->getCurrentRole()->__toString()
'data' => $this->security->getUser()->getGroups()[0]->__toString()
))
->add('destinataire', HiddenType::class, array(
'data' => $this->em->getRepository(Prestataire::class)->findOneBy(array('mlc' => true))->getId(),
......@@ -99,7 +96,7 @@ class CotiserFormType extends AbstractType
}
$builder->add('payCB', SubmitType::class, ['label' => "Payer en CB"]);
if ($this->rolecheck->isGranted('ROLE_ADHERENT')) {
if ($this->security->getUser()->isGranted('ROLE_ADHERENT')) {
$builder
->add('expediteur', HiddenType::class, array(
'entity_class' => Adherent::class,
......@@ -108,7 +105,7 @@ class CotiserFormType extends AbstractType
'data' => $this->security->getUser()->getAdherent()->getId()
))
;
} elseif ($this->rolecheck->isGranted('ROLE_PRESTATAIRE')) {
} elseif ($this->security->getUser()->isGranted('ROLE_PRESTATAIRE')) {
$builder
->add('expediteur', HiddenType::class, array(
'entity_class' => Prestataire::class,
......
......@@ -4,7 +4,6 @@ namespace App\Form\Type;
use App\Entity\Flux;
use App\Entity\User;
use App\Tools\RoleCheck;
use App\Enum\MoyenEnum;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
......@@ -30,15 +29,13 @@ class FluxFormType extends AbstractType
protected $security;
protected $container;
protected $session;
protected $rolecheck;
public function __construct(EntityManagerInterface $em, Security $security, ContainerInterface $container, SessionInterface $session, RoleCheck $rolecheck)
public function __construct(EntityManagerInterface $em, Security $security, ContainerInterface $container, SessionInterface $session)
{
$this->em = $em;
$this->security = $security;
$this->container = $container;
$this->session = $session;
$this->rolecheck = $rolecheck;
}
public function buildForm(FormBuilderInterface $builder, array $options)
......@@ -61,7 +58,7 @@ class FluxFormType extends AbstractType
'em' => $this->em
))
->add('role', HiddenType::class, array(
'data' => $this->rolecheck->getCurrentRole()->__toString()
'data' => $this->security->getUser()->getGroups()[0]->__toString()
))
;
if (empty($flux->getExpediteur())) {
......
......@@ -2,12 +2,15 @@
namespace App\Listener;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
* Class AfterLoginRedirection
......@@ -17,15 +20,19 @@ use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerI
class AfterLoginRedirection implements AuthenticationSuccessHandlerInterface
{
private $router;
private $em;
private $tokenStorage;
/**
* AfterLoginRedirection constructor.
*
* @param RouterInterface $router
*/
public function __construct(RouterInterface $router)
public function __construct(RouterInterface $router, EntityManagerInterface $em, TokenStorageInterface $tokenStorage)
{
$this->router = $router;
$this->em = $em;
$this->tokenStorage = $tokenStorage;
}
/**
......@@ -38,6 +45,9 @@ class AfterLoginRedirection implements AuthenticationSuccessHandlerInterface
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$roles = $token->getRoles();
$user = $token->getUser();
$groups = $token->getUser()->getGroups();
$possibleGroups = $token->getUser()->getPossibleGroups();
$rolesTab = array_map(function ($role) {
return $role->getRole();
......@@ -46,38 +56,67 @@ class AfterLoginRedirection implements AuthenticationSuccessHandlerInterface
$request->getSession()->remove('_prestagere');
$request->getSession()->remove('_comptoirgere');
$request->getSession()->remove('_groupegere');
if ($request->getSession()->has('_groupId') && !$token->getUser()->getGroups()->contains($request->getSession()->get('_groupId'))) {
$request->getSession()->remove('_groupId');
}
if (!$request->getSession()->has('_groupId')) {
if (count($token->getUser()->getGroups()) > 1) {
$request->getSession()->set('_choixGroup', 'true');
if ($user->getPossiblegroups()->count() == 1) {
if ($user->getGroups()->count() != 1) {
$groupe = $user->getPossiblegroups()->first();
if (in_array('ROLE_PRESTATAIRE', $groupe->getRoles()) && count($user->getPrestataires()) >= 1) {
$request->getSession()->set('_prestagere', $user->getPrestataires()[0]);
} elseif (in_array('ROLE_COMPTOIR', $groupe->getRoles()) && count($user->getComptoirsGeres()) >= 1) {
$request->getSession()->set('_comptoirgere', $user->getComptoirsGeres()[0]);
} elseif ((in_array('ROLE_TRESORIER', $groupe->getRoles()) || in_array('ROLE_CONTACT', $groupe->getRoles()) || in_array('ROLE_GESTION_GROUPE', $groupe->getRoles())) && count($user->getGroupesGeres()) >= 1) {
$request->getSession()->set('_groupegere', $user->getGroupesGeres()[0]);
}
$user->setGroups([$groupe]);
$this->em->persist($user);
$this->em->flush();
$this->updateToken($user);
} else {
$request->getSession()->remove('_choixGroup');
$groupe = $token->getUser()->getGroups()[0];
foreach ($rolesTab as $role) {
if ($role == 'ROLE_PRESTATAIRE' && count($token->getUser()->getPrestataires()) >= 1) {
$request->getSession()->set('_prestagere', $token->getUser()->getPrestataires()[0]);
} elseif ($role == 'ROLE_COMPTOIR' && count($token->getUser()->getComptoirsGeres()) >= 1) {
$request->getSession()->set('_comptoirgere', $token->getUser()->getComptoirsGeres()[0]);
} elseif (($role == 'ROLE_TRESORIER' || $role == 'ROLE_CONTACT' || $role == 'ROLE_GESTION_GROUPE') && count($token->getUser()->getGroupesGeres()) >= 1) {
$request->getSession()->set('_groupegere', $token->getUser()->getGroupesGeres()[0]);
$groupe = $user->getGroups()->first();
if (in_array('ROLE_PRESTATAIRE', $groupe->getRoles()) && count($user->getPrestataires()) >= 1) {
$request->getSession()->set('_prestagere', $user->getPrestataires()[0]);
} elseif (in_array('ROLE_COMPTOIR', $groupe->getRoles()) && count($user->getComptoirsGeres()) >= 1) {
$request->getSession()->set('_comptoirgere', $user->getComptoirsGeres()[0]);
} elseif ((in_array('ROLE_TRESORIER', $groupe->getRoles()) || in_array('ROLE_CONTACT', $groupe->getRoles()) || in_array('ROLE_GESTION_GROUPE', $groupe->getRoles())) && count($user->getGroupesGeres()) >= 1) {
$request->getSession()->set('_groupegere', $user->getGroupesGeres()[0]);
}
}
} elseif (count($user->getPossiblegroups()) > 1) {
if ($user->getGroups()->count() != 1) {
$hasSuperAdminRole = false;
foreach ($user->getPossiblegroups() as $groupe) {
if (in_array('ROLE_SUPER_ADMIN', $groupe->getRoles())) {
$hasSuperAdminRole = true;
$user->setGroups([]);
$this->em->persist($user);
$this->em->flush();
$user->setGroups([$groupe]);
$this->em->persist($user);
$this->em->flush();
$this->updateToken($user);
}
}
if (!$hasSuperAdminRole) {
$user->setGroups([]);
$user->setRoles(['ROLE_USER']);
$this->em->persist($user);
$this->em->flush();
$this->updateToken($user);
}
} else {
$groupe = $user->getGroups()->first();
if (in_array('ROLE_PRESTATAIRE', $groupe->getRoles()) && count($user->getPrestataires()) >= 1) {
$request->getSession()->set('_prestagere', $user->getPrestataires()[0]);
} elseif (in_array('ROLE_COMPTOIR', $groupe->getRoles()) && count($user->getComptoirsGeres()) >= 1) {
$request->getSession()->set('_comptoirgere', $user->getComptoirsGeres()[0]);
} elseif ((in_array('ROLE_TRESORIER', $groupe->getRoles()) || in_array('ROLE_CONTACT', $groupe->getRoles()) || in_array('ROLE_GESTION_GROUPE', $groupe->getRoles())) && count($user->getGroupesGeres()) >= 1) {
$request->getSession()->set('_groupegere', $user->getGroupesGeres()[0]);
}
}
}
if (in_array('ROLE_SUPER_ADMIN', $rolesTab, true)) {
// c'est un administrateur
if ($this->getTargetUrlFromSession($request->getSession(), $token) != null) {
// on le redirige vers l'url demandée à l'origine si elle existe
$redirection = new RedirectResponse($this->getTargetUrlFromSession($request->getSession(), $token));
} else {
// sinon on le redirige vers le dashboard
// @TODO : choix du rôle sur la page d'admin sonata OU redirection vers l'index avec modale choix du rôle
// $redirection = new RedirectResponse($this->router->generate('sonata_admin_dashboard'));
$redirection = new RedirectResponse($this->router->generate('index'));
}
$redirection = new RedirectResponse($this->router->generate('sonata_admin_dashboard'));
} else {
$redirection = new RedirectResponse($this->router->generate('index'));
}
......@@ -85,17 +124,9 @@ class AfterLoginRedirection implements AuthenticationSuccessHandlerInterface
return $redirection;
}
/**
* @return string|null
*/
private function getTargetUrlFromSession(SessionInterface $session, TokenInterface $token)
private function updateToken($user)
{
$key = sprintf('_security.%s.target_path', $token->getProviderKey());
if ($session->has($key)) {
return $session->get($key);
}
return null;
$token = new UsernamePasswordToken($user, $user->getPassword(), 'main', $user->getRoles());
$this->tokenStorage->setToken($token);
}
}
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20200605122646 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE TABLE user_possiblegroup (user_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_A6B5F5DFA76ED395 (user_id), INDEX IDX_A6B5F5DFFE54D947 (group_id), PRIMARY KEY(user_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE `utf8_general_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE user_possiblegroup ADD CONSTRAINT FK_A6B5F5DFA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)');
$this->addSql('ALTER TABLE user_possiblegroup ADD CONSTRAINT FK_A6B5F5DFFE54D947 FOREIGN KEY (group_id) REFERENCES usergroup (id)');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP TABLE user_possiblegroup');
}
}
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20200605124113 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
// Migrate usergroup to possibleusergroup and reinit user_usergroup
$this->addSql('INSERT INTO user_possiblegroup SELECT * FROM user_usergroup');
$this->addSql('DELETE FROM user_usergroup');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
}
}
......@@ -3,7 +3,6 @@
namespace App\Security\Handler;
use App\Entity\GlobalParameter;
use App\Tools\RoleCheck;
use Doctrine\ORM\EntityManagerInterface;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Security\Handler\RoleSecurityHandler;
......@@ -12,7 +11,6 @@ use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundE
class VoterSecurityHandler extends RoleSecurityHandler
{
protected $manager;
protected $rolecheck;
/**
* {@inheritdoc}
......@@ -29,6 +27,7 @@ class VoterSecurityHandler extends RoleSecurityHandler
$allRole = sprintf($this->getBaseRole($admin), 'ALL');
/* Si on utilise le front Wordpress, on ne fait pas apparaitre la gestion du front (faq, page, document, menu, news...) */
$isWordpress = $this->manager->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_WORDPRESS) != 'false';
if ($isWordpress) {
foreach ($attributes as $attribute) {
......@@ -55,11 +54,6 @@ class VoterSecurityHandler extends RoleSecurityHandler
$this->manager = $manager;
}
public function setRolecheck(RoleCheck $rolecheck)
{
$this->rolecheck = $rolecheck;
}
private function isAnyGranted(array $attributes, $subject = null): bool
{
foreach ($attributes as $attribute) {
......
<?php
namespace App\Security;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class LoginAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'fos_user_security_login';
private $entityManager;
private $urlGenerator;
private $csrfTokenManager;
private $passwordEncoder;
public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
{
$this->entityManager = $entityManager;
$this->urlGenerator = $urlGenerator;
$this->csrfTokenManager = $csrfTokenManager;
$this->passwordEncoder = $passwordEncoder;
}
public function supports(Request $request)
{
return self::LOGIN_ROUTE === $request->attributes->get('_route')
&& $request->isMethod('POST');
}
public function getCredentials(Request $request)
{
$credentials = [
'username' => $request->request->get('username'),
'password' => $request->request->get('password'),
'csrf_token' => $request->request->get('_csrf_token'),
];
$request->getSession()->set(
Security::LAST_USERNAME,
$credentials['username']
);
return $credentials;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$token = new CsrfToken('authenticate', $credentials['csrf_token']);
if (!$this->csrfTokenManager->isTokenValid($token)) {
throw new InvalidCsrfTokenException();
}
$user = $this->entityManager->getRepository(User::class)->findOneBy(['username' => $credentials['username']]);
if (!$user) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('Username could not be found.');
}
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*/
public function getPassword($credentials): ?string
{
return $credentials['password'];
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
return new RedirectResponse($targetPath);
}
// For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
// throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
return new RedirectResponse($this->urlGenerator->generate('index'));
}
protected function getLoginUrl()
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}
<?php
namespace App\Security\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class AdherentVoter extends Voter
{
protected function supports($attribute, $subject)
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, ['POST_EDIT', 'POST_VIEW'])
&& $subject instanceof \App\Entity\BlogPost;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case 'POST_EDIT':
// logic to determine if the user can EDIT
// return true or false
break;
case 'POST_VIEW':
// logic to determine if the user can VIEW
// return true or false
break;
}
return false;
}
}
<?php
namespace App\Tools;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Role\Role;
class RoleCheck
{
private $security;
private $session;
public function __construct(Security $security, SessionInterface $session)
{
$this->security = $security;
$this->session = $session;
}
/**
* Fonction permettant de vérifier que l'utilisateur a choisi ce rôle si il en a plusieurs ou sinon qu'il a bien ce rôle
*
* @param string $role Role
* @return boolean Boolean
*/
public function isGranted($role)
{
if ($this->session->has('_groupId')) {
$group = $this->session->get('_groupId');
return (in_array($role, $group->getRoles()) && ($this->security->getUser() && $this->security->getUser()->isGranted($role)));
} else {
return ($this->security->getUser() && $this->security->getUser()->isGranted($role));
}
}
public function getCurrentRole()
{
if ($this->session->has('_groupId')) {
return $this->session->get('_groupId');
} else {
if (count($this->security->getUser()->getRoles()) == 1) {
return $this->security->getUser()->getRoles()[0];
} elseif (count($this->security->getUser()->getRoles()) <= 0) {
throw new \Exception('Utilisateur sans rôle => Impossible de faire une transaction ! ');
} elseif (count($this->security->getUser()->getGroups()) == 1) {
return $this->security->getUser()->getGroups()[0];
} else {
// $roles = $this->security->getUser()->getRoles();
// if (in_array('ROLE_USER', $roles)) {
// unset($roles[array_search('ROLE_USER', $roles)]);
// }
// if (count($this->security->getUser()->getRoles()) == 1) {
// return $this->security->getUser()->getRoles()[0];
// } else {
// return new Role('ROLE_USER');
// }
throw new \Exception('Utilisateur avec plusieurs rôles devant choisir le rôle avant de faire une transaction ! ');
}
}
}
}
......@@ -11,7 +11,6 @@ use App\Entity\Prestataire;
use App\Entity\Rubrique;
use App\Entity\Siege;
use App\Entity\User;
use App\Tools\RoleCheck;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
......@@ -31,26 +30,24 @@ class AppExtension extends AbstractExtension
public $container;
public $paginator;
public $session;
public $rolecheck;
public function __construct(ContainerInterface $container, Security $security, EntityManagerInterface $em, PaginatorInterface $paginator, SessionInterface $session, RoleCheck $rolecheck)
public function __construct(ContainerInterface $container, Security $security, EntityManagerInterface $em, PaginatorInterface $paginator, SessionInterface $session)
{
$this->em = $em;
$this->security = $security;
$this->container = $container;
$this->paginator = $paginator;
$this->session = $session;
$this->rolecheck = $rolecheck;
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('showModalGroupChoice', array($this, 'showModalGroupChoice')),
new \Twig_SimpleFunction('getCurrentComptoir', array($this, 'getCurrentComptoir')),
new \Twig_SimpleFunction('getCurrentGroupe', array($this, 'getCurrentGroupe')),
new \Twig_SimpleFunction('getCurrentPrestataire', array($this, 'getCurrentPrestataire')),
new \Twig_SimpleFunction('isCotisationValid', array($this, 'isCotisationValid')),
new \Twig_SimpleFunction('isCurrentRoleGranted', array($this, 'isCurrentRoleGranted')),
new \Twig_SimpleFunction('getSiege', array($this, 'getSiege')),
new \Twig_SimpleFunction('isDevFixture', array($this, 'isDevFixture')),
new \Twig_SimpleFunction('getLastNews', array($this, 'getLastNews')),
......@@ -67,6 +64,16 @@ class AppExtension extends AbstractExtension
];
}
public function showModalGroupChoice()
{
if ($this->security->getUser() != null) {
if (count($this->security->getUser()->getPossiblegroups()) > 1 && count($this->security->getUser()->getGroups()) == 0) {
return true;
}
}
return false;
}
public function getCurrentComptoir()
{
if (!$this->session->has('_comptoirgere')) {
......@@ -94,9 +101,9 @@ class AppExtension extends AbstractExtension
public function isCotisationValid(): bool
{
if ($this->security->getUser() != null) {
if ($this->isCurrentRoleGranted('ROLE_ADHERENT') && $this->security->getUser()->getAdherent() != null) {
if ($this->security->getUser()->isGranted('ROLE_ADHERENT') && $this->security->getUser()->getAdherent() != null) {
$query = $this->em->getRepository(Flux::class)->getQueryByAdherent($this->security->getUser()->getAdherent(), 'cotisation');
} elseif ($this->isCurrentRoleGranted('ROLE_PRESTATAIRE') && $this->session->get('_prestagere') != null) {
} elseif ($this->security->getUser()->isGranted('ROLE_PRESTATAIRE') && $this->session->get('_prestagere') != null) {
$query = $this->em->getRepository(Flux::class)->getQueryByPrestataire($this->session->get('_prestagere'));
}
$cotisations = $query->getResult();
......@@ -109,11 +116,6 @@ class AppExtension extends AbstractExtension
return false;
}
public function isCurrentRoleGranted($role)
{
return $this->rolecheck->isGranted($role);
}
public function isDevFixture(?string $username = null)
{
if ($username == null) {
......
......@@ -456,6 +456,9 @@
"sonata-project/exporter": {
"version": "1.9.1"
},
"sonata-project/form-extensions": {
"version": "0.1.2"
},
"sonata-project/formatter-bundle": {
"version": "4.1.2"
},
......@@ -480,6 +483,9 @@
"ref": "00e821cb362f00c6893f7183311893267330ecfe"
}
},
"sonata-project/twig-extensions": {
"version": "0.1.1"
},
"sonata-project/user-bundle": {
"version": "4.2.3"
},
......@@ -669,6 +675,9 @@
"symfony/polyfill-php73": {
"version": "v1.13.1"
},
"symfony/polyfill-php80": {
"version": "v1.17.0"
},
"symfony/process": {
"version": "v4.1.7"
},
......
......@@ -22,7 +22,7 @@
{% endfor %}
</ul>
{% if (isCurrentRoleGranted('ROLE_ADHERENT') and app.user.adherent or (isCurrentRoleGranted('ROLE_PRESTATAIRE') and app.session.has('_prestagere'))) %}
{% if ((app.user and app.user.isGranted('ROLE_ADHERENT') and app.user.adherent) or (app.user and app.user.isGranted('ROLE_PRESTATAIRE') and app.session.has('_prestagere'))) %}
<a class='btn btn-xs btn-primary' href='{{ path('cotiser') }}'>
{{ 'Cotiser en MLC'|trans }}
</a>
......
{% set compte = compte|default('[ERREUR] !') %}
{% set soldelabel = soldelabel|default('Solde'|trans) %}
{% set icon = icon|default('fa-coins'|trans) %}
{% set icon = icon|default(''|trans) %}
<div class="card mb-3">
<div class="card-header"><i class="fa {{icon}} mr-4"></i> {{soldelabel}} : <b>{{compte}}</b></div>
<div class="card-body p-2"><i class="fa {{icon}} mr-4"></i> {{soldelabel}} : <b>{{compte}}</b></div>
</div>
<!-- small box -->
......
......@@ -7,7 +7,7 @@
{{ 'RETOUR SUPER ADMIN'|trans }}
</a>
</div>
{% elseif isCurrentRoleGranted('ROLE_SUPER_ADMIN') %}
{% elseif app.user and app.user.isGranted('ROLE_SUPER_ADMIN') %}
<div class='mb-2 group text-center'>
{% if isDevFixture('user_prestataire') %}
<a class='btn btn-xs m-1 btn-primary' href='{{path('index', [], true)}}?_switch_user=user_prestataire'>
......@@ -61,7 +61,7 @@
{# ACTIONS PRINCIPALES POUR CHAQUE UTILISATEUR CONNECTE #}
<div id="accordion">
{% if not app.request.session.has('_choixGroup') %}
{% if isCurrentRoleGranted('ROLE_ADMIN_SIEGE') %}
{% if app.user and app.user.isGranted('ROLE_ADMIN_SIEGE') %}
{% set siege = getSiege() %}
{% set compte = siege.getCompte() %}
......@@ -73,12 +73,12 @@
{% include 'siege/block/transfert_siegegroupe.html.twig' %}
{% include 'siege/block/transfert_groupesiege.html.twig' %}
{% elseif isCurrentRoleGranted('ROLE_REDACTEUR') %}
{% elseif app.user and app.user.isGranted('ROLE_REDACTEUR') %}
{% include 'block/userinfos.html.twig' %}
{% include 'block/userpassword.html.twig' %}
{% elseif isCurrentRoleGranted('ROLE_TRESORIER') %}
{% elseif app.user and app.user.isGranted('ROLE_TRESORIER') %}
{% set siege = getSiege() %}
{% set compte = siege.getCompte() %}
......@@ -88,11 +88,11 @@
{% include 'block/userpassword.html.twig' %}
{# {% include 'block/soldegroupes.html.twig' %} #}
{% elseif isCurrentRoleGranted('ROLE_CONTROLEUR') %}
{% elseif app.user and app.user.isGranted('ROLE_CONTROLEUR') %}
{% include 'block/userinfos.html.twig' %}
{% elseif isCurrentRoleGranted('ROLE_GESTION_GROUPE') %}
{% elseif app.user and app.user.isGranted('ROLE_GESTION_GROUPE') %}
{% if getCurrentGroupe() != null %}
{% set compte = getCurrentGroupe().compte %}
......@@ -106,7 +106,7 @@
{% include 'groupe/block/transaction_comptoir.html.twig' %}
{% include 'groupe/block/retourgroupe.html.twig' %}
{% elseif isCurrentRoleGranted('ROLE_COMPTOIR') %}
{% elseif app.user and app.user.isGranted('ROLE_COMPTOIR') %}
{% if getCurrentComptoir() != null %}
{% set compte = getCurrentComptoir().compte %}
......@@ -123,13 +123,13 @@
{% include 'comptoir/block/retrait_adherent.html.twig' %}
{% include 'comptoir/block/reconversion.html.twig' %}
{% elseif isCurrentRoleGranted('ROLE_CONTACT') %}
{% elseif app.user and app.user.isGranted('ROLE_CONTACT') %}
{% include 'groupe/block/infos.html.twig' %}
{% include 'block/userinfos.html.twig' %}
{% include 'block/userpassword.html.twig' %}
{% elseif isCurrentRoleGranted('ROLE_SUPER_ADMIN') %}
{% elseif app.user and app.user.isGranted('ROLE_SUPER_ADMIN') %}
{% set siege = getSiege() %}
{% set compte = siege.getCompte() %}
......@@ -139,7 +139,7 @@
{% include 'block/userinfos.html.twig' %}
{% include 'block/userpassword.html.twig' %}
{% elseif isCurrentRoleGranted('ROLE_PRESTATAIRE') and app.user and getCurrentPrestataire() != null %}
{% elseif app.user and app.user.isGranted('ROLE_PRESTATAIRE') and getCurrentPrestataire() != null %}
{% set esoldelabel = 'Solde e-mlc'|trans %}
{% include 'block/solde.html.twig' with {'compte': getCurrentPrestataire().ecompte, 'soldelabel': esoldelabel} %}
......@@ -159,7 +159,7 @@
{% include 'presta/block/reconversion.html.twig' %}
{% endif %}
{% elseif isCurrentRoleGranted('ROLE_ADHERENT') and app.user and app.user.adherent %}
{% elseif app.user and app.user.isGranted('ROLE_ADHERENT') and app.user.adherent %}
{% set esoldelabel = 'Solde e-mlc'|trans %}
{% include 'block/solde.html.twig' with {'compte': app.user.adherent.ecompte, 'soldelabel': esoldelabel} %}
......
{% extends 'block/block_collapse.html.twig' %}
{% block blocktitle %}
<i class="fa fa-user-cog mr-4"></i> {{ 'Compte utilisateur'|trans }}
<i class="fa fa-user mr-4"></i> {{ 'Compte utilisateur'|trans }}
{% endblock blocktitle %}
{% block blocksubtitle %}
{% endblock blocksubtitle %}
......
{% extends 'block/block_collapse.html.twig' %}
{% block blocktitle %}
<i class="fa fa-user-cog mr-4"></i> {{ 'Changer votre mot de passe'|trans }}
<i class="fa fa-lock mr-4"></i> {{ 'Changer votre mot de passe'|trans }}
{% endblock blocktitle %}
{% block blocksubtitle %}
{% endblock blocksubtitle %}
......
......@@ -445,6 +445,9 @@ Modified for MLC from Sonata package.
{% block js %}
{{ encore_entry_script_tags('admin') }}
<script type="text/javascript">
$('.viewChoiceGroup').on('click', function () {
$('#roleGroupeModal').modal('show');
});
$(document).ready(function() {
$.datepicker.regional['fr'] = {
closeText: 'Fermer',
......@@ -478,6 +481,8 @@ Modified for MLC from Sonata package.
});
</script>
{% endblock js %}
{% include 'common/modale_choix_groupe.html.twig' %}
{# FIN AJOUT #}
</body>
......
......@@ -44,10 +44,14 @@ file that was distributed with this source code.
#}
<li class="user-footer">
<div class="pull-left">
{# <div class="pull-left">
<a href="{{ _profile_uri }}" class="btn btn-default btn-flat"><i class="fa fa-user"></i> {{ _profile_text }}</a>
</div>
</div> #}
{% if app.user.possiblegroups|length > 1 %}
<div class="pull-left">
<a href="#" class="viewChoiceGroup btn btn-default btn-flat"><i class='fa fa-group fa-fw'></i> {{ 'Choix du rôle'|trans }}</a>
</div>
{% endif %}
<div class="pull-right">
<a href="{{ _logout_uri }}" class="btn btn-default btn-flat"><i class="fa fa-sign-out fa-fw"></i> {{ _logout_text }}</a>
</div>
......
......@@ -66,7 +66,7 @@
{% block js %} {% endblock js %}
{# AFFICHAGE DE LA MODALE DE CHOIX DU RÔLE (groupe associé aux rôles) #}
{% if app.request.session.has('_choixGroup') %}
{% if showModalGroupChoice() %}
<script type="text/javascript">
$(document).ready(function() {
$('#roleGroupeModal').modal('show');
......
......@@ -25,15 +25,7 @@
{{ tree.menu(menuItems, currentPath) }}
{% endif %}
{# MENU UTILISATEUR AYANT ACCES A L'ADMIN CONNECTE #}
{% if app.user and (isCurrentRoleGranted('ROLE_ADMIN_SIEGE') or
isCurrentRoleGranted('ROLE_SUPER_ADMIN') or
isCurrentRoleGranted('ROLE_TRESORIER') or
isCurrentRoleGranted('ROLE_REDACTEUR') or
isCurrentRoleGranted('ROLE_CONTACT') or
isCurrentRoleGranted('ROLE_GESTION_GROUPE') or
isCurrentRoleGranted('ROLE_COMPTOIR') or
isCurrentRoleGranted('ROLE_CONTROLEUR')
) %}
{% if app.user and app.user.isGranted('ROLE_ADMIN') %}
<li class="nav-item" role="menu-item">
<a href="{{ path('sonata_admin_dashboard') }}" class="nav-link" data-toggle="tooltip" data-placement="bottom" title="{{ 'Administration'|trans }}">
<i class="fas fa-cog text-primary"></i>{% if KOH_USE_WORDPRESS != 'false' %}<span class='ml-1 text-primary'>Administration</span>{% endif %}
......@@ -71,16 +63,16 @@
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownUC">
{# COMPTE ou ECOMPTE : @TODO : mettre plutôt dans le header en visible tout le temps ? #}
{% if isCurrentRoleGranted('ROLE_ADHERENT') %}
{% if app.user and app.user.isGranted('ROLE_ADHERENT') %}
<b class="dropdown-item bg-primary text-white"> Ecompte : {{app.user.adherent.ecompte }}</b>
{% elseif isCurrentRoleGranted('ROLE_PRESTATAIRE') and getCurrentPrestataire() != null %}
{% elseif app.user and app.user.isGranted('ROLE_PRESTATAIRE') and getCurrentPrestataire() != null %}
<b class="dropdown-item bg-primary text-white"> Ecompte : {{getCurrentPrestataire().ecompte }}</b>
{% elseif getCurrentGroupe() != null %}
<b class="dropdown-item bg-primary text-white"> Compte : {{getCurrentGroupe().compte }}</b>
{% elseif getCurrentComptoir() != null %}
<b class="dropdown-item bg-primary text-white"> Compte : {{getCurrentComptoir().compte }}</b>
{% endif %}
{% if app.user.groups|length > 1 %}
{% if app.user.possiblegroups|length > 1 %}
<a href="#" class="viewChoiceGroup dropdown-item">{{ 'Choix du rôle'|trans }}</a>
{% endif %}
{% if is_granted('ROLE_PREVIOUS_ADMIN') %}
......
......@@ -8,29 +8,29 @@
<div class="modal-body">
<div class='row'>
{% if app.user %}
{% for group in app.user.groups %}
{% for group in app.user.possiblegroups %}
{% for role in group.roles %}
{% if role == 'ROLE_PRESTATAIRE' %}
{% for presta in app.user.prestataires %}
<div class='col-6 text-center p-2'>
<a role="button" class="btn btn-secondary" href='{{path('presta_choice', {'prestaid' : presta.id, 'usergrpid': group.id})}}'>{{ group.name|trans }} - {{presta}} </a>
<a role="button" class="btn btn-default btn-secondary" href='{{path('presta_choice', {'prestaid' : presta.id, 'usergrpid': group.id})}}'>{{ group.name|trans }} - {{presta}} </a>
</div>
{% endfor %}
{% elseif role == 'ROLE_COMPTOIR' %}
{% for comptoir in app.user.comptoirsgeres %}
<div class='col-6 text-center p-2'>
<a role="button" class="btn btn-secondary" href='{{path('comptoir_choice', {'cptid' : comptoir.id, 'usergrpid': group.id})}}'>{{ group.name|trans }} - {{comptoir}} </a>
<a role="button" class="btn btn-default btn-secondary" href='{{path('comptoir_choice', {'cptid' : comptoir.id, 'usergrpid': group.id})}}'>{{ group.name|trans }} - {{comptoir}} </a>
</div>
{% endfor %}
{% elseif role == 'ROLE_TRESORIER' or role == 'ROLE_CONTACT' or role == 'ROLE_GESTION_GROUPE' %}
{% for groupe in app.user.groupesgeres %}
<div class='col-6 text-center p-2'>
<a role="button" class="btn btn-secondary" href='{{path('groupe_choice', {'grpid' : groupe.id, 'usergrpid': group.id})}}'>{{ group.name|trans }} - {{groupe}} </a>
<a role="button" class="btn btn-default btn-secondary" href='{{path('groupe_choice', {'grpid' : groupe.id, 'usergrpid': group.id})}}'>{{ group.name|trans }} - {{groupe}} </a>
</div>
{% endfor %}
{% elseif role == 'ROLE_ADHERENT' or role == 'ROLE_ADMIN_SIEGE' or role == 'ROLE_REDACTEUR' or role == 'ROLE_CONTROLEUR' or role == 'ROLE_SUPER_ADMIN' %}
<div class='col-6 text-center p-2'>
<a role="button" class="btn btn-secondary" href='{{path('usergroup_choice', {'id': group.id})}}'>{{ group.name|trans }}</a>
<a role="button" class="btn btn-default btn-secondary" href='{{path('usergroup_choice', {'id': group.id})}}'>{{ group.name|trans }}</a>
</div>
{% endif %}
{% endfor %}
......
......@@ -4,10 +4,10 @@
<div class='container' style='max-width: 800px;'>
<h2 class='text-center w-100 mt-3'>{{ "Cotiser pour l'année"|trans }} {{ "now"|date('Y') }}</h2>
<div class='text-center mb-5'>
{% if isCurrentRoleGranted('ROLE_ADHERENT') %}
{% if app.user and app.user.isGranted('ROLE_ADHERENT') %}
<h4>{{ 'Solde de eMLC'|trans }} : <b>{{ app.user.adherent.ecompte }}</b></h4>
<h5>{{ 'Montant minimum de la cotisation'|trans }} : <b>{{ KOH_COTISATION_ADHERENT|default('') }}</b></h5>
{% elseif isCurrentRoleGranted('ROLE_PRESTATAIRE') %}
{% elseif app.user and app.user.isGranted('ROLE_PRESTATAIRE') %}
<h4>{{ 'Solde de eMLC'|trans }} : <b>{{ app.session.get('_prestagere').ecompte }}</b></h4>
<h5>{{ 'Montant minimum de la cotisation'|trans }} : <b>{{ KOH_COTISATION_PRESTATAIRE|default('') }}</b></h5>
{% endif %}
......
......@@ -14,7 +14,7 @@
{% if presta.geolocs|length > 0 %}
{% for geolocp in presta.geolocs %}
{% if geolocp.enabled and geolocp.geoloc.lat != null and geolocp.geoloc.lon != null %}
{% if presta.rubriques.first.media is not null %}
{% if presta.rubriques|length > 0 and presta.rubriques.first.media is not null %}
var icon = L.icon({
iconSize: [50, 50],
iconAnchor: [50,25],
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment