-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathUserEditController.php
302 lines (243 loc) · 10.4 KB
/
UserEditController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
<?php
declare(strict_types=1);
namespace Bolt\Controller\Backend;
use Bolt\Common\Str;
use Bolt\Configuration\Config;
use Bolt\Controller\CsrfTrait;
use Bolt\Controller\TwigAwareController;
use Bolt\Entity\User;
use Bolt\Enum\UserStatus;
use Bolt\Event\UserEvent;
use Bolt\Form\UserType;
use Bolt\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class UserEditController extends TwigAwareController implements BackendZoneInterface
{
use CsrfTrait;
/** @var UrlGeneratorInterface */
private $urlGenerator;
/** @var EntityManagerInterface */
private $em;
/** @var UserPasswordHasherInterface */
private $passwordHasher;
/** @var EventDispatcherInterface */
private $dispatcher;
/** @var string */
protected $defaultLocale;
/** @var array */
private $assignableRoles;
public function __construct(
UrlGeneratorInterface $urlGenerator,
EntityManagerInterface $em,
UserPasswordHasherInterface $passwordHasher,
CsrfTokenManagerInterface $csrfTokenManager,
EventDispatcherInterface $dispatcher,
Config $config,
string $defaultLocale
) {
$this->urlGenerator = $urlGenerator;
$this->em = $em;
$this->passwordHasher = $passwordHasher;
$this->csrfTokenManager = $csrfTokenManager;
$this->dispatcher = $dispatcher;
$this->defaultLocale = $defaultLocale;
$this->assignableRoles = $config->get('permissions/assignable_roles')->all();
}
/**
* @Route("/user-edit/add", methods={"GET","POST"}, name="bolt_user_add")
* @Security("is_granted('user:add')")
*/
public function add(Request $request): Response
{
$user = UserRepository::factory();
/** @var array $submitted_data */
$submitted_data = $request->request->get('user');
$event = new UserEvent($user);
$this->dispatcher->dispatch($event, UserEvent::ON_ADD);
$roles = $this->getPossibleRolesForForm();
// These are the variables we have to pass into our FormType so we can build the fields correctly
$form_data = [
'suggested_password' => Str::generatePassword(),
'roles' => $roles,
'require_username' => true,
'require_password' => true,
'default_locale' => $this->defaultLocale,
'is_profile_edit' => false,
];
$form = $this->createForm(UserType::class, $user, $form_data);
// ON SUBMIT
if (! empty($submitted_data)) {
// We need to transform to JSON.stringify value for the field "roles" into
// an array so symfony forms validation works
$submitted_data['roles'] = json_decode($submitted_data['roles']);
$submitted_data['locale'] = json_decode($submitted_data['locale'])[0];
$submitted_data['status'] = json_decode($submitted_data['status'])[0];
// Transform media array to keep only filepath
$submitted_data['avatar'] = $submitted_data['avatar']['filename'];
$form->submit($submitted_data);
}
if ($form->isSubmitted() && $form->isValid()) {
$this->handleValidFormSubmit($form);
return $this->redirectToRoute('bolt_users');
}
return $this->render('@bolt/users/add.html.twig', [
'userForm' => $form->createView(),
]);
}
/**
* @Route("/profile-edit", methods={"GET","POST"}, name="bolt_profile_edit")
*
* @Security("is_granted('editprofile')")
*/
public function editProfile(Request $request): Response
{
$submitted_data = $request->request->get('user');
/** @var User $user */
$user = $this->getUser();
return $this->handleEdit(true, $user, $submitted_data);
}
/**
* @Route("/user-edit/{id}", methods={"GET","POST"}, name="bolt_user_edit", requirements={"id": "\d+"})
*
* @Security("is_granted('user:edit')")
*/
public function edit(User $user, Request $request): Response
{
$submitted_data = $request->request->get('user');
return $this->handleEdit(false, $user, $submitted_data);
}
/**
* @Route("/user-status/{id}", methods={"POST", "GET"}, name="bolt_user_update_status", requirements={"id": "\d+"})
* @Security("is_granted('user:status')") -- first check, more detailed checks in method
*/
public function status(User $user): Response
{
$this->validateCsrf('useredit');
$newStatus = $this->request->get('status', UserStatus::DISABLED);
$user->setStatus($newStatus);
$this->addFlash('success', 'user.updated_successfully');
$this->em->persist($user);
$this->em->flush();
$url = $this->urlGenerator->generate('bolt_users');
return new RedirectResponse($url);
}
/**
* @Route("/user-delete/{id}", methods={"POST", "GET"}, name="bolt_user_delete", requirements={"id": "\d+"})
* @Security("is_granted('user:delete')")
*/
public function delete(User $user): Response
{
$this->validateCsrf('useredit');
$this->em->remove($user);
$contentArray = $this->getDoctrine()->getManager()->getRepository(\Bolt\Entity\Content::class)->findBy(['author' => $user]);
foreach ($contentArray as $content) {
$content->setAuthor(null);
$this->em->persist($content);
}
$mediaArray = $this->getDoctrine()->getManager()->getRepository(\Bolt\Entity\Media::class)->findBy(['author' => $user]);
foreach ($mediaArray as $media) {
$media->setAuthor(null);
$this->em->persist($media);
}
$this->em->flush();
$url = $this->urlGenerator->generate('bolt_users');
$this->addFlash('success', 'user.updated_profile');
return new RedirectResponse($url);
}
/**
* This function is called by add and edit function if given form was submitted and validated correctly.
* Here the User Object will be persisted to the DB. A security exception will be raised if the roles
* for the user being saved are not allowed for the current logged user.
*/
private function handleValidFormSubmit(FormInterface $form): void
{
// Get the adjusted User Entity from the form
/** @var User $user */
$user = $form->getData();
// Once validated, encode the password
if ($user->getPlainPassword()) {
$user->setPassword($this->passwordHasher->hashPassword($user, $user->getPlainPassword()));
$user->eraseCredentials();
}
$event = new UserEvent($user);
$this->dispatcher->dispatch($event, UserEvent::ON_PRE_SAVE);
// Save the new user data into the DB
$this->em->persist($user);
$this->em->flush();
$event = new UserEvent($user);
$this->dispatcher->dispatch($event, UserEvent::ON_POST_SAVE);
$this->addFlash('success', 'user.updated_profile');
}
private function getPossibleRolesForForm(): array
{
$result = [];
$assignableRoles = $this->assignableRoles;
// convert into array for form
foreach ($assignableRoles as $assignableRole) {
$result[$assignableRole] = $assignableRole;
}
return $result;
}
/**
* @return RedirectResponse|Response
*/
private function handleEdit(bool $is_profile_edit, User $user, $submitted_data)
{
$redirectRouteAfterSubmit = $is_profile_edit ? 'bolt_profile_edit' : 'bolt_users';
$event = new UserEvent($user);
$this->dispatcher->dispatch($event, UserEvent::ON_EDIT);
$roles = $this->getPossibleRolesForForm();
// We don't require the user to set the password again on the "user edit" form
// If it is otherwise set use the given password normally
$require_password = false;
if (! empty($submitted_data['plainPassword'])) {
$require_password = true;
}
// These are the variables we have to pass into our FormType so we can build the fields correctly
$form_data = [
'suggested_password' => Str::generatePassword(),
'roles' => $roles,
'require_username' => false,
'require_password' => $require_password,
'default_locale' => $this->defaultLocale,
'is_profile_edit' => $is_profile_edit,
];
$form = $this->createForm(UserType::class, $user, $form_data);
// ON SUBMIT
if (! empty($submitted_data)) {
// Since the username is disabled on edit form we need to set it here so Symfony Forms doesn't throw an error
$submitted_data['username'] = $user->getUsername();
$submitted_data['locale'] = json_decode($submitted_data['locale'])[0];
// Status is not available for profile edit on non admin users
if (! empty($submitted_data['status'])) {
$submitted_data['status'] = json_decode($submitted_data['status'])[0];
}
// Roles is not available for profile edit on non admin users
if (! empty($submitted_data['roles'])) {
// We need to transform to JSON.stringify value for the field "roles" into
// an array so symfony forms validation works
$submitted_data['roles'] = json_decode($submitted_data['roles']);
}
// Transform media array to keep only filepath
$submitted_data['avatar'] = $submitted_data['avatar']['filename'];
$form->submit($submitted_data);
}
if ($form->isSubmitted() && $form->isValid()) {
$this->handleValidFormSubmit($form);
return $this->redirectToRoute($redirectRouteAfterSubmit);
}
return $this->render('@bolt/users/edit.html.twig', [
'userForm' => $form->createView(),
]);
}
}