Add security

1. Users
2. Login/logout controllers
3. Podcasts can have an owner to restrict their access in the backoffice
This commit is contained in:
dece 2023-09-09 22:48:14 +02:00
parent cccbdf8960
commit e3d80d1093
16 changed files with 442 additions and 22 deletions

2
.env
View file

@ -26,7 +26,7 @@ APP_SECRET=c798512b7c48614d5278e8e47bb556ce
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
# DATABASE_URL="mysql://app:!ChangeMe!@127.0.0.1:3306/app?serverVersion=8.0.32&charset=utf8mb4"
# DATABASE_URL="mysql://app:!ChangeMe!@127.0.0.1:3306/app?serverVersion=10.11.2-MariaDB&charset=utf8mb4"
DATABASE_URL="postgresql://lsbc:dev@127.0.0.1:5432/lsbc?serverVersion=15&charset=utf8"
DATABASE_URL="postgresql://dev:dev@127.0.0.1:5432/lsbc?serverVersion=15&charset=utf8"
###< doctrine/doctrine-bundle ###
###> symfony/messenger ###

View file

@ -1,6 +1,8 @@
LSBC
====
> Lightweight Symfony Broadcast Client, probably.
A small platform to create podcasts and episodes, host the audio files and share
the RSS feed, with external sources download abilities.
@ -11,7 +13,7 @@ Install
This project requires:
- PHP 8
- PHP 8.2
- PostgreSQL 15 and its PHP driver
For production:

View file

@ -4,34 +4,32 @@ security:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers:
users_in_memory: { memory: null }
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: users_in_memory
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#the-firewall
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
provider: app_user_provider
form_login:
login_path: app_login
check_path: app_login
enable_csrf: true
logout:
path: app_logout
target: app_index
role_hierarchy:
ROLE_ADMIN: ROLE_USER
access_control:
# - { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }
- { path: ^/admin, roles: ROLE_USER }
when@test:
security:
password_hashers:
# By default, password hashers are resource intensive and take time. This is
# important to generate secure password hashes. In tests however, secure hashes
# are not important, waste resources and increase test times. The following
# reduces the work factor to the lowest possible values.
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: auto
cost: 4 # Lowest possible value for bcrypt

View file

@ -3,3 +3,7 @@ controllers:
path: ../src/Controller/
namespace: App\Controller
type: attribute
app_logout:
path: /logout
methods: GET

View file

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20230909134846 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SEQUENCE "user_id_seq" INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE "user" (id INT NOT NULL, email VARCHAR(180) NOT NULL, roles JSON NOT NULL, password VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE UNIQUE INDEX UNIQ_8D93D649E7927C74 ON "user" (email)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('DROP SEQUENCE "user_id_seq" CASCADE');
$this->addSql('DROP TABLE "user"');
}
}

View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20230909202203 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE podcast ADD owner_id INT');
$this->addSql('ALTER TABLE podcast ADD CONSTRAINT FK_D7E805BD7E3C61F9 FOREIGN KEY (owner_id) REFERENCES "user" (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('CREATE INDEX IDX_D7E805BD7E3C61F9 ON podcast (owner_id)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('ALTER TABLE podcast DROP CONSTRAINT FK_D7E805BD7E3C61F9');
$this->addSql('DROP INDEX IDX_D7E805BD7E3C61F9');
$this->addSql('ALTER TABLE podcast DROP owner_id');
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace App\Command;
use App\Repository\PodcastRepository;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'app:own-orphan-podcasts',
description: 'Set the owner of all orphaned podcasts to the user with this user ID.',
)]
class OwnOrphanPodcastsCommand extends Command
{
public function __construct(
protected UserRepository $userRepository,
protected PodcastRepository $podcastRepository,
protected EntityManagerInterface $entityManager,
) {
parent::__construct();
}
protected function configure(): void
{
$this->addArgument('id', InputArgument::REQUIRED, 'Owner ID');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$userId = $input->getArgument('id');
$user = $this->userRepository->find($userId);
if ($user === null) {
$io->error("No user with ID $userId.");
return Command::FAILURE;
}
$orphanPodcasts = $this->podcastRepository->findBy(['owner' => null]);
foreach ($orphanPodcasts as $podcast) {
$podcast->setOwner($user);
$this->entityManager->persist($podcast);
}
$this->entityManager->flush();
$io->success('Orphan podcasts successfully updated.');
return Command::SUCCESS;
}
}

View file

