Parcourir la source

Récupérer un mot de passe oublié

François il y a 6 ans
Parent
commit
4eff85c2a2

+ 8 - 0
app/Resources/views/base.html.twig

@@ -82,6 +82,14 @@
 						</button>
 					</div>
 					{% endfor %}
+                    {% for message in app.flashes('warning') %}
+						<div class="alert alert-warning alert-dismissible fade show" role="alert">
+							<strong>Attention</strong> {{ message }}
+							<button type="button" class="close" data-dismiss="alert" aria-label="Close">
+								<span aria-hidden="true">&times;</span>
+							</button>
+						</div>
+                    {% endfor %}
 					{% block body %}{% endblock %}
 				</div>
 

+ 1 - 1
app/config/security.yml

@@ -21,7 +21,7 @@ security:
             security: false
 
         main_login:
-            pattern: ^/(login$|register)
+            pattern: ^/(login$|register$|motdepasseoublie$|resetpassword/token=)
             anonymous: true
             logout_on_user_change: true
 

+ 64 - 2
src/AppBundle/Controller/SecurityController.php

@@ -2,14 +2,18 @@
 
 namespace AppBundle\Controller;
 
+use AppBundle\Form\UserEditPasswordType;
 use AppBundle\Form\UserEditType;
 use AppBundle\Form\UserRegisterType;
 use Symfony\Bundle\FrameworkBundle\Controller\Controller;
+use Symfony\Component\Form\Extension\Core\Type\SearchType;
+use Symfony\Component\Form\Extension\Core\Type\SubmitType;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\Routing\Annotation\Route;
 use AppBundle\Form\UserType;
 use AppBundle\Entity\User;
 use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
+use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
 
 class SecurityController extends Controller
 {
@@ -147,10 +151,68 @@ class SecurityController extends Controller
     }
 
     /**
-     * @Route("/resetpassword/{token}", name="security_resetpassword")
+     * @Route("/motdepasseoublie", name="security_envoyertoken")
      */
-    public function resetPasswordAction(User $user)
+    public function recupMdpAction(Request $request, \Swift_Mailer $mailer)
     {
+        $form = $this->createFormBuilder()
+            ->add('email', SearchType::class)
+            ->add('Envoyer mail', SubmitType::class)
+            ->getForm();
+
+        $form->handleRequest($request);
+        if ($form->isSubmitted() && $form->isValid()) {
+            $em = $this->getDoctrine()->getManager();
+            $data = $form->getData();
+            $user = $em->getRepository('AppBundle:User')->findOneBy(array('mail'=>$data['email']));
+            if ($user != null)
+            {
+                $user->setToken();
+                $em->flush();
+                $adresse = $this->generateUrl('security_resetpassword', array('token'=>$user->getToken()), UrlGeneratorInterface::ABSOLUTE_URL);
+                $swiftMessage = new \Swift_Message('Videothèque - Mot de passe oublié');
+                $message = $swiftMessage
+                    ->setFrom('admin@fdlibre.eu')
+                    ->setTo($user->getMail())
+                    ->setBody("Salut ".$user->getUsername().", clique sur ce lien pour renouveller ton mot de passe : ". $adresse);
+
+                $mailer->send($message);
+                $this->addFlash('success', "Un mail vous a été envoyé à ".$user->getUsername()." pour récupérer le mot de passe");
+                return $this->redirectToRoute('login');
+            } else {
+                $this->addFlash('warning', "Cet email n'existe pas");
+            }
+        }
+        return $this->render('@App/security/chercheruserpourpassword.html.twig', array (
+            'form'  =>  $form->createView()
+        ));
+    }
+
+    /**
+     * @Route("/resetpassword/token={token}", name="security_resetpassword")
+     */
+    public function resetPasswordAction(Request $request, UserPasswordEncoderInterface $encoder, User $user = null)
+    {
+        if ($user != null) {
+            if ($user->isValidToken()) {
+                $form = $this->createForm(UserEditPasswordType::class, $user);
+                $form->handleRequest($request);
+                if ($form->isSubmitted() && $form->isValid()) {
+                    $encoded = $encoder->encodePassword($user, $user->getPassword());
+                    $user->setPassword($encoded);
+                    $user->setToken();
+                    $em = $this->getDoctrine()->getManager();
+                    $em->flush();
+                    $this->addFlash('success', 'Mot de passe changé, veuillez vous connecter');
+                    return $this->redirectToRoute('videotheque_liste');
+                }
+                return $this->render('@App/security/password.html.twig', array(
+                    'form' => $form->createView()
+                ));
+            }
+        }
+        $this->addFlash('warning', "Ce token n'est plus valide");
+        return $this->redirectToRoute('videotheque_liste');
 
     }
 

