Passed
Push — master ( 1e4fc2...92950f )
by Jan
24:48
created

SecurityController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

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

200
                $event = new SecurityEvent(/** @scrutinizer ignore-type */ $u);
Loading history...
201
                /** @var EventDispatcher $eventDispatcher */
202
                $eventDispatcher->dispatch($event, SecurityEvents::PASSWORD_RESET);
203
204
                return $this->redirectToRoute('login');
205
            }
206
        }
207
208
        return $this->render('security/pw_reset_new_pw.html.twig', [
209
            'form' => $form->createView(),
210
        ]);
211
    }
212
213
    /**
214
     * @Route("/logout", name="logout")
215
     */
216
    public function logout(): void
217
    {
218
        throw new RuntimeException('Will be intercepted before getting here');
219
    }
220
}
221