Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 62 ยท Projects

Project: A Task Manager

Build a multi-user task manager in Symfony with a User entity, firewall, voters, forms and Doctrine relations, plus runnable voter and SQLite stand-ins.

A task manager looks simple, but it forces you to answer the questions every real application has to answer: who is this person, which data may they see, and how do rows relate to each other. Users own projects, projects contain tasks, and nobody should be able to read or change another person's tasks by guessing a URL.

This project walks through the design with the real Symfony code (read-only, because Symfony needs a server) and two runnable plain-PHP stand-ins: a voter with a decision manager and a role hierarchy, and a SQLite domain with relations, foreign keys and an ownership check. It builds on Security: Users and Firewalls, Authorization: Roles and Voters, Relations and Forms: Building and Rendering.

The plan

Entity Fields Relations
User email, roles, password owns many Project
Project name belongs to one User, has many Task
Task title, status, dueOn belongs to one Project
erDiagram
    USER ||--o{ PROJECT : owns
    PROJECT ||--o{ TASK : contains
    USER {
        int id
        string email
        json roles
    }
    PROJECT {
        int id
        string name
    }
    TASK {
        int id
        string title
        string status
    }

A task has no owner column of its own: it is owned through its project, so ownership is checked in one place.

Rules the application must enforce:

  • Anyone can register, but only a logged-in user can see the task pages at all.
  • You can view and edit tasks in your own projects, and delete only your own.
  • An administrator can view and edit everything, but not delete other people's tasks.

Users and the firewall

Create the user class with php bin/console make:user, which adds a User entity implementing UserInterface and PasswordAuthenticatedUserInterface plus the provider configuration. The security file then needs a firewall with a login form and one rule for the whole /app area:

YAML
# config/packages/security.yaml
security:
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'

    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email

    role_hierarchy:
        ROLE_ADMIN: ROLE_USER

    firewalls:
        main:
            lazy: true
            provider: app_user_provider
            form_login:
                login_path: app_login
                check_path: app_login
                enable_csrf: true
            logout:
                path: app_logout

    access_control:
        - { path: ^/app, roles: ROLE_USER }

access_control is a coarse gate: it only asks whether someone is logged in. It cannot know that task 17 belongs to somebody else. That question needs an object, and objects are the job of voters.

Doctrine relations

The ownership chain is User โ† Project โ† Task, each a ManyToOne seen from the child. The child is the owning side that holds the foreign key (see Relations):

PHP
<?php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\Entity]
class Task
{
    public const STATUSES = ['todo', 'doing', 'done'];

    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 120)]
    #[Assert\NotBlank, Assert\Length(max: 120)]
    private string $title = '';

    #[ORM\Column(length: 10)]
    #[Assert\Choice(choices: self::STATUSES)]
    private string $status = 'todo';

    #[ORM\Column(nullable: true)]
    private ?\DateTimeImmutable $dueOn = null;

    #[ORM\ManyToOne(inversedBy: 'tasks')]
    #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
    private ?Project $project = null;

    public function getProject(): ?Project
    {
        return $this->project;
    }

    // other getters and setters omitted
}

On Project, the inverse side is #[ORM\OneToMany(mappedBy: 'project', targetEntity: Task::class, orphanRemoval: true)], and owner is a ManyToOne to User. Remember that onDelete: 'CASCADE' is enforced by the database, while orphanRemoval and cascade are enforced by Doctrine in PHP.

Voters: who may touch this task?

A voter answers one question for one kind of subject. It receives an attribute (a verb such as TASK_EDIT), the subject and the current user, and returns grant, deny or abstain:

PHP
<?php
namespace App\Security;

use App\Entity\Task;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

/** @extends Voter<string, Task> */
final class TaskVoter extends Voter
{
    public const VIEW = 'TASK_VIEW';
    public const EDIT = 'TASK_EDIT';
    public const DELETE = 'TASK_DELETE';

    protected function supports(string $attribute, mixed $subject): bool
    {
        return $subject instanceof Task
            && in_array($attribute, [self::VIEW, self::EDIT, self::DELETE], true);
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();
        if (!$user instanceof User) {
            return false;
        }

        $isOwner = $subject->getProject()?->getOwner() === $user;

        return match ($attribute) {
            self::VIEW, self::EDIT => $isOwner || in_array('ROLE_ADMIN', $user->getRoles(), true),
            self::DELETE => $isOwner,
            default => false,
        };
    }
}

