<?php
declare(strict_types=1);
namespace App\Security\Voters;
use App\Entity\Client;
use App\Entity\OA2User;
use App\Entity\Psd2Consent;
use App\Repository\ClientRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class Psd2ConsentVoter extends Voter
{
public const PERMISSION_VIEW = 'view';
public const PERMISSION_APPROVE = 'approve';
public const PERMISSION_REJECT = 'reject';
private $clientRepository;
public function __construct(ClientRepository $clientRepository)
{
$this->clientRepository = $clientRepository;
}
protected function supports($attribute, $subject)
{
return !(!$subject instanceof Psd2Consent)
;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
/** @var Psd2Consent $psd2Consent */
$psd2Consent = $subject;
$consentClient = $psd2Consent->getAccessToken()->getUser()->getClientUser();
$currentClient = $this->getCurrentClient($token);
if (!$currentClient || !$consentClient) {
return false;
}
$user = $currentClient->getPerson()->getUser();
$consentUsername = $consentClient->getUsername();
$username = $user ? $user->getUsername() : '';
return $consentUsername === $username;
}
private function getCurrentClient(TokenInterface $token): ?Client
{
/** @var OA2User $oa2User */
$oa2User = $token->getUser();
if (!$oa2User instanceof OA2User || $oa2User->isBankUser()) {
return null; // Client user only
}
return $this->clientRepository->findOneByOa2User($oa2User);
}
}