set admin user

This commit is contained in:
jleroy2023
2024-11-20 10:40:08 +01:00
parent caa78c634b
commit 74f6db8a80
9 changed files with 273 additions and 26 deletions

2
.env
View File

@@ -37,5 +37,5 @@ MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=0
###< symfony/messenger ###
###> symfony/mailer ###
MAILER_DSN=null://null
MAILER_DSN=smtp://no-reply@lidge.fr:t7qbPx6C1XDSWbO3XOFf@mail.lidge.fr:587
###< symfony/mailer ###

1
.idea/sortir.iml generated
View File

@@ -3,7 +3,6 @@
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" packagePrefix="App\" />
<sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" packagePrefix="App\Tests\" />
<excludeFolder url="file://$MODULE_DIR$/vendor/composer" />
<excludeFolder url="file://$MODULE_DIR$/vendor/doctrine/cache" />

View File

@@ -44,6 +44,7 @@ security:
access_control:
- { path: ^/login, roles: PUBLIC_ACCESS }
- { path: ^/register, roles: PUBLIC_ACCESS }
- { path: ^/admin, roles: ROLE_ADMIN }
- { path: ^/, roles: ROLE_USER }
when@test:

View File

@@ -0,0 +1,33 @@
<?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 Version20241120093750 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 password_reset_token (id_password_reset_token CHAR(36) NOT NULL COMMENT \'(DC2Type:guid)\', token VARCHAR(255) NOT NULL, created_at DATETIME NOT NULL, email VARCHAR(255) NOT NULL, PRIMARY KEY(id_password_reset_token)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE participant DROP file_name');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('DROP TABLE password_reset_token');
$this->addSql('ALTER TABLE participant ADD file_name VARCHAR(255) DEFAULT NULL');
}
}

View File

