Last active
August 29, 2015 14:28
-
-
Save lashae/2f88768b3c0e6d3bee74 to your computer and use it in GitHub Desktop.
Sf2 Voter Implementation
This file contains hidden or 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
# app/config/services.yml | |
services: | |
security.access.todo_voter: | |
class: AppBundle\Security\Authorization\Voter\TodoVoter | |
public: false | |
tags: | |
- { name: security.voter } |
This file contains hidden or 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 | |
// AppBundle/Controller/TodoController.php | |
namespace AppBundle\Controller; | |
use AppBundle\Entity\Todo; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; | |
class TodoController extends Controller | |
{ | |
/** | |
* @Security("is_granted('edit', todo)") | |
*/ | |
public function editAction(Todo $todo) { | |
// Yetkilendirilmeyen kimse buraya giremez. | |
} |
This file contains hidden or 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 | |
// AppBundle/Security/Authorization/Voter/TodoVoter.php | |
namespace AppBundle\Security\Authorization\Voter; | |
use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter; | |
use Symfony\Component\Security\Core\User\UserInterface; | |
class TodoVoter extends AbstractVoter | |
{ | |
const EDIT = 'edit'; | |
protected function getSupportedAttributes() | |
{ | |
return array(self::EDIT); | |
} | |
protected function getSupportedClasses() | |
{ | |
return array('AppBundle\Entity\Todo'); | |
} | |
/** | |
* @param string $attribute | |
* @param \AppBundle\Entity\Todo $todo | |
* @param \AppBundle\Entity\User $user | |
* @return bool | |
*/ | |
protected function isGranted($attribute, $todo, $user = null) | |
{ | |
/* | |
* Sadece giriş yapmış kullanıcılar için bu Voter'ı kullanacağız bu yüzden | |
* aslında aşağıdaki kontrole gerek yok, ancak alışkanlık olarak bulundurmakta | |
* fayda var. | |
*/ | |
if (!$user instanceof UserInterface) { | |
return false; | |
} | |
switch ($attribute) { | |
case self::EDIT: | |
foreach ($todo->getUsers() as $allowedUser) { | |
if($allowedUser->getId() == $user->getId()) { | |
return true; | |
} | |
} | |
break; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment