Skip to content
This repository was archived by the owner on Jan 14, 2025. It is now read-only.
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
3 changes: 3 additions & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,6 @@ services:

# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones

access_token_hasher:
class: Symfony\Component\PasswordHasher\Hasher\NativePasswordHasher
36 changes: 36 additions & 0 deletions migrations/Version20241121223603.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
use Symfony\Component\PasswordHasher\Hasher\NativePasswordHasher;

final class Version20241121223603 extends AbstractMigration
{
public function getDescription(): string
{
return 'Hash access tokens';
}

public function up(Schema $schema): void
{
$accessTokenHasher = new NativePasswordHasher();
$accessTokens = $this->connection->fetchAllAssociative('SELECT id, token FROM access_token');

foreach ($accessTokens as $accessToken) {
if (str_starts_with($accessToken['token'], 'conductor-')) {
$hashedToken = $accessTokenHasher->hash($accessToken['token']);

$this->addSql('UPDATE access_token SET token = ? WHERE id = ?', [$hashedToken, $accessToken['id']]);
}
}
}

public function down(Schema $schema): void
{
$this->throwIrreversibleMigrationException();
}
}
17 changes: 14 additions & 3 deletions src/Controller/Dashboard/DashboardAccessTokenController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@
use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Orm\EntityRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
Expand All @@ -33,14 +36,21 @@ public function configureCrud(Crud $crud): Crud
{
return $crud
->setEntityLabelInSingular('Access token')
->setEntityLabelInPlural('Access tokens');
->setEntityLabelInPlural('Access tokens')
->overrideTemplate('crud/index', 'dashboard/access_token/index.html.twig');
}

public function configureActions(Actions $actions): Actions
{
return $actions
->remove(Crud::PAGE_INDEX, Action::EDIT)
->remove(Crud::PAGE_NEW, Action::SAVE_AND_ADD_ANOTHER);
}

public function configureFields(string $pageName): iterable
{
yield TextField::new('name');
yield TextField::new('token')
->onlyOnIndex();
yield DateTimeField::new('expiresAt');
}

public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
Expand All @@ -57,5 +67,6 @@ public function beforeEntityPersisted(BeforeEntityPersistedEvent $event): void
$accessToken = $event->getEntityInstance();

$accessToken->setUser($this->getUser());
$this->addFlash('access-token', $accessToken->getPlainToken());
}
}
51 changes: 31 additions & 20 deletions src/Doctrine/Entity/AccessToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,37 @@
namespace CodedMonkey\Conductor\Doctrine\Entity;

use CodedMonkey\Conductor\Doctrine\Repository\AccessTokenRepository;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping as ORM;

#[Entity(repositoryClass: AccessTokenRepository::class)]
#[ORM\Entity(repositoryClass: AccessTokenRepository::class)]
class AccessToken
{
#[Column]
#[GeneratedValue]
#[Id]
#[ORM\Column]
#[ORM\GeneratedValue]
#[ORM\Id]
private ?int $id = null;

#[ManyToOne(User::class)]
#[ORM\ManyToOne(User::class)]
private ?User $user = null;

#[Column]
#[ORM\Column]
private ?string $name = null;

#[Column]
private readonly string $token;
#[ORM\Column]
private ?string $token = null;

#[Column]
#[ORM\Column]
private readonly \DateTimeImmutable $createdAt;

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

private ?string $plainToken = null;

public function __construct()
{
$this->createdAt = new \DateTimeImmutable();
// todo generate proper hash
$this->token = uniqid('conductor-');
$this->plainToken = uniqid('conductor-');
}

public function getId(): ?int
Expand Down Expand Up @@ -64,7 +61,7 @@ public function setName(?string $name): void
$this->name = $name;
}

public function getToken(): string
public function getToken(): ?string
{
return $this->token;
}
Expand All @@ -84,9 +81,23 @@ public function setExpiresAt(?\DateTimeImmutable $expiresAt): void
$this->expiresAt = $expiresAt;
}

public function getPlainToken(): ?string
{
return $this->plainToken;
}

public function isValid(): bool
{
// todo check if expired
return true;
return !$this->expiresAt || $this->expiresAt->getTimestamp() <= time();
}

public function hashCredentials(string $token): void
{
if (null === $this->plainToken) {
throw new \LogicException('Access token was already hashed.');
}

$this->token = $token;
$this->plainToken = null;
}
}
25 changes: 11 additions & 14 deletions src/Doctrine/Entity/Credentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,32 @@

use CodedMonkey\Conductor\Doctrine\Repository\CredentialsRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping as ORM;

