Soft-delete users instead of hard-deleting, add last login tracking

Fixes the 500 on admin user deletion: deleting a user with an
email_log row (i.e. basically anyone who received any email) hit an
unhandled ForeignKeyConstraintViolationException, since email_log,
reset_password_request and player all have non-nullable FKs to user
with no cascade at the DB level.

Instead of cascading the delete (which would be fine for email_log
and reset_password_request but risky for player - removing a player
row could corrupt other real players' session state), admin delete
now sets a deletedAt timestamp instead of removing the row:
- UserChecker blocks login for deleted users (checkPreAuth).
- EmailLoggerListener rejects the message before send for deleted
  recipients (checked at actual send time, not at queue time).
- Added a last_login_at column + a LoginSuccessEvent listener to
  populate it, and surfaced both last login and status in the admin
  users list.

Added `app:users:purge-deleted`, a command intended to run on a
schedule that permanently removes users who were soft-deleted more
than 3 months ago and never played a game (join to Player via a
NOT EXISTS subquery). For that eventual hard-delete to actually
succeed, email_log and reset_password_request now cascade-delete at
the DB level (migration drops+recreates both FK constraints with ON
DELETE CASCADE) - player intentionally still isn't cascaded, so a
user with game history can never be purged this way even by mistake.
This commit is contained in:
Frank
2026-07-11 23:09:52 +02:00
parent 3a7bc3ed49
commit 3c58e153dc
11 changed files with 188 additions and 8 deletions
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260711210000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add deleted_at and last_login_at to user table; cascade-delete email_log and reset_password_request rows';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE `user` ADD deleted_at DATETIME DEFAULT NULL, ADD last_login_at DATETIME DEFAULT NULL');
$this->addSql('ALTER TABLE email_log DROP FOREIGN KEY FK_6FB4883A76ED395');
$this->addSql('ALTER TABLE email_log ADD CONSTRAINT FK_6FB4883A76ED395 FOREIGN KEY (user_id) REFERENCES `user` (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE reset_password_request DROP FOREIGN KEY FK_7CE748AA76ED395');
$this->addSql('ALTER TABLE reset_password_request ADD CONSTRAINT FK_7CE748AA76ED395 FOREIGN KEY (user_id) REFERENCES `user` (id) ON DELETE CASCADE');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE email_log DROP FOREIGN KEY FK_6FB4883A76ED395');
$this->addSql('ALTER TABLE email_log ADD CONSTRAINT FK_6FB4883A76ED395 FOREIGN KEY (user_id) REFERENCES `user` (id)');
$this->addSql('ALTER TABLE reset_password_request DROP FOREIGN KEY FK_7CE748AA76ED395');
$this->addSql('ALTER TABLE reset_password_request ADD CONSTRAINT FK_7CE748AA76ED395 FOREIGN KEY (user_id) REFERENCES `user` (id)');
$this->addSql('ALTER TABLE `user` DROP deleted_at, DROP last_login_at');
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Command;
use App\Tech\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(
name: 'app:users:purge-deleted',
description: 'Permanently removes soft-deleted users who never played a game, 3 months after deletion.'
)]
final class PurgeDeletedUsersCommand extends Command
{
public function __construct(
private readonly UserRepository $userRepository,
private readonly EntityManagerInterface $entityManager,
) {
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$deletedBefore = new \DateTimeImmutable('-3 months');
$users = $this->userRepository->findPurgeableDeletedUsers($deletedBefore);
foreach ($users as $user) {
$this->entityManager->remove($user);
}
$this->entityManager->flush();
$output->writeln(sprintf('<info>Purged %d deleted user(s).</info>', count($users)));
return Command::SUCCESS;
}
}
@@ -66,11 +66,12 @@ final class GameAdminUserController extends AbstractController
return $this->redirectToRoute('game_admin_users'); return $this->redirectToRoute('game_admin_users');
} }
$username = $user->getUsername(); if (!$user->isDeleted()) {
$em->remove($user); $user->setDeletedAt(new \DateTimeImmutable());
$em->flush(); $em->flush();
}
$this->addFlash('success', sprintf('User "%s" deleted.', $username)); $this->addFlash('success', sprintf('User "%s" deleted.', $user->getUsername()));
return $this->redirectToRoute('game_admin_users'); return $this->redirectToRoute('game_admin_users');
} }
+1 -1
View File
@@ -16,7 +16,7 @@ class EmailLog
private ?int $id = null; private ?int $id = null;
#[ORM\ManyToOne(targetEntity: User::class)] #[ORM\ManyToOne(targetEntity: User::class)]
#[ORM\JoinColumn(nullable: false)] #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
private ?User $user = null; private ?User $user = null;
#[ORM\Column(length: 255)] #[ORM\Column(length: 255)]
+1 -1
View File
@@ -19,7 +19,7 @@ class ResetPasswordRequest implements ResetPasswordRequestInterface
private ?int $id = null; private ?int $id = null;
#[ORM\ManyToOne] #[ORM\ManyToOne]
#[ORM\JoinColumn(nullable: false)] #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
private ?User $user = null; private ?User $user = null;
public function __construct(User $user, \DateTimeInterface $expiresAt, string $selector, string $hashedToken) public function __construct(User $user, \DateTimeInterface $expiresAt, string $selector, string $hashedToken)
+35
View File
@@ -42,6 +42,12 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
#[ORM\Column(type: 'boolean')] #[ORM\Column(type: 'boolean')]
private bool $marketingOptIn = false; private bool $marketingOptIn = false;
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
private ?\DateTimeImmutable $deletedAt = null;
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
private ?\DateTimeImmutable $lastLoginAt = null;
public function getId(): ?int public function getId(): ?int
{ {
return $this->id; return $this->id;
@@ -152,4 +158,33 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
return $this; return $this;
} }
public function getDeletedAt(): ?\DateTimeImmutable
{
return $this->deletedAt;
}
public function setDeletedAt(?\DateTimeImmutable $deletedAt): static
{
$this->deletedAt = $deletedAt;
return $this;
}
public function isDeleted(): bool
{
return $this->deletedAt !== null;
}
public function getLastLoginAt(): ?\DateTimeImmutable
{
return $this->lastLoginAt;
}
public function setLastLoginAt(?\DateTimeImmutable $lastLoginAt): static
{
$this->lastLoginAt = $lastLoginAt;
return $this;
}
} }
@@ -42,6 +42,11 @@ class EmailLoggerListener
continue; continue;
} }
if ($user->isDeleted()) {
$event->reject();
return;
}
$emailLog = new EmailLog(); $emailLog = new EmailLog();
$emailLog->setUser($user); $emailLog->setUser($user);
$emailLog->setSentAt(new \DateTimeImmutable()); $emailLog->setSentAt(new \DateTimeImmutable());
@@ -0,0 +1,28 @@
<?php
namespace App\Tech\EventListener;
use App\Tech\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
#[AsEventListener(event: LoginSuccessEvent::class, method: 'onLoginSuccess')]
class LastLoginListener
{
public function __construct(
private EntityManagerInterface $entityManager,
) {
}
public function onLoginSuccess(LoginSuccessEvent $event): void
{
$user = $event->getUser();
if (!$user instanceof User) {
return;
}
$user->setLastLoginAt(new \DateTimeImmutable());
$this->entityManager->flush();
}
}
+16
View File
@@ -44,4 +44,20 @@ class UserRepository extends ServiceEntityRepository implements PasswordUpgrader
->getQuery() ->getQuery()
->getResult(); ->getResult();
} }
/**
* Soft-deleted users, deleted before the given date, who never played a game.
*
* @return User[]
*/
public function findPurgeableDeletedUsers(\DateTimeImmutable $deletedBefore): array
{
return $this->createQueryBuilder('u')
->andWhere('u.deletedAt IS NOT NULL')
->andWhere('u.deletedAt <= :deletedBefore')
->andWhere('NOT EXISTS (SELECT 1 FROM App\Game\Entity\Player p WHERE p.user = u)')
->setParameter('deletedBefore', $deletedBefore)
->getQuery()
->getResult();
}
} }
+4
View File
@@ -16,6 +16,10 @@ class UserChecker implements UserCheckerInterface
return; return;
} }
if ($user->isDeleted()) {
throw new CustomUserMessageAuthenticationException('This account no longer exists.');
}
if (!$user->isVerified()) { if (!$user->isVerified()) {
throw new CustomUserMessageAuthenticationException('Your email address is not verified.', ['%resend_link%' => '/verify/resend']); throw new CustomUserMessageAuthenticationException('Your email address is not verified.', ['%resend_link%' => '/verify/resend']);
} }
+14 -2
View File
@@ -18,6 +18,8 @@
<th style="padding: 0.75rem 1rem; text-align: left; color: #475569; font-weight: 600;">Roles</th> <th style="padding: 0.75rem 1rem; text-align: left; color: #475569; font-weight: 600;">Roles</th>
<th style="padding: 0.75rem 1rem; text-align: left; color: #475569; font-weight: 600;">Verified</th> <th style="padding: 0.75rem 1rem; text-align: left; color: #475569; font-weight: 600;">Verified</th>
<th style="padding: 0.75rem 1rem; text-align: left; color: #475569; font-weight: 600;">Marketing</th> <th style="padding: 0.75rem 1rem; text-align: left; color: #475569; font-weight: 600;">Marketing</th>
<th style="padding: 0.75rem 1rem; text-align: left; color: #475569; font-weight: 600;">Last Login</th>
<th style="padding: 0.75rem 1rem; text-align: left; color: #475569; font-weight: 600;">Status</th>
<th style="padding: 0.75rem 1rem; text-align: left; color: #475569; font-weight: 600;">Actions</th> <th style="padding: 0.75rem 1rem; text-align: left; color: #475569; font-weight: 600;">Actions</th>
</tr> </tr>
</thead> </thead>
@@ -57,6 +59,16 @@
<span style="color: #dc2626;">✗ No</span> <span style="color: #dc2626;">✗ No</span>
{% endif %} {% endif %}
</td> </td>
<td style="padding: 0.75rem 1rem; color: #475569;">
{{ user.lastLoginAt ? user.lastLoginAt|date('Y-m-d H:i') : 'Never' }}
</td>
<td style="padding: 0.75rem 1rem;">
{% if user.deleted %}
<span style="color: #dc2626; font-weight: 500;">Deleted</span>
{% else %}
<span style="color: #16a34a; font-weight: 500;">Active</span>
{% endif %}
</td>
<td style="padding: 0.75rem 1rem;"> <td style="padding: 0.75rem 1rem;">
<a href="{{ path('game_admin_user_edit', {id: user.id}) }}" style=" <a href="{{ path('game_admin_user_edit', {id: user.id}) }}" style="
color: #3b82f6; color: #3b82f6;
@@ -65,7 +77,7 @@
margin-right: 0.75rem; margin-right: 0.75rem;
">Edit</a> ">Edit</a>
{% if user != app.user %} {% if user != app.user and not user.deleted %}
<form method="post" action="{{ path('game_admin_user_delete', {id: user.id}) }}" style="display: inline;" onsubmit="return confirm('Delete user {{ user.username }}?')"> <form method="post" action="{{ path('game_admin_user_delete', {id: user.id}) }}" style="display: inline;" onsubmit="return confirm('Delete user {{ user.username }}?')">
<input type="hidden" name="_token" value="{{ csrf_token('delete_user_' ~ user.id) }}"> <input type="hidden" name="_token" value="{{ csrf_token('delete_user_' ~ user.id) }}">
<button type="submit" style=" <button type="submit" style="
@@ -82,7 +94,7 @@
</tr> </tr>
{% else %} {% else %}
<tr> <tr>
<td colspan="7" style="padding: 2rem; text-align: center; color: #94a3b8;">No users found.</td> <td colspan="9" style="padding: 2rem; text-align: center; color: #94a3b8;">No users found.</td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>