From 669cbfdaca7f2bb7e41bcf9ea393f7822f263f06 Mon Sep 17 00:00:00 2001 From: tim Date: Sat, 8 Apr 2023 17:58:14 +0200 Subject: [PATCH] Allow public raw snips to be accessed without account --- config/packages/security.yaml | 2 ++ src/Security/Voter/SnipVoter.php | 10 ++++------ src/Service/SnipService.php | 8 ++++++-- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/config/packages/security.yaml b/config/packages/security.yaml index 2c0256c..17a429e 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -43,6 +43,8 @@ security: - { path: ^/logout$, role: ROLE_USER } - { path: ^/admin, role: ROLE_ADMIN } + - { path: ^/snip/raw, role: PUBLIC_ACCESS } + - { path: ^/, role: ROLE_USER } when@test: diff --git a/src/Security/Voter/SnipVoter.php b/src/Security/Voter/SnipVoter.php index 7aefe01..d28649d 100644 --- a/src/Security/Voter/SnipVoter.php +++ b/src/Security/Voter/SnipVoter.php @@ -23,19 +23,17 @@ class SnipVoter extends Voter protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool { /** @var Snip $subject */ - $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 self::VIEW: if ($subject->isPublic()) { return true; } case self::EDIT: + $user = $token->getUser(); + if (!$user instanceof UserInterface) { + return false; + } if ($subject->getCreatedBy() === $user) { return true; } diff --git a/src/Service/SnipService.php b/src/Service/SnipService.php index 952ff69..810a8d8 100644 --- a/src/Service/SnipService.php +++ b/src/Service/SnipService.php @@ -4,6 +4,7 @@ namespace App\Service; use App\Entity\User; use App\Git\CustomGitRepository; +use Symfony\Component\Security\Core\User\UserInterface; class SnipService { @@ -12,7 +13,7 @@ class SnipService public function __construct( private readonly CustomGitRepository $repo, - private readonly User $user, + private readonly ?User $user, ) { } @@ -29,6 +30,9 @@ class SnipService public function update(string $snipContents): void { + if (!$this->user instanceof UserInterface) { + return; + } if ($this->repo->getCurrentBranchName() !== self::MASTER_BRANCH_NAME) { $this->repo->checkout(self::MASTER_BRANCH_NAME); } @@ -54,6 +58,6 @@ class SnipService public function deleteRepo(): void { - system("rm -rf ".escapeshellarg($this->repo->getRepositoryPath())); + system("rm -rf " . escapeshellarg($this->repo->getRepositoryPath())); } } \ No newline at end of file