This commit is contained in:
2024-07-03 14:03:50 +02:00
parent a2f2520617
commit dad0d86e8c
15 changed files with 377 additions and 4 deletions

View File

@@ -8,6 +8,7 @@ use App\Entity\Conference;
use App\Form\CommentType;
use App\Repository\CommentRepository;
use App\Repository\ConferenceRepository;
use App\SpamChecker;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
@@ -35,6 +36,7 @@ class ConferenceController extends AbstractController
Request $request,
Conference $conference,
CommentRepository $commentRepository,
SpamChecker $spamChecker,
ConferenceRepository $conferenceRepository,
#[Autowire('%photo_dir%')] string $photoDir,
): Response {
@@ -50,6 +52,15 @@ class ConferenceController extends AbstractController
$comment->setPhotoFilename($filename);
}
$this->entityManager->persist($comment);
$context = [
'user_ip' => $request->getClientIp(),
'user_agent' => $request->headers->get('user-agent'),
'referrer' => $request->headers->get('referer'),
'permalink' => $request->getUri(),
];
if (2 === $spamChecker->getSpamScore($comment, $context)) {
throw new \RuntimeException('Blatant spam, go away!');
}
$this->entityManager->flush();
return $this->redirectToRoute('conference', ['slug' => $conference->getSlug()]);

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
#[Route(path: '/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
#[Route(path: '/logout', name: 'app_logout')]
public function logout(): void
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
}

108
src/Entity/Admin.php Normal file
View File

@@ -0,0 +1,108 @@
<?php
namespace App\Entity;
use App\Repository\AdminRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: AdminRepository::class)]
#[ORM\UniqueConstraint(name: 'UNIQ_IDENTIFIER_USERNAME', fields: ['username'])]
class Admin implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 180)]
private ?string $username = 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 getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): static
{
$this->username = $username;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->username;
}
/**
* @see UserInterface
*
* @return list<string>
*/
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;
}
/**
* @see UserInterface
*/
public function eraseCredentials(): void
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace App\Repository;
use App\Entity\Admin;
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<Admin>
*/
class AdminRepository extends ServiceEntityRepository implements PasswordUpgraderInterface
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Admin::class);
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*/
public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
{
if (!$user instanceof Admin) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $user::class));
}
$user->setPassword($newHashedPassword);
$this->getEntityManager()->persist($user);
$this->getEntityManager()->flush();
}
// /**
// * @return Admin[] Returns an array of Admin objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('a')
// ->andWhere('a.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('a.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Admin
// {
// return $this->createQueryBuilder('a')
// ->andWhere('a.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}

53
src/SpamChecker.php Normal file
View File

@@ -0,0 +1,53 @@
<?php
namespace App;
use App\Entity\Comment;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class SpamChecker
{
private $endpoint;
public function __construct(
private HttpClientInterface $client,
#[Autowire('%env(AKISMET_KEY)%')] string $akismetKey,
) {
$this->endpoint = sprintf('https://%s.rest.akismet.com/1.1/comment-check', $akismetKey);
}
/**
* @return int Spam score: 0: not spam, 1: maybe spam, 2: blatant spam
*
* @throws \RuntimeException if the call did not work
*/
public function getSpamScore(Comment $comment, array $context): int
{
$response = $this->client->request('POST', $this->endpoint, [
'body' => array_merge($context, [
'blog' => 'https://guestbook.example.com',
'comment_type' => 'comment',
'comment_author' => $comment->getAuthor(),
'comment_author_email' => $comment->getEmail(),
'comment_content' => $comment->getText(),
'comment_date_gmt' => $comment->getCreatedAt()->format('c'),
'blog_lang' => 'en',
'blog_charset' => 'UTF-8',
'is_test' => true,
]),
]);
$headers = $response->getHeaders();
if ('discard' === ($headers['x-akismet-pro-tip'][0] ?? '')) {
return 2;
}
$content = $response->getContent();
if (isset($headers['x-akismet-debug-help'][0])) {
throw new \RuntimeException(sprintf('Unable to check for spam: %s (%s).', $content, $headers['x-akismet-debug-help'][0]));
}
return 'true' === $content ? 1 : 0;
}
}