Skip to content

Add a security Post Voter #442

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/Resources/views/blog/post_show.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
{% endblock %}

{% block sidebar %}
{% if post.isAuthor(app.user) %}
{% if is_granted('edit', post) %}
<div class="section">
<a class="btn btn-lg btn-block btn-success" href="{{ path('admin_post_edit', { id: post.id }) }}">
<i class="fa fa-edit" aria-hidden="true"></i> {{ 'action.edit_post'|trans }}
Expand Down
8 changes: 8 additions & 0 deletions app/config/services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ services:
tags:
- { name: kernel.event_subscriber }

# To inject the voter into the security layer, you must declare it as a service and tag it with security.voter.
# See http://symfony.com/doc/current/security/voters.html#configuring-the-voter
app.post_voter:
class: AppBundle\Security\PostVoter
public: false
tags:
- { name: security.voter }

# Uncomment the following lines to define a service for the Post Doctrine repository.
# It's not mandatory to create these services, but if you use repositories a lot,
# these services simplify your code:
Expand Down
16 changes: 5 additions & 11 deletions src/AppBundle/Controller/Admin/BlogController.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,12 +119,9 @@ public function newAction(Request $request)
*/
public function showAction(Post $post)
{
// This security check can also be performed:
// 1. Using an annotation: @Security("post.isAuthor(user)")
// 2. Using a "voter" (see http://symfony.com/doc/current/cookbook/security/voters_data_permission.html)
if (!$post->isAuthor($this->getUser())) {
throw $this->createAccessDeniedException('Posts can only be shown to their authors.');
}
// This security check can also be performed
// using an annotation: @Security("is_granted('show', post)")
$this->denyAccessUnlessGranted('show', $post, 'Posts can only be shown to their authors.');

return $this->render('admin/blog/show.html.twig', [
'post' => $post,
Expand All @@ -139,9 +136,7 @@ public function showAction(Post $post)
*/
public function editAction(Post $post, Request $request)
{
if (!$post->isAuthor($this->getUser())) {
throw $this->createAccessDeniedException('Posts can only be edited by their authors.');
}
$this->denyAccessUnlessGranted('edit', $post, 'Posts can only be edited by their authors.');
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should use PostVoter::EDIT instead?


$entityManager = $this->getDoctrine()->getManager();

Expand Down Expand Up @@ -169,11 +164,10 @@ public function editAction(Post $post, Request $request)
*
* @Route("/{id}/delete", name="admin_post_delete")
* @Method("POST")
* @Security("post.isAuthor(user)")
* @Security("is_granted('delete', post)")
*
* The Security annotation value is an expression (if it evaluates to false,
* the authorization mechanism will prevent the user accessing this resource).
* The isAuthor() method is defined in the AppBundle\Entity\Post entity.
*/
public function deleteAction(Request $request, Post $post)
{
Expand Down
61 changes: 61 additions & 0 deletions src/AppBundle/Security/PostVoter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace AppBundle\Security;

use AppBundle\Entity\Post;
use AppBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

/**
* It grants or denies permissions for actions related to blog posts (such as
* showing, editing and deleting posts).
*
* See http://symfony.com/doc/current/security/voters.html
*
* @author Yonel Ceruto <[email protected]>
*/
class PostVoter extends Voter
{
// Defining these constants is overkill for this simple application, but for real
// applications, it's a recommended practice to avoid relying on "magic strings"
const SHOW = 'show';
const EDIT = 'edit';
const DELETE = 'delete';

/**
* {@inheritdoc}
*/
protected function supports($attribute, $subject)
{
// this voter is only executed for three specific permissions on Post objects
return $subject instanceof Post && in_array($attribute, [self::SHOW, self::EDIT, self::DELETE]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've simplified this method to a 1-liner to reduce the perceived complexity of voters. They have been traditionally criticized for the required boilerplate ... and thanks to the new abstract voter, it's code can be super simple.

}

/**
* {@inheritdoc}
*/
protected function voteOnAttribute($attribute, $post, TokenInterface $token)
Copy link
Member Author

@yceruto yceruto Jan 20, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This implementation can be simplified too, just one line:

return $token->getUser() === $post->getAuthor();

? because $post->getAuthor() always has an author when $token->getUser() is null this return false.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What you say is correct ... but at the same time is very common to do the if (!$user instanceof User) { return false; } thing in voters ... so we probably should keep it.

{
$user = $token->getUser();

// the user must be logged in; if not, deny permission
if (!$user instanceof User) {
return false;
}

// the logic of this voter is pretty simple: if the logged user is the
// author of the given blog post, grant permission; otherwise, deny it.
// (the supports() method guarantees that $post is a Post object)
return $user === $post->getAuthor();
}
}