-
-
Save dsuurlant/5988f90e757b41454ce52050fd502273 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\EventSubscriber; | |
use App\Entity\User; | |
use App\Exception\ApplicationUserNotFoundException; | |
use Symfony\Component\HttpFoundation\JsonResponse; | |
use Symfony\Component\HttpFoundation\Response; | |
use Symfony\Component\HttpKernel\Event\GetResponseEvent; | |
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; | |
/** | |
* @author Danielle Suurlant <danielle.suurlant@gmail.com> | |
*/ | |
class AuthenticatedSubscriber | |
{ | |
/** | |
* @var TokenStorageInterface | |
*/ | |
private $tokenStorage; | |
/** | |
* @param TokenStorageInterface $tokenStorage | |
*/ | |
public function __construct( | |
TokenStorageInterface $tokenStorage | |
) { | |
$this->tokenStorage = $tokenStorage; | |
} | |
/** | |
* @return User | |
* @throws ApplicationUserNotFoundException | |
*/ | |
private function getUser(): User | |
{ | |
$token = $this->tokenStorage->getToken(); | |
if (null === $token || ! $token->getUser() instanceof User) { | |
throw new ApplicationUserNotFoundException('Unable to find application user in token storage.'); | |
} | |
$user = $token->getUser(); | |
return $user; | |
} | |
/** | |
* @param GetResponseEvent $event | |
* @param string $userRelatedEntityClass | |
*/ | |
protected function setUser(GetResponseEvent $event, string $userRelatedEntityClass) | |
{ | |
$data = $event->getRequest()->get('data'); | |
if ($data instanceof $userRelatedEntityClass && | |
method_exists($data, 'getUser') && | |
method_exists($data, 'setUser') | |
) { | |
try { | |
$user = $this->getUser(); | |
} catch (ApplicationUserNotFoundException $e) { | |
$event->stopPropagation(); | |
$event->setResponse( | |
new JsonResponse( | |
[ | |
'code' => Response::HTTP_UNAUTHORIZED, | |
'message' => 'Unable to retrieve application user; request could not be fulfilled.', | |
], | |
Response::HTTP_UNAUTHORIZED | |
) | |
); | |
return; | |
} | |
if (null !== $data->getUser() && $user !== $data->getUser()) { | |
$event->stopPropagation(); | |
$event->setResponse( | |
new JsonResponse( | |
[ | |
'code' => Response::HTTP_UNAUTHORIZED, | |
'message' => 'Not authorized to perform actions on this entity.', | |
], | |
Response::HTTP_UNAUTHORIZED | |
) | |
); | |
return; | |
} | |
if (null === $data->getUser()) { | |
$data->setUser($user); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment