SecurityController::login()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace App\Controller;
4
5
use App\Entity\User;
6
use App\Form\ResetPasswordType;
7
use App\Form\UserRegistrationType;
8
use Doctrine\Common\Persistence\ObjectManager;
9
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
10
use Symfony\Component\Form\Extension\Core\Type\EmailType;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpFoundation\Response;
13
use Symfony\Component\Routing\Annotation\Route;
14
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
15
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
16
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
17
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
18
19
class SecurityController extends AbstractController
20
{
21
    /**
22
     * @Route("/login", name="security_login")
23
     */
24
    public function login(AuthenticationUtils $auth): Response
25
    {
26
        $error = $auth->getLastAuthenticationError();
27
        $lastUsername = $auth->getLastUsername();
28
        return $this->render('security/login.html.twig', [
29
           'last_username' => $lastUsername,
30
           'error' => $error
31
        ]);
32
    }
33
34
    /**
35
     * @Route("/logout", name="security_logout")
36
     */
37
    public function logout()
38
    {
39
    }
40
41
    /**
42
     * @Route("/register", name="security_register")
43
     */
44
    public function register(Request $request,
45
                             ObjectManager $om,
46
                             UserPasswordEncoderInterface $encoder,
47
                             \Swift_Mailer $mailer,
48
                             TokenGeneratorInterface $generator)
49
    {
50
51
        $user = new User();
52
        $form = $this->createForm(UserRegistrationType::class, $user);
53
        $form->handleRequest($request);
54
55
        if ($form->isSubmitted() && $form->isValid()) {
56
            $hash = $encoder->encodePassword($user, $user->getPlainPassword());
57
            $user->setPassword($hash);
58
59
            $token = $generator->generateToken();
60
            $user->setToken($token);
61
62
            $user->setValidation(false);
63
64
            $mode = $form->getData()->getMode();
65
            //dump($request);dump($mode); dump($form->getData()->getMode()); die();
66
67
            if ($mode == 1) {
68
                $user->setRoles(['ROLE_RECRUITER']);
69
            } else {
70
                $user->setRoles(['ROLE_CANDIDATE']);
71
            }
72
            $om->persist($user);
73
            $om->flush();
74
75
            $message = (new \Swift_Message('Votre inscription sur SnowTricks'))
76
                ->setFrom('[email protected]')
77
                ->setTo($user->getEmail())
78
                ->setBody('Validez votre compte en cliquant sur ce <a href="http://localhost:8000/confirm?user=' . $user->getId() . '&token=' . $token . '">LIEN</a>', 'text/html');
79
80
            $mailer->send($message);
81
82
            $this->addFlash('success', 'Un mail de confirmation vous a été envoyé, cliquez sur le lien pour activer votre compte.');
83
            return $this->redirectToRoute('security_login');
84
        }
85
86
        return $this->render('security/register.html.twig', [
87
            'formRegister' => $form->createView(),
88
        ]);
89
    }
90
91
    /**
92
     * @param Request $request
93
     * @param User $user
94
     * @return Response
95
     * @Route("/confirm", name="security_confirm")
96
     */
97
    public function registerConfirm(Request $request, User $user)
98
    {
99
        $token = $request->get('token');
100
        if (!$token) {
101
            return new Response(new InvalidCsrfTokenException());
102
        }
103
104
        if (!$user) {
0 ignored issues
show
introduced by
$user is of type App\Entity\User, thus it always evaluated to true.
Loading history...
105
            throw $this->createNotFoundException();
106
        }
107
108
        if ($user->getToken() === $token) {
109
            $user->setValidation(true);
110
            $this->getDoctrine()->getManager()->flush();
111
            $this->addFlash('success', 'Votre compte a bien été activé');
112
        }
113
        return $this->redirecttoRoute('security_login');
114
    }
115
116
    /**
117
     * @Route("/forgotpassword", name="security_forgot")
118
     */
119
    public function forgotPassword(Request $request, \Swift_Mailer $mailer, TokenGeneratorInterface $generator)
120
    {
121
        $user = new User();
122
        $form = $this->createFormBuilder($user)
123
            ->add('email', EmailType::class)
124
            ->getForm();
125
126
        $form->handleRequest($request);
127
128
        if ($form->isSubmitted()) {
129
            $user = $form->getData();
130
            $email = $user->getEmail();
131
132
133
            $repository = $this->getDoctrine()->getRepository(User::class);
134
            $userMail = $repository->findOneBy(['email' => $email]);
135
            //dd($userMail);
136
137
138
            $token = $generator->generateToken();
139
            $userMail->setToken($token);
140
141
            $this->getDoctrine()->getManager()->flush();
142
143
            if ($userMail){
144
145
                $message = (new \Swift_Message('Réinitialisation de votre mot de passe'))
146
                    ->setFrom('[email protected]')
147
                    ->setTo($user->getEmail())
148
                    ->setBody('<a href="http://localhost:8000/resetpassword?user=' . $userMail->getId() . '&token=' . $token . '">Réinitialiser votre mot de passe</a>', 'text/html');
149
                $mailer->send($message);
150
                $this->addFlash(
151
                    'success',
152
                    'Un mail vous a été envoyé, cliquez sur le lien pour réinitialiser votre mot de passe.'
153
                );
154
            }
155
            return $this->redirectToRoute('security_login');
156
        }
157
158
        return $this->render(
159
            'security/forgotpassword.html.twig', [
160
                'formForgotPassword' => $form->createView(),
161
            ]
162
        );
163
    }
164
165
    /**
166
     * Page pour réinitialiser son mot de passe
167
     *
168
     * @Route("/resetpassword", name="security_reset")
169
     */
170
    function resetPasswordPage(Request $request, UserPasswordEncoderInterface $encoder)
171
    {
172
        $token = $request->get('token');
173
        if (!$token) {
174
            return new Response(new InvalidCsrfTokenException());
175
        }
176
177
        $user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['token' => $request->get('token')]);
178
        if (!$user) {
179
            throw $this->createNotFoundException();
180
        }
181
        if ($user->getToken() !== $token) {
182
            throw $this->createNotFoundException();
183
        }
184
185
        $form = $this->createForm(ResetPasswordType::class, $user);
186
        $form->handleRequest($request);
187
        if ($form->isSubmitted() && $form->isValid()) {
188
            $password = $form->getData();
189
            $hash = $encoder->encodePassword($password, $user->getPlainPassword());
190
            $user->setPassword($hash);
191
            $user->setResetToken('');
0 ignored issues
show
Bug introduced by
The method setResetToken() does not exist on App\Entity\User. Did you maybe mean setToken()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

191
            $user->/** @scrutinizer ignore-call */ 
192
                   setResetToken('');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
192
            $this->getDoctrine()->getManager()->flush();
193
            $this->addFlash('success', 'Votre mot de passe a bien été réinitialisé !');
194
            return $this->redirectToRoute('security_login');
195
        }
196
        return $this->render(
197
            'security/resetpasswordpage.html.twig', [
198
                'formResetPassword' => $form->createView(),
199
            ]
200
        );
201
    }
202
}
203