@@ -14,6 +14,8 @@ use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Attribute\Route;
class AdminController extends AbstractController
@@ -82,8 +84,68 @@ class AdminController extends AbstractController
$this->addFlash('success', 'Utilisateur supprimé avec succès.');
return $this->redirectToRoute('app_adminUser'); // Redirigez vers la liste des utilisateurs
}
#[Route('/admin/user/add', name: 'app_adminUserAdd', methods: ['POST'])]
public function userAdd(Request $request, EntityManagerInterface $entityManager, MailerInterface $mailer): Response
{
try {
// Récupérer les données envoyées par le formulaire
$nom = $request->request->get('nom');
$prenom = $request->request->get('prenom');
$pseudo = $request->request->get('pseudo');
$telephone = $request->request->get('phone');
$mail = $request->request->get('mail');
// Vérifier que les champs ne sont pas vides
if (!$mail || !$pseudo) {
$this->addFlash('error', 'Tous les champs sont requis.');
return $this->redirectToRoute('app_adminUser');
}
// Vérifier que le mail est valide avec une regex
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
$this->addFlash('error', 'L\'adresse e-mail n\'est pas valide.');
return $this->redirectToRoute('app_adminUser');
}
// Créer une nouvelle entité City et définir ses propriétés
$participant = new Participant();
$participant->setNom($nom);
$participant->setPrenom($prenom);
$participant->setPseudo($pseudo);
$participant->setTelephone($telephone);
$participant->setEmail($mail);
$participant->setAdministrateur(false);
$participant->setActif(false);
$participant->setRoles(['ROLE_USER']);
$participant->setPassword(password_hash("aChanger44!", PASSWORD_BCRYPT));
// Enregistrer la ville dans la base de données
$entityManager->persist($participant);
$entityManager->flush();
// Envoyer un email de notification
$email = (new Email())
->from('contact@Sortir.com')
->to($mail)
->subject('Sortir.com | Bienvenue sur notre site !')
->html("
<h1>Bonjour $pseudo,</h1>
<p>Un administrateur du site vous à créé un compte sur <a href='https://localhost:8080' target='_blank'>Sortir.com</a> !</p>
<p>Votre mot de passe temporaire est : <strong>aChanger44!</strong></p>
<p>Toute l'équipe de Sortir vous souhaite la bienvenue !</p>
");
$mailer->send($email);
$this->addFlash('success', "Utilisateur ajouté ! Un email lui a été envoyé !");
return $this->redirectToRoute('app_adminUser');
} catch(\Exception $e) {
$this->addFlash('error', "Erreur : " . $e->getMessage());
return $this->redirectToRoute('app_adminUser');
}
}
#[Route('/admin/user/import', name: 'participant_import', methods: ['POST'])]
public function import(Request $request, EntityManagerInterface $em): Response
public function import(Request $request, EntityManagerInterface $em): RedirectResponse
{
$file = $request->files->get('csv_file');
if ($file) {
@@ -96,10 +158,10 @@ class AdminController extends AbstractController
$participant->setPseudo($row[2]);
$participant->setTelephone($row[3]);
$participant->setEmail($row[4]);
$participant->setAdministrateur((bool)$row[5]);
$participant->setActif((bool)$row[6]);
$participant->setAdministrateur(false);
$participant->setActif(false);
$participant->setRoles(explode('|', $row[7]));
$participant->setPassword(password_hash($row[8], PASSWORD_BCRYPT));
$participant->setPassword(password_hash("aChanger44!", PASSWORD_BCRYPT));
$em->persist($participant);
}
$em->flush();

View File

@@ -0,0 +1,70 @@
<?php
namespace App\Entity;
use App\Repository\PasswordResetTokenRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: PasswordResetTokenRepository::class)]
class PasswordResetToken
{
#[ORM\Id]
#[ORM\Column(type: 'guid', unique: true)]
#[ORM\GeneratedValue(strategy: 'CUSTOM')]
#[ORM\CustomIdGenerator(class: 'doctrine.uuid_generator')]
private ?string $idPasswordResetToken = null;
#[ORM\Column(type: 'string', length: 255)]
private ?string $token = null;
#[ORM\Column(type: 'datetime')]
private ?\DateTimeInterface $createdAt = null;
#[ORM\Column(type: 'string', length: 255)]
private ?string $email = null;
public function getIdPasswordResetToken(): ?string
{
return $this->idPasswordResetToken;
}
public function getToken(): ?string
{
return $this->token;
}
public function setToken(string $token): self
{
$this->token = $token;
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function isExpired(): bool
{
$now = new \DateTime();
return $this->createdAt->modify('+24 hours') < $now;
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace App\Repository;
use App\Entity\PasswordResetToken;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<PasswordResetToken>
*/
class PasswordResetTokenRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, PasswordResetToken::class);
}
// /**
// * @return PasswordResetToken[] Returns an array of PasswordResetToken objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('p')
// ->andWhere('p.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('p.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?PasswordResetToken
// {
// return $this->createQueryBuilder('p')
// ->andWhere('p.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}

View File

@@ -5,26 +5,11 @@
{% block content %}
<div class="flex">
<!-- Bouton pour afficher la sidebar sur les petits écrans -->
<button id="sidebarToggle" class="lg:hidden p-4 text-white bg-gray-700 rounded">
&#9776; <!-- Symbole hamburger -->
</button>
{% include 'admin/sidebar.html.twig' %}
<div id="sidebar" class="lg:block fixed inset-0 bg-gray-800 bg-opacity-75 z-50 hidden">
{% include 'admin/sidebar.html.twig' %}
</div>
<div id="mainContent" class="flex-1 p-8 ml-64 lg:ml-0">
<div class="ml-64 p-8 w-full">
<h1 class="text-2xl font-semibold">Bienvenue sur le Panel d'Administration</h1>
<p class="text-gray-600 mt-4">Utilisez le menu pour accéder aux différentes sections.</p>
</div>
</div>
<script>
const sidebarToggle = document.getElementById('sidebarToggle');
const sidebar = document.getElementById('sidebar');
sidebarToggle.addEventListener('click', function () {
sidebar.classList.toggle('hidden'); // Bascule l'affichage de la sidebar
});
</script>
{% endblock %}

View File

@@ -29,9 +29,16 @@
Importer CSV
</button>
</form>
<a href="{{ path('participant_export') }}" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
Exporter CSV
</a>
<button
id="openModal"
class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700">
Ajouter un utilisateur
</button>
<button
type="submit"
class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
<a href="{{ path('participant_export') }}">Exporter CSV</a>
</button>
</div>
<!-- Participants Table -->
@@ -83,5 +90,52 @@
</table>
</div>
</div>
<!-- Modale pour ajouter une ville -->
<div id="userModal" class="fixed inset-0 z-50 hidden bg-gray-900 bg-opacity-50">
<div class="flex justify-center items-center min-h-screen">
<div class="bg-white p-6 rounded shadow-md w-1/3">
<h2 class="text-xl font-semibold mb-4">Ajouter un utilisateur</h2>
<form id="addUserForm" method="POST" action="{{ path('app_adminUserAdd') }}">
<div class="mb-4">
<label for="nom" class="block text-sm font-medium text-gray-700">Nom</label>
<input id="nom" name="nom" type="text" class="mt-1 block w-full px-4 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
<div class="mb-4">
<label for="prenom" class="block text-sm font-medium text-gray-700">Prénom</label>
<input id="prenom" name="prenom" type="text" class="mt-1 block w-full px-4 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
<div class="mb-4">
<label for="pseudo" class="block text-sm font-medium text-gray-700">Pseudo *</label>
<input id="pseudo" name="pseudo" type="text" class="mt-1 block w-full px-4 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500" required>
</div>
<div class="mb-4">
<label for="phone" class="block text-sm font-medium text-gray-700">téléphone</label>
<input id="phone" name="phone" type="text" class="mt-1 block w-full px-4 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
<div class="mb-4">
<label for="mail" class="block text-sm font-medium text-gray-700">Email *</label>
<input id="mail" name="mail" type="text" class="mt-1 block w-full px-4 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500" required>
</div>
<p>* Champ obligatoire</p>
<div class="flex justify-end">
<button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-700">Ajouter</button>
<button type="button" id="closeModal" class="ml-2 bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-700">Annuler</button>
</div>
</form>
</div>
</div>
</div>
<script>
// Ouvrir la modale manuellement
document.getElementById('openModal').addEventListener('click', function() {
document.getElementById('userModal').classList.remove('hidden');
});
// Fermer la modale
document.getElementById('closeModal').addEventListener('click', function() {
document.getElementById('userModal').classList.add('hidden');
});
</script>
</div>
{% endblock %}