jun 3
This commit is contained in:
2
.env
2
.env
@@ -14,6 +14,8 @@
|
||||
# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2).
|
||||
# https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration
|
||||
|
||||
AKISMET_KEY=f7aadd74d13f
|
||||
|
||||
###> symfony/framework-bundle ###
|
||||
APP_ENV=dev
|
||||
APP_SECRET=cf9b8a37ccaf3e584b1bbb006b79af57
|
||||
|
||||
@@ -35,6 +35,7 @@ web:
|
||||
|
||||
mounts:
|
||||
"/var": { source: local, source_path: var }
|
||||
"/public/uploads": { source: local, source_path: uploads }
|
||||
|
||||
|
||||
relationships:
|
||||
|
||||
@@ -4,14 +4,26 @@ 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 }
|
||||
# used to reload user from session & other features (e.g. switch_user)
|
||||
app_user_provider:
|
||||
entity:
|
||||
class: App\Entity\Admin
|
||||
property: username
|
||||
firewalls:
|
||||
dev:
|
||||
pattern: ^/(_(profiler|wdt)|css|images|js)/
|
||||
security: false
|
||||
main:
|
||||
lazy: true
|
||||
provider: users_in_memory
|
||||
provider: app_user_provider
|
||||
form_login:
|
||||
login_path: app_login
|
||||
check_path: app_login
|
||||
enable_csrf: true
|
||||
logout:
|
||||
path: app_logout
|
||||
# where to redirect after logout
|
||||
# target: app_any_route
|
||||
|
||||
# activate different ways to authenticate
|
||||
# https://symfony.com/doc/current/security.html#the-firewall
|
||||
@@ -22,8 +34,8 @@ security:
|
||||
# Easy way to control access for large sections of your site
|
||||
# Note: Only the *first* access control that matches will be used
|
||||
access_control:
|
||||
# - { path: ^/admin, roles: ROLE_ADMIN }
|
||||
# - { path: ^/profile, roles: ROLE_USER }
|
||||
- { path: ^/admin, roles: ROLE_ADMIN }
|
||||
# - { path: ^/profile, roles: ROLE_USER }
|
||||
|
||||
when@test:
|
||||
security:
|
||||
|
||||
3
config/secrets/dev/dev.AKISMET_KEY.ca01fb.php
Normal file
3
config/secrets/dev/dev.AKISMET_KEY.ca01fb.php
Normal file
@@ -0,0 +1,3 @@
|
||||
<?php // dev.AKISMET_KEY.ca01fb on Wed, 03 Jul 2024 11:59:32 +0000
|
||||
|
||||
return "\xB98\x05Hk\x3B\xA0\xD6\x02\x7Cj\x9F\xF0\x2Am\xEF\x22\x8F\x29\xF7C\x95\x85\x3B\xE2\xC6\xFC~\x0C\x8D\xDDZ\x9A\xDE\xCF\x86\xF5\xBFZ\xD2\x5C\xC0\x09fK\xD8\xDD\xB3\x8F\x81\x0B\x9D\xFC\x8C\x1BZ\x8F\xB3\x83\x1B";
|
||||
4
config/secrets/dev/dev.decrypt.private.php
Normal file
4
config/secrets/dev/dev.decrypt.private.php
Normal file
@@ -0,0 +1,4 @@
|
||||
<?php // dev.decrypt.private on Wed, 03 Jul 2024 11:59:32 +0000
|
||||
|
||||
// SYMFONY_DECRYPTION_SECRET=DvrLXH7erqdZVC2zbEww19XKYO0wZhwhjp0jcHYgouhbYEZHdK9I4Q8GVHLnKKe5YS2dYBHKFniktsfjrKOXcA==
|
||||
return "\x0E\xFA\xCB\x5C~\xDE\xAE\xA7YT-\xB3lL0\xD7\xD5\xCA\x60\xED0f\x1C\x21\x8E\x9D\x23pv\x20\xA2\xE8\x5B\x60FGt\xAFH\xE1\x0F\x06Tr\xE7\x28\xA7\xB9a-\x9D\x60\x11\xCA\x16x\xA4\xB6\xC7\xE3\xAC\xA3\x97p";
|
||||
3
config/secrets/dev/dev.encrypt.public.php
Normal file
3
config/secrets/dev/dev.encrypt.public.php
Normal file
@@ -0,0 +1,3 @@
|
||||
<?php // dev.encrypt.public on Wed, 03 Jul 2024 11:59:32 +0000
|
||||
|
||||
return "\x5B\x60FGt\xAFH\xE1\x0F\x06Tr\xE7\x28\xA7\xB9a-\x9D\x60\x11\xCA\x16x\xA4\xB6\xC7\xE3\xAC\xA3\x97p";
|
||||
5
config/secrets/dev/dev.list.php
Normal file
5
config/secrets/dev/dev.list.php
Normal file
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'AKISMET_KEY' => null,
|
||||
];
|
||||
3
config/secrets/prod/prod.encrypt.public.php
Normal file
3
config/secrets/prod/prod.encrypt.public.php
Normal file
@@ -0,0 +1,3 @@
|
||||
<?php // prod.encrypt.public on Wed, 03 Jul 2024 12:03:06 +0000
|
||||
|
||||
return "G\x26\xF8\x25\xABd\x84\x3AbWM2\xE9\x0D\x2C\x02\xCA\xD2\xAEV\x82\xA1\x3E\xBF\xC3gv7q\xBAQ.";
|
||||
35
migrations/Version20240703113708.php
Normal file
35
migrations/Version20240703113708.php
Normal 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 Version20240703113708 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 admin_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE TABLE admin (id INT NOT NULL, username VARCHAR(180) NOT NULL, roles JSON NOT NULL, password VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
|
||||
$this->addSql('CREATE UNIQUE INDEX UNIQ_IDENTIFIER_USERNAME ON admin (username)');
|
||||
}
|
||||
|
||||
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 admin_id_seq CASCADE');
|
||||
$this->addSql('DROP TABLE admin');
|
||||
}
|
||||
}
|
||||
@@ -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()]);
|
||||
|
||||
32
src/Controller/SecurityController.php
Normal file
32
src/Controller/SecurityController.php
Normal 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
108
src/Entity/Admin.php
Normal 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;
|
||||
}
|
||||
}
|
||||
60
src/Repository/AdminRepository.php
Normal file
60
src/Repository/AdminRepository.php
Normal 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
53
src/SpamChecker.php
Normal 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;
|
||||
}
|
||||
}
|
||||
41
templates/security/login.html.twig
Normal file
41
templates/security/login.html.twig
Normal file
@@ -0,0 +1,41 @@
|
||||
{% extends 'base.html.twig' %}
|
||||
|
||||
{% block title %}Log in!{% endblock %}
|
||||
|
||||
{% block body %}
|
||||
<form method="post">
|
||||
{% if error %}
|
||||
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
|
||||
{% endif %}
|
||||
|
||||
{% if app.user %}
|
||||
<div class="mb-3">
|
||||
You are logged in as {{ app.user.userIdentifier }}, <a href="{{ path('app_logout') }}">Logout</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
|
||||
<label for="username">Username</label>
|
||||
<input type="text" value="{{ last_username }}" name="_username" id="username" class="form-control" autocomplete="username" required autofocus>
|
||||
<label for="password">Password</label>
|
||||
<input type="password" name="_password" id="password" class="form-control" autocomplete="current-password" required>
|
||||
|
||||
<input type="hidden" name="_csrf_token"
|
||||
value="{{ csrf_token('authenticate') }}"
|
||||
>
|
||||
|
||||
{#
|
||||
Uncomment this section and add a remember_me option below your firewall to activate remember me functionality.
|
||||
See https://symfony.com/doc/current/security/remember_me.html
|
||||
|
||||
<div class="checkbox mb-3">
|
||||
<input type="checkbox" name="_remember_me" id="_remember_me">
|
||||
<label for="_remember_me">Remember me</label>
|
||||
</div>
|
||||
#}
|
||||
|
||||
<button class="btn btn-lg btn-primary" type="submit">
|
||||
Sign in
|
||||
</button>
|
||||
</form>
|
||||
{% endblock %}
|
||||
Reference in New Issue
Block a user