+ 5 - 6
src/AppBundle/Entity/User.php

@@ -289,7 +289,7 @@ class User implements UserInterface
     /**
      * Get token_validity
      *
-     * @return string
+     * @return \DateTime
      */
     public function getTokenValidity()
     {
@@ -299,11 +299,11 @@ class User implements UserInterface
     /**
      * Set token
      *
-     * @param string $tokenValidity
+     * @param \DateTime $tokenValidity
      *
      * @return User
      */
-    private function setTokenValidity($tokenValidity)
+    private function setTokenValidity(\DateTime $tokenValidity)
     {
         $this->tokenValidity = $tokenValidity;
 
@@ -319,9 +319,8 @@ class User implements UserInterface
 
     public function isValidToken()
     {
-        $delay = new \DateTime('1 hour');
-
-        return ( $this->getTokenValidity() < $delay );
+        $expire = $this->getTokenValidity()->modify('+1 hour');
+        return ( $expire > new \DateTime('now') );
     }
 
     /**

+ 27 - 0
src/AppBundle/Form/UserEditPasswordType.php

@@ -0,0 +1,27 @@
+<?php
+
+namespace AppBundle\Form;
+
+use Symfony\Component\Form\AbstractType;
+use Symfony\Component\Form\FormBuilderInterface;
+
+class UserEditPasswordType extends AbstractType
+{
+    /**
+     * {@inheritdoc}
+     */
+    public function buildForm(FormBuilderInterface $builder, array $options)
+    {
+        $builder
+            ->remove('username')
+            ->remove('nom')
+            ->remove('prenom')
+            ->remove('mail')
+            ->remove('roles');
+    }
+
+    public function getParent()
+    {
+        return UserType::class;
+    }
+}

+ 9 - 0
src/AppBundle/Resources/views/security/chercheruserpourpassword.html.twig

@@ -0,0 +1,9 @@
+{% extends "base.html.twig" %}
+
+{% block title %}Récupérer mot de passe{%  endblock %}
+{% block titre %}Récupérer mot de passe{%  endblock %}
+
+{% block body %}
+    <h2>Veuillez entrer votre adresse mail</h2>
+    {{ form(form) }}
+{% endblock %}

+ 1 - 0
src/AppBundle/Resources/views/security/login.html.twig

@@ -24,5 +24,6 @@
         <input type="submit" value="Connexion" />
     </form>
     <p>Pas de compte ? <a href="{{ path('security_register') }}">S'enregistrer</a></p>
+    <p>Mot de passe oublié ? <a href="{{ path('security_envoyertoken') }}">Récupérer mot de passe</a></p>
 
 {% endblock %}

+ 9 - 0
src/AppBundle/Resources/views/security/password.html.twig

@@ -0,0 +1,9 @@
+{% extends "base.html.twig" %}
+
+{% block title %}Changer de mot de passe{%  endblock %}
+{% block titre %}Changer de mot de passe{%  endblock %}
+
+{% block body %}
+    <h2>Vous pouvez changer de mot de passe ici</h2>
+    {{ form(form) }}
+{% endblock %}