The controller then states the rule declaratively, and a failed check becomes a 403 (or a redirect to login for anonymous visitors):

PHP
<?php
namespace App\Controller;

use App\Entity\Task;
use App\Form\TaskType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/app/tasks')]
final class TaskController extends AbstractController
{
    #[Route('/{id}/edit', name: 'task_edit', requirements: ['id' => '\d+'], methods: ['GET', 'POST'])]
    #[IsGranted('TASK_EDIT', subject: 'task')]
    public function edit(Task $task, Request $request, EntityManagerInterface $em): Response
    {
        $form = $this->createForm(TaskType::class, $task);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em->flush();
            $this->addFlash('success', 'Task saved.');

            return $this->redirectToRoute('project_show', ['id' => $task->getProject()->getId()]);
        }

        return $this->render('task/edit.html.twig', ['task' => $task, 'form' => $form]);
    }
}

The same attribute works in Twig, for example {% if is_granted('TASK_DELETE', task) %} to show the delete button only to people who may use it. Hiding a button is a convenience; the controller check is the real protection. Always do both.

Run the next stand-in to see how the pieces fit: a role hierarchy, two voters that may abstain, and a decision manager with the affirmative strategy (one grant is enough, otherwise any deny means denied, and if every voter abstains the answer is denied).

PHP Voters, role hierarchy and the decision manager (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The matrix shows the three rules from the plan. The last line is the important safety property: if no voter claims to know the attribute, access is denied, so a typo in an attribute name fails closed instead of opening a hole. Real Symfony uses the same three results and, by default, the affirmative strategy.

A runnable domain with SQLite

Now the data side. The stand-in creates the three tables with real foreign keys, loads some rows and implements the queries the task pages need: the tasks of one user's projects, counts by status, and an ownership-checked "complete" action. It also shows what onDelete: 'CASCADE' does.

PHP Users, projects and tasks on SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Two things to carry back to Symfony. First, the check "is this task in one of my projects" is expressed once, near the data, which is what the voter does with getProject()->getOwner(). Second, the database still protects the structure: the foreign key refuses an orphan task (PDO throws exceptions by default since PHP 8), and ON DELETE CASCADE removes the children when a project goes away.

Finishing touches

  • Registration: a RegistrationType form with a RepeatedType password field, hashing with UserPasswordHasherInterface, and #[UniqueEntity('email')] on the entity.
  • Scoped lists: never load "all tasks" and filter in PHP. Add repository methods such as findByOwner(User $user) so the query itself contains the ownership condition.
  • Tests: a WebTestCase that logs in with $client->loginUser($bob) and asserts that /app/tasks/{aliceTaskId}/edit returns 403 (Testing with PHPUnit).
  • Fixtures: create two users and a few tasks each so these tests have data (Fixtures and Factories).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is access_control with ROLE_USER not enough to protect task 17?

    access_control works on the request (path, roles). Deciding about one specific object is the job of a voter.
  2. 2. All voters abstain for an attribute. What is the result in the decision manager?

    By default, abstaining everywhere means nobody granted access, so it is denied. A typo in an attribute name therefore fails closed.
  3. 3. In the plan, an admin may edit but not delete another user's task. Where is that rule best expressed?

    The voter receives the attribute and the object, so it can apply a different rule to TASK_EDIT and TASK_DELETE. Templates can mirror it for display, but they do not protect anything.
  4. 4. What does onDelete: 'CASCADE' on the Task's project join column do?

    It creates ON DELETE CASCADE on the foreign key, so the database itself removes the child rows. orphanRemoval and cascade are the Doctrine-side equivalents.

Summary

  • Model ownership once: User owns Project, Project contains Task; the foreign key sits on the child.
  • Use access_control for coarse rules and voters plus #[IsGranted] for per-object rules; also check in the controller, not only in the template.
  • Voters return grant, deny or abstain; if no voter grants, access is denied.
  • Put ownership conditions into repository queries so users never load other people's rows.
  • Let the database guard integrity with foreign keys and cascades.

Next, expose a similar model over HTTP in Project: A Bookstore JSON API.