Skip to content

Instantly share code, notes, and snippets.

@lashae
Last active August 29, 2015 14:28
Show Gist options
  • Save lashae/2f88768b3c0e6d3bee74 to your computer and use it in GitHub Desktop.
Save lashae/2f88768b3c0e6d3bee74 to your computer and use it in GitHub Desktop.
Sf2 Voter Implementation
# app/config/services.yml
services:
security.access.todo_voter:
class: AppBundle\Security\Authorization\Voter\TodoVoter
public: false
tags:
- { name: security.voter }
<?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.
}
<?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