#[Entity(repositoryClass: CredentialsRepository::class)]
#[ORM\Entity(repositoryClass: CredentialsRepository::class)]
class Credentials
{
#[Column]
#[GeneratedValue]
#[Id]
#[ORM\Column]
#[ORM\GeneratedValue]
#[ORM\Id]
private ?int $id = null;

#[Column]
#[ORM\Column]
private ?string $name = null;

#[Column(type: Types::TEXT, nullable: true)]
#[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $description = null;

#[Column(type: Types::STRING, enumType: CredentialsType::class)]
#[ORM\Column(type: Types::STRING, enumType: CredentialsType::class)]
private CredentialsType|string $type = CredentialsType::HttpBasic;

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

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

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

public function getId(): ?int
Expand Down
30 changes: 30 additions & 0 deletions src/Doctrine/EventListener/AccessTokenListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace CodedMonkey\Conductor\Doctrine\EventListener;

use CodedMonkey\Conductor\Doctrine\Entity\AccessToken;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\ORM\Events;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\PasswordHasher\PasswordHasherInterface;

#[AsEntityListener(Events::prePersist, entity: AccessToken::class)]
readonly class AccessTokenListener
{
public function __construct(
#[Autowire(service: 'access_token_hasher')]
private PasswordHasherInterface $accessTokenHasher,
) {
}

public function prePersist(AccessToken $accessToken): void
{
$this->hashToken($accessToken);
}

private function hashToken(AccessToken $accessToken): void
{
$token = $this->accessTokenHasher->hash($accessToken->getPlainToken());
$accessToken->hashCredentials($token);
}
}
4 changes: 2 additions & 2 deletions src/Doctrine/EventListener/UserListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@

#[AsEntityListener(Events::prePersist, entity: User::class)]
#[AsEntityListener(Events::preUpdate, entity: User::class)]
class UserListener
readonly class UserListener
{
public function __construct(
private readonly UserPasswordHasherInterface $passwordHasher,
private UserPasswordHasherInterface $passwordHasher,
) {
}

Expand Down
18 changes: 10 additions & 8 deletions src/EventListener/SecurityEventListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\PasswordHasher\PasswordHasherInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
Expand All @@ -17,13 +18,15 @@
public function __construct(
private AccessTokenRepository $accessTokenRepository,
private AuthorizationCheckerInterface $authorizationChecker,
#[Autowire(service: 'access_token_hasher')]
private PasswordHasherInterface $accessTokenHasher,
#[Autowire(param: 'conductor.security.public_access')]
private bool $publicAccess,
) {
}

#[AsEventListener]
public function onKernelController(ControllerEvent $event): void
public function checkAccessIsGranted(ControllerEvent $event): void
{
if (null !== ($event->getAttributes(IsGrantedAccess::class)[0] ?? null)) {
if (!$this->publicAccess && !$this->authorizationChecker->isGranted('ROLE_USER')) {
Expand All @@ -33,7 +36,7 @@ public function onKernelController(ControllerEvent $event): void
}

#[AsEventListener]
public function onCheckPassport(CheckPassportEvent $event): void
public function checkAccessTokenIsValid(CheckPassportEvent $event): void
{
$passport = $event->getPassport();

Expand All @@ -45,16 +48,15 @@ public function onCheckPassport(CheckPassportEvent $event): void
return;
}

$accessToken = $this->accessTokenRepository->findOneBy([
$accessTokens = $this->accessTokenRepository->findBy([
'user' => $passport->getUser(),
'token' => $password,
]);

if (null === $accessToken || !$accessToken->isValid()) {
return;
foreach ($accessTokens as $accessToken) {
if ($accessToken->isValid() && $this->accessTokenHasher->verify($accessToken->getToken(), $password)) {
$passwordBadge->markResolved();
}
}

$passwordBadge->markResolved();
}
}
}
19 changes: 19 additions & 0 deletions templates/bundles/EasyAdminBundle/flash_messages.html.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{# template override to limit flash messages to Boostrap color types #}

{# @var ea \EasyCorp\Bundle\EasyAdminBundle\Provider\AdminContextProvider #}
{% trans_default_domain ea.hasContext ? ea.i18n.translationDomain : (translation_domain is defined ? translation_domain ?? 'messages') %}

{% set flash_messages = app.flashes(['primary', 'secondary', 'danger', 'info', 'success', 'warning']) %}

{% if flash_messages|length > 0 %}
<div id="flash-messages">
{% for label, messages in flash_messages %}
{% for message in messages %}
<div class="alert alert-{{ label }} alert-dismissible fade show" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
{{ message|trans|raw }}
</div>
{% endfor %}
{% endfor %}
</div>
{% endif %}
23 changes: 23 additions & 0 deletions templates/dashboard/access_token/index.html.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{% extends '@EasyAdmin/crud/index.html.twig' %}

{% block main %}
<div>
{% set flash_messages = app.flashes(['access-token']) %}

{% if flash_messages|length > 0 %}
<div id="flash-messages-main">
{% for label, messages in flash_messages %}
{% for message in messages %}
<div class="alert alert-success alert-dismissible fade show" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
Your access token: {{ message|trans|raw }}
</div>
{% endfor %}
{% endfor %}
</div>
{% endif %}
</div>

<hr>
{{ parent() }}
{% endblock %}
1 change: 1 addition & 0 deletions translations/messages.en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Current password: Current password
Description: Description
Dynamic Update Delay: Dynamic Update Delay
Email: Email
Expires At: Expires at
New password: New password
Name: Name
Package Mirroring: Package Mirroring
Expand Down