feat: align role assignment logic with myep-team

This commit is contained in:
Björn Fromme
2026-08-19 12:14:09 +02:00
parent 5a3957e143
commit 0c667d6b69
23 changed files with 1109 additions and 527 deletions
@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\User;
use App\Controller\Traits\ReturnUrlTrait;
use App\Entity\User;
use App\Htmx\HxRedirectResponse;
use App\Security\Role;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\Security\Http\Authenticator\Token\PostAuthenticationToken;
/**
* Turns a nomination from the BusPro CRM into an actual role.
*
* This is deliberately its own action rather than a field on a form: it grants a privilege, so
* it is confirmed on its own, logged on its own, and cannot happen as a side effect of saving
* something unrelated. The nomination is checked again on submit, so a sync that revoked the
* claim while the dialog was open cannot be approved through. Role::SELF_APPROVAL_FORBIDDEN is
* refused for your own account.
*/
#[IsGranted('ROLE_ADMIN')]
class ApproveRoleController extends AbstractController
{
use ReturnUrlTrait;
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
private readonly TokenStorageInterface $tokenStorage,
) {
}
#[Route('/admin/user/{id}/approve/{role}', name: 'app_admin_user_approve_role', requirements: ['role' => 'ROLE_[A-Z_]+'])]
public function index(User $user, string $role, Request $request): Response
{
if ($user === $this->getUser() && \in_array($role, Role::SELF_APPROVAL_FORBIDDEN, true)) {
throw $this->createAccessDeniedException(sprintf('The role "%s" cannot be approved for your own account.', $role));
}
$nominated = Role::nominatedFrom($user->getRoles());
if (false === \array_key_exists($role, $nominated)) {
throw $this->createNotFoundException(sprintf('The account is not nominated for "%s".', $role));
}
$csrfTokenId = 'approve_user_role_'.$user->getId().'_'.$role;
if ($request->isMethod(Request::METHOD_POST)) {
if (false === $this->isCsrfTokenValid($csrfTokenId, $request->request->getString('_token'))) {
throw $this->createAccessDeniedException('Invalid CSRF token.');
}
$user->setRoles(Role::approve($user->getRoles(), $role));
$this->entityManager->flush();
$this->reissueOwnSecurityToken($user);
$this->addFlash('success', sprintf('Die Rolle %s wurde freigeschaltet', $nominated[$role]));
$this->logger->info('Approved user role', [
'email' => $user->getEmail(),
'role' => $role,
'roles' => $user->getRoles(),
]);
return new HxRedirectResponse($this->getReturnUrl($request, 'app_admin_user'));
}
return $this->render('admin/user/modal_approve_role.html.twig', [
'user' => $user,
'role_label' => $nominated[$role],
'csrf_token_id' => $csrfTokenId,
]);
}
/**
* Keeps the approver signed in when they just approved a role for themselves.
*
* A token carries the role names it was issued with, and ContextListener ends the session
* as soon as the stored user no longer matches them — the safeguard that makes a revocation
* take effect at once. Here the grant is deliberate and just happened under ROLE_ADMIN, so
* the token is re-issued with the new roles instead of the session being dropped.
*/
private function reissueOwnSecurityToken(User $user): void
{
$token = $this->tokenStorage->getToken();
if (false === $token instanceof PostAuthenticationToken || $token->getUser() !== $user) {
return;
}
$this->tokenStorage->setToken(
new PostAuthenticationToken($user, $token->getFirewallName(), $user->getRoles()),
);
}
}
@@ -1,78 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\User;
use App\Controller\Traits\ReturnUrlTrait;
use App\Entity\User;
use App\Form\Admin\UserType;
use App\Htmx\HxRedirectResponse;
use App\Security\Role;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_ADMIN')]
class EditController extends AbstractController
{
use ReturnUrlTrait;
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
) {
}
#[Route('/admin/user/{id}/edit', name: 'app_admin_user_edit')]
public function index(User $user, Request $request): Response
{
$previousRoles = $user->getRoles();
$previousHotelCodes = $user->getHotelCodes();
$form = $this->createForm(UserType::class, $user, ['hx_post' => $request->getRequestUri()]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($this->locksOutSelf($user)) {
$form->get('roles')->addError(new FormError('Du kannst dir die Rolle Administration nicht selbst entziehen.'));
return $this->render('admin/user/modal_edit.html.twig', [
'user' => $user,
'form' => $form,
'syncedRoles' => Role::syncedOnly($user->getRoles()),
]);
}
$this->entityManager->flush();
$this->addFlash('success', 'Der Benutzeraccount wurde aktualisiert');
$this->logger->info('Updated user permissions', [
'email' => $user->getEmail(),
'previousRoles' => $previousRoles,
'roles' => $user->getRoles(),
'previousHotelCodes' => $previousHotelCodes,
'hotelCodes' => $user->getHotelCodes(),
]);
return new HxRedirectResponse($this->getReturnUrl($request, 'app_admin_user'));
}
return $this->render('admin/user/modal_edit.html.twig', [
'user' => $user,
'form' => $form,
'syncedRoles' => Role::syncedOnly($user->getRoles()),
]);
}
private function locksOutSelf(User $user): bool
{
return $user === $this->getUser() && false === \in_array(Role::ADMIN, $user->getRoles(), true);
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Controller\Admin\User;
use App\Entity\User;
use App\Security\Role;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Shows what an account holds and what it is nominated for.
*
* Nothing here is editable: roles and hotel codes come from the BusPro CRM and are synced on
* every login, so the only administrative act is approving a nomination — which is its own
* route, its own confirmation and its own log entry (see ApproveRoleController).
*/
#[IsGranted('ROLE_ADMIN')]
class ShowController extends AbstractController
{
#[Route('/admin/user/{id}/permissions', name: 'app_admin_user_permissions')]
public function index(User $user, Request $request): Response
{
$nominated = Role::nominatedFrom($user->getRoles());
// What ApproveRoleController would refuse for this account is not offered either, so
// nobody is sent into an access denied page.
$refused = $user === $this->getUser()
? array_intersect_key($nominated, array_flip(Role::SELF_APPROVAL_FORBIDDEN))
: [];
return $this->render('admin/user/modal_permissions.html.twig', [
'user' => $user,
'approvableRoles' => array_diff_key($nominated, $refused),
'selfRefusedRoles' => $refused,
'returnUrl' => $this->forwardedReturnUrl($request),
]);
}
/**
* Where an approval started from, still encoded the way return_url() handed it over.
*
* The approval links must forward what this modal was given rather than call return_url()
* themselves: that function answers with the *current* request URI, which here is the modal
* itself — and redirecting to it after the approval would render a bare modal as a page.
*/
private function forwardedReturnUrl(Request $request): string
{
$returnUrl = $request->query->getString('r');
return '' !== $returnUrl ? $returnUrl : rawurlencode($this->generateUrl('app_admin_user'));
}
}
+1 -1
View File
@@ -55,7 +55,7 @@ class UserinfoController extends AbstractController
// Patch current user's roles. The implicit ROLE_USER says nothing about the
// account — every authenticated user holds it — and is not exported.
$data->roles = Role::assignedOnly($user->getRoles());
$data->roles = Role::effectiveOnly($user->getRoles());
// Patch current user's hotel codes
$data->hotelCodes = $user->getHotelCodes();