@ -22,7 +22,6 @@ class PodcastCrudController extends AbstractCrudController
{
return [
TextField::new('name'),
TextField::new('slug'),
UrlField::new('website'),
TextEditorField::new('description'),
TextField::new('author'),

View file

@ -0,0 +1,23 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class LoginController extends AbstractController
{
#[Route('/login', name: 'app_login')]
public function index(AuthenticationUtils $authUtils): Response
{
$error = $authUtils->getLastAuthenticationError();
$lastUsername = $authUtils->getLastUsername();
return $this->render('login/index.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
}

View file

@ -44,6 +44,10 @@ class Podcast
#[ORM\Column(length: 255, nullable: true)]
private ?string $logoFilename;
#[ORM\ManyToOne(inversedBy: 'podcasts')]
#[ORM\JoinColumn(nullable: true)]
private ?User $owner = null;
public function __construct()
{
$this->episodes = new ArrayCollection();
@ -177,4 +181,16 @@ class Podcast
return $this;
}
public function getOwner(): ?User
{
return $this->owner;
}
public function setOwner(?User $owner): static
{
$this->owner = $owner;
return $this;
}
}

142
src/Entity/User.php Normal file
View file

@ -0,0 +1,142 @@
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: '`user`')]
#[UniqueEntity(fields: ['email'], message: 'There is already an account with this email')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 180, unique: true)]
private ?string $email = null;
#[ORM\Column]
private array $roles = [];
/**
* @var string The hashed password
*/
#[ORM\Column]
private ?string $password = null;
#[ORM\OneToMany(mappedBy: 'owner', targetEntity: Podcast::class)]
private Collection $podcasts;
public function __construct()
{
$this->podcasts = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
/**
* @return Collection<int, Podcast>
*/
public function getPodcasts(): Collection
{
return $this->podcasts;
}
public function addPodcast(Podcast $podcast): static
{
if (!$this->podcasts->contains($podcast)) {
$this->podcasts->add($podcast);
$podcast->setOwner($this);
}
return $this;
}
public function removePodcast(Podcast $podcast): static
{
if ($this->podcasts->removeElement($podcast)) {
// set the owning side to null (unless already changed)
if ($podcast->getOwner() === $this) {
$podcast->setOwner(null);
}
}
return $this;
}
}

View file

@ -0,0 +1,83 @@
<?php
namespace App\Repository;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
/**
* @extends ServiceEntityRepository<User>
*
* @method User|null find($id, $lockMode = null, $lockVersion = null)
* @method User|null findOneBy(array $criteria, array $orderBy = null)
* @method User[] findAll()
* @method User[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class UserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
public function save(User $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(User $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*/
public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
{
if (!$user instanceof User) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));
}
$user->setPassword($newHashedPassword);
$this->save($user, true);
}
// /**
// * @return User[] Returns an array of User objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('u')
// ->andWhere('u.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('u.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?User
// {
// return $this->createQueryBuilder('u')
// ->andWhere('u.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}

View file

@ -4,7 +4,6 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}LSBC{% endblock %}</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text></svg>">
{# Run `composer require symfony/webpack-encore-bundle` to start using Symfony UX #}
{% block stylesheets %}
<style>

View file

@ -4,7 +4,8 @@
<p>Podcasts available on this LSBC instance:</p>
<ul>
{% for podcast in podcasts %}
<li><a href="{{ path('app_podcast', {slug: podcast.slug}) }}">{{ podcast.name }}</a></li>
<li><a href="{{ path('app_podcast', { slug: podcast.slug }) }}">{{ podcast.name }}</a></li>
{% endfor %}
</ul>
<p>The <a href="https://git.dece.space/dece/lsbc">LSBC</a> project is licensed as GPLv3.</p>
{% endblock %}

View file

@ -1,5 +1,7 @@
{% extends 'base.html.twig' %}
{% block body %}{{ podcast.name }}{% endblock %}
{% block body %}
<h1>{{ podcast.name }}</h1>
<p>

View file

@ -0,0 +1,25 @@
{% extends 'base.html.twig' %}
{% block title %}Login{% endblock %}
{% block body %}
<h1>Login</h1>
{% if error %}
<p>{{ error.messageKey|trans(error.messageData, 'security') }}</p>
{% endif %}
<form action="{{ path('app_login') }}" method="post">
<label for="username">Email:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}">
<label for="password">Password:</label>
<input type="password" id="password" name="_password">
{# If you want to control the URL the user is redirected to on success
<input type="hidden" name="_target_path" value="/account"> #}
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
<button type="submit">Login</button>
</form>
{% endblock %}