Add basic auth

This commit is contained in:
myrmidex 2026-06-02 22:26:03 +00:00
parent 4ce856198a
commit cc213bfb15
9 changed files with 355 additions and 4 deletions

View file

@ -5,7 +5,11 @@ security:
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers:
users_in_memory: { memory: null }
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
@ -14,7 +18,7 @@ security:
security: false
main:
lazy: true
provider: users_in_memory
provider: app_user_provider
# Activate different ways to authenticate:
# https://symfony.com/doc/current/security.html#the-firewall

View file

@ -0,0 +1,32 @@
<?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 Version20260602214533 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 TABLE "user" (id INT GENERATED BY DEFAULT AS IDENTITY 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_IDENTIFIER_EMAIL ON "user" (email)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('DROP TABLE "user"');
}
}

View file

@ -0,0 +1,68 @@
<?php
namespace App\Controller;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class AccountController extends AbstractController
{
#[Route('/account/login')]
public function login(AuthenticationUtils $authUtils): Response
{
$error = $authUtils->getLastAuthenticationError();
$lastUsername = $authUtils->getLastUsername();
return $this->render('account/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
#[Route('/account/register')]
public function register(
Request $request,
UserPasswordHasherInterface $passwordHasher,
EntityManagerInterface $em,
): Response {
$user = new User();
$form = $this->createFormBuilder($user)
->add('email', EmailType::class)
->add('password', PasswordType::class)
->add('password_again', PasswordType::class, [
'mapped' => false,
])
->add('register', SubmitType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$plaintextPassword = $form->get('password')->getData();
$hashedPassword = $passwordHasher->hashPassword(
$user,
$plaintextPassword
);
$user->setPassword($hashedPassword);
$em->persist($user);
$em->flush();
return $this->redirectToRoute('app_account_login');
}
return $this->render('account/register.html.twig', [
'form' => $form,
]);
}
}

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

@ -0,0 +1,109 @@
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: '`user`')]
#[ORM\UniqueConstraint(name: 'UNIQ_IDENTIFIER_EMAIL', fields: ['email'])]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 180)]
private ?string $email = null;
/**
* @var list<string> The user roles
*/
#[ORM\Column]
private array $roles = [];
/**
* @var string The hashed password
*/
#[ORM\Column]
private ?string $password = null;
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): static
{
$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);
}
/**
* @param list<string> $roles
*/
public function setRoles(array $roles): static
{
$this->roles = $roles;
return $this;
}
/**
* @see PasswordAuthenticatedUserInterface
*/
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): static
{
$this->password = $password;
return $this;
}
/**
* Ensure the session doesn't contain actual password hashes by CRC32C-hashing them, as supported since Symfony 7.3.
*/
public function __serialize(): array
{
$data = (array) $this;
$data["\0" . self::class . "\0password"] = hash('crc32c', $this->password);
return $data;
}
}

View file

@ -0,0 +1,60 @@
<?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>
*/
class UserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
/**
* 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.', $user::class));
}
$user->setPassword($newHashedPassword);
$this->getEntityManager()->persist($user);
$this->getEntityManager()->flush();
}
// /**
// * @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

@ -0,0 +1,10 @@
<html>
<head>
<title>Rater Login</title>
</head>
<body>
body
{{ form(form) }}
</body>
</html>

View file

@ -0,0 +1,34 @@
<?php
namespace App\Tests\Integration\Auth;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class LoginTest extends WebTestCase
{
public function testAddingNewSubject(): void
{
$client = static::createClient();
$faker = \Zenstruck\Foundry\faker();
$email = $faker->email();
$plainPwd = $faker->word(8);
$client->request('GET', '/account/register');
$client->submitForm('form_register', [
'form[email]' => $email,
'form[password]' => $plainPwd,
'form[password_again]' => $plainPwd,
]);
$this->assertResponseRedirects();
$subject = static::getContainer()
->get(UserRepository::class)
->findOneBy(['email' => $email]);
$this->assertNotNull($subject);
}
}

View file

@ -0,0 +1,34 @@
<?php
namespace App\Tests\Integration\Auth;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class RegistrationControllerTest extends WebTestCase
{
public function testAddingNewSubject(): void
{
$client = static::createClient();
$faker = \Zenstruck\Foundry\faker();
$email = $faker->email();
$plainPwd = $faker->word(8);
$client->request('GET', '/account/register');
$client->submitForm('form_register', [
'form[email]' => $email,
'form[password]' => $plainPwd,
'form[password_again]' => $plainPwd,
]);
$this->assertResponseRedirects();
$subject = static::getContainer()
->get(UserRepository::class)
->findOneBy(['email' => $email]);
$this->assertNotNull($subject);
}
}

View file

@ -1,13 +1,13 @@
<?php
namespace App\Tests\Integration\Controller;
namespace App\Tests\Integration\Subject;
use App\Entity\Restaurant;
use App\Factory\RestaurantFactory;
use App\Repository\SubjectRepository;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class SubjectControllerTest extends WebTestCase
class AddSubjectTest extends WebTestCase
{
public function testSubjectList(): void
{