Passed
Push — master ( 4f70d8...12b310 )
by Jan
04:24
created

SecurityController::pwResetNewPw()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 51
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 32
c 0
b 0
f 0
nc 5
nop 4
dl 0
loc 51
rs 8.7857

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
4
 *
5
 * Copyright (C) 2019 Jan Böhmer (https://github.com/jbtronics)
6
 *
7
 * This program is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU General Public License
9
 * as published by the Free Software Foundation; either version 2
10
 * of the License, or (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
20
 */
21
22
namespace App\Controller;
23
24
use App\Services\PasswordResetManager;
25
use Doctrine\ORM\EntityManagerInterface;
26
use Gregwar\CaptchaBundle\Type\CaptchaType;
27
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
28
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
29
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
30
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
31
use Symfony\Component\Form\Extension\Core\Type\TextType;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
34
use Symfony\Component\Mailer\MailerInterface;
35
use Symfony\Component\Routing\Annotation\Route;
36
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
37
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
38
use Symfony\Component\Validator\Constraints\Length;
39
use Symfony\Component\Validator\Constraints\NotBlank;
40
use Symfony\Contracts\Translation\TranslatorInterface;
41
42
class SecurityController extends AbstractController
43
{
44
    protected $translator;
45
    protected $allow_email_pw_reset;
46
47
    public function __construct(TranslatorInterface $translator, bool $allow_email_pw_reset)
48
    {
49
        $this->translator = $translator;
50
        $this->allow_email_pw_reset = $allow_email_pw_reset;
51
    }
52
53
    /**
54
     * @Route("/login", name="login", methods={"GET", "POST"})
55
     */
56
    public function login(AuthenticationUtils $authenticationUtils)
57
    {
58
        // get the login error if there is one
59
        $error = $authenticationUtils->getLastAuthenticationError();
60
61
        // last username entered by the user
62
        $lastUsername = $authenticationUtils->getLastUsername();
63
64
        return $this->render('security/login.html.twig', [
65
            'last_username' => $lastUsername,
66
            'error' => $error,
67
        ]);
68
    }
69
70
    /**
71
     * @Route("/pw_reset/request", name="pw_reset_request")
72
     */
73
    public function requestPwReset(PasswordResetManager $passwordReset, Request $request)
74
    {
75
        if (!$this->allow_email_pw_reset) {
76
            throw new AccessDeniedHttpException("The password reset via email is disabled!");
77
        }
78
79
        if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
80
            throw new AccessDeniedHttpException("You are already logged in, so you can not reset your password!");
81
        }
82
83
        $builder = $this->createFormBuilder();
84
        $builder->add('user', TextType::class, [
85
            'label' => $this->translator->trans('pw_reset.user_or_password'),
86
            'constraints' => [new NotBlank()]
87
        ]);
88
        $builder->add('captcha', CaptchaType::class, [
89
            'width' => 200,
90
            'height' => 50,
91
            'length' => 6,
92
        ]);
93
        $builder->add('submit', SubmitType::class, [
94
            'label' => 'pw_reset.submit'
95
        ]);
96
97
        $form = $builder->getForm();
98
        $form->handleRequest($request);
99
100
        if ($form->isSubmitted() && $form->isValid()) {
101
            $passwordReset->request($form->getData()['user']);
102
            $this->addFlash('success', $this->translator->trans('pw_reset.request.success'));
103
            return $this->redirectToRoute('login');
104
        }
105
106
        return $this->render('security/pw_reset_request.html.twig', [
107
            'form' => $form->createView()
108
        ]);
109
    }
110
111
    /**
112
     * @Route("/pw_reset/new_pw/{user}/{token}", name="pw_reset_new_pw")
113
     */
114
    public function pwResetNewPw(PasswordResetManager $passwordReset, Request $request, string $user = null, string $token = null)
115
    {
116
        if (!$this->allow_email_pw_reset) {
117
            throw new AccessDeniedHttpException("The password reset via email is disabled!");
118
        }
119
120
        if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
121
            throw new AccessDeniedHttpException("You are already logged in, so you can not reset your password!");
122
        }
123
124
        $data = ['username' => $user, 'token' => $token];
125
        $builder = $this->createFormBuilder($data);
126
        $builder->add('username', TextType::class, [
127
            'label' => $this->translator->trans('pw_reset.username')
128
        ]);
129
        $builder->add('token', TextType::class, [
130
            'label' => $this->translator->trans('pw_reset.token')
131
        ]);
132
        $builder->add('new_password', RepeatedType::class, [
133
            'type' => PasswordType::class,
134
            'first_options' => ['label' => 'user.settings.pw_new.label'],
135
            'second_options' => ['label' => 'user.settings.pw_confirm.label'],
136
            'invalid_message' => 'password_must_match',
137
            'constraints' => [new Length([
138
                'min' => 6,
139
                'max' => 128,
140
            ])],
141
        ]);
142
143
        $builder->add('submit', SubmitType::class, [
144
            'label' => 'pw_reset.submit'
145
        ]);
146
147
        $form = $builder->getForm();
148
        $form->handleRequest($request);
149
150
        if ($form->isSubmitted() && $form->isValid()) {
151
            $data = $form->getData();
152
            //Try to set the new password
153
            $success = $passwordReset->setNewPassword($data['username'], $data['token'], $data['new_password']);
154
            if (!$success) {
155
                $this->addFlash('error', $this->translator->trans('pw_reset.new_pw.error'));
156
            } else {
157
                $this->addFlash('success', $this->translator->trans('pw_reset.new_pw.success'));
158
                return $this->redirectToRoute('login');
159
            }
160
        }
161
162
163
        return $this->render('security/pw_reset_new_pw.html.twig', [
164
            'form' => $form->createView()
165
        ]);
166
    }
167
168
    /**
169
     * @Route("/logout", name="logout")
170
     */
171
    public function logout()
172
    {
173
        throw new \RuntimeException('Will be intercepted before getting here');
174
    }
175
}
176