- ensureCanAccessMail : refuse ROLE_CLIENT pur (sans ROLE_ADMIN) - ensureIsAdmin : helper pour endpoints config - service utilise par tous les controllers metier mail Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
54 lines
1.6 KiB
PHP
54 lines
1.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Security;
|
|
|
|
use App\Entity\User;
|
|
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
|
|
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
|
|
use Symfony\Component\Security\Core\User\UserInterface;
|
|
|
|
final readonly class MailAccessChecker
|
|
{
|
|
public function __construct(
|
|
private AuthorizationCheckerInterface $authorizationChecker,
|
|
) {}
|
|
|
|
/**
|
|
* Verifie que l'utilisateur courant peut acceder aux endpoints mail.
|
|
* Autorise : ROLE_USER, ROLE_ADMIN.
|
|
* Refuse : ROLE_CLIENT pur (sans ROLE_ADMIN), non authentifie.
|
|
*
|
|
* @throws AccessDeniedException
|
|
*/
|
|
public function ensureCanAccessMail(?UserInterface $user): void
|
|
{
|
|
if (!$user instanceof User) {
|
|
throw new AccessDeniedException('Authentication required');
|
|
}
|
|
|
|
$roles = $user->getRoles();
|
|
|
|
if (in_array('ROLE_CLIENT', $roles, true) && !in_array('ROLE_ADMIN', $roles, true)) {
|
|
throw new AccessDeniedException('Mail not accessible to clients');
|
|
}
|
|
|
|
if (!in_array('ROLE_USER', $roles, true) && !in_array('ROLE_ADMIN', $roles, true)) {
|
|
throw new AccessDeniedException('ROLE_USER required');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Verifie que l'utilisateur est ROLE_ADMIN.
|
|
*
|
|
* @throws AccessDeniedException
|
|
*/
|
|
public function ensureIsAdmin(?UserInterface $user): void
|
|
{
|
|
if (!$user instanceof User || !$this->authorizationChecker->isGranted('ROLE_ADMIN')) {
|
|
throw new AccessDeniedException('Admin only');
|
|
}
|
|
}
|
|
}
|