]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Controller/ConfigController.php
Change the way to enable 2FA
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Controller / ConfigController.php
CommitLineData
4d85d7e9
J
1<?php
2
3namespace Wallabag\CoreBundle\Controller;
4
dfd0a7bc 5use PragmaRX\Recovery\Recovery as BackupCodes;
4d85d7e9 6use Symfony\Bundle\FrameworkBundle\Controller\Controller;
0c83fd59 7use Symfony\Component\HttpFoundation\JsonResponse;
98568055 8use Symfony\Component\HttpFoundation\RedirectResponse;
619cc453 9use Symfony\Component\HttpFoundation\Request;
bb0c78f4 10use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
115de64e 11use Symfony\Component\Routing\Annotation\Route;
4d4147b2 12use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint;
4d85d7e9 13use Wallabag\CoreBundle\Entity\Config;
f19f9f62 14use Wallabag\CoreBundle\Entity\TaggingRule;
d9085c63 15use Wallabag\CoreBundle\Form\Type\ChangePasswordType;
f808b016 16use Wallabag\CoreBundle\Form\Type\ConfigType;
0c83fd59 17use Wallabag\CoreBundle\Form\Type\RssType;
619cc453
JB
18use Wallabag\CoreBundle\Form\Type\TaggingRuleType;
19use Wallabag\CoreBundle\Form\Type\UserInformationType;
0c83fd59 20use Wallabag\CoreBundle\Tools\Utils;
4d85d7e9
J
21
22class ConfigController extends Controller
23{
24 /**
25 * @param Request $request
26 *
27 * @Route("/config", name="config")
4d85d7e9
J
28 */
29 public function indexAction(Request $request)
30 {
d9085c63 31 $em = $this->getDoctrine()->getManager();
4d85d7e9 32 $config = $this->getConfig();
fcb1fba5 33 $userManager = $this->container->get('fos_user.user_manager');
c0d9eba0 34 $user = $this->getUser();
4d85d7e9 35
32da2a70 36 // handle basic config detail (this form is defined as a service)
4094ea47 37 $configForm = $this->createForm(ConfigType::class, $config, ['action' => $this->generateUrl('config')]);
d9085c63 38 $configForm->handleRequest($request);
4d85d7e9 39
21e7ccef 40 if ($configForm->isSubmitted() && $configForm->isValid()) {
4d85d7e9
J
41 $em->persist($config);
42 $em->flush();
43
ece4718f
NL
44 $request->getSession()->set('_locale', $config->getLanguage());
45
32da2a70
J
46 // switch active theme
47 $activeTheme = $this->get('liip_theme.active_theme');
48 $activeTheme->setName($config->getTheme());
49
a6b242a1 50 $this->addFlash(
4d85d7e9 51 'notice',
4204a06b 52 'flashes.config.notice.config_saved'
4d85d7e9
J
53 );
54
55 return $this->redirect($this->generateUrl('config'));
56 }
57
d9085c63 58 // handle changing password
f808b016 59 $pwdForm = $this->createForm(ChangePasswordType::class, null, ['action' => $this->generateUrl('config') . '#set4']);
d9085c63
J
60 $pwdForm->handleRequest($request);
61
21e7ccef 62 if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
a4f42c59 63 if ($this->get('craue_config')->get('demo_mode_enabled') && $this->get('craue_config')->get('demo_mode_username') === $user->getUsername()) {
4204a06b 64 $message = 'flashes.config.notice.password_not_updated_demo';
6c9f50a6 65 } else {
4204a06b 66 $message = 'flashes.config.notice.password_updated';
b6c00b0b 67
d8d56448
NL
68 $user->setPlainPassword($pwdForm->get('new_password')->getData());
69 $userManager->updateUser($user, true);
6c9f50a6 70 }
d9085c63 71
a6b242a1 72 $this->addFlash('notice', $message);
b6c00b0b 73
f808b016 74 return $this->redirect($this->generateUrl('config') . '#set4');
d9085c63
J
75 }
76
c0d9eba0 77 // handle changing user information
4094ea47
JB
78 $userForm = $this->createForm(UserInformationType::class, $user, [
79 'validation_groups' => ['Profile'],
f808b016 80 'action' => $this->generateUrl('config') . '#set3',
4094ea47 81 ]);
c0d9eba0
J
82 $userForm->handleRequest($request);
83
21e7ccef 84 if ($userForm->isSubmitted() && $userForm->isValid()) {
fcb1fba5 85 $userManager->updateUser($user, true);
c0d9eba0 86
a6b242a1 87 $this->addFlash(
c0d9eba0 88 'notice',
4204a06b 89 'flashes.config.notice.user_updated'
c0d9eba0
J
90 );
91
f808b016 92 return $this->redirect($this->generateUrl('config') . '#set3');
c0d9eba0
J
93 }
94
0c83fd59 95 // handle rss information
f808b016 96 $rssForm = $this->createForm(RssType::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
0c83fd59
J
97 $rssForm->handleRequest($request);
98
21e7ccef 99 if ($rssForm->isSubmitted() && $rssForm->isValid()) {
0c83fd59
J
100 $em->persist($config);
101 $em->flush();
102
a6b242a1 103 $this->addFlash(
0c83fd59 104 'notice',
4204a06b 105 'flashes.config.notice.rss_updated'
0c83fd59
J
106 );
107
f808b016 108 return $this->redirect($this->generateUrl('config') . '#set2');
0c83fd59
J
109 }
110
f19f9f62
KG
111 // handle tagging rule
112 $taggingRule = new TaggingRule();
f808b016 113 $action = $this->generateUrl('config') . '#set5';
bf3dc999
JB
114
115 if ($request->query->has('tagging-rule')) {
116 $taggingRule = $this->getDoctrine()
117 ->getRepository('WallabagCoreBundle:TaggingRule')
118 ->find($request->query->get('tagging-rule'));
119
120 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
121 return $this->redirect($action);
122 }
123
f808b016 124 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
bf3dc999
JB
125 }
126
127 $newTaggingRule = $this->createForm(TaggingRuleType::class, $taggingRule, ['action' => $action]);
f19f9f62
KG
128 $newTaggingRule->handleRequest($request);
129
21e7ccef 130 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
f19f9f62
KG
131 $taggingRule->setConfig($config);
132 $em->persist($taggingRule);
133 $em->flush();
134
a6b242a1 135 $this->addFlash(
f19f9f62 136 'notice',
4204a06b 137 'flashes.config.notice.tagging_rules_updated'
f19f9f62
KG
138 );
139
f808b016 140 return $this->redirect($this->generateUrl('config') . '#set5');
f19f9f62
KG
141 }
142
4094ea47
JB
143 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
144 'form' => [
0c83fd59
J
145 'config' => $configForm->createView(),
146 'rss' => $rssForm->createView(),
147 'pwd' => $pwdForm->createView(),
148 'user' => $userForm->createView(),
f19f9f62 149 'new_tagging_rule' => $newTaggingRule->createView(),
4094ea47
JB
150 ],
151 'rss' => [
0c83fd59
J
152 'username' => $user->getUsername(),
153 'token' => $config->getRssToken(),
4094ea47 154 ],
63e40f2d 155 'twofactor_auth' => $this->getParameter('twofactor_auth'),
be9d693e 156 'wallabag_url' => $this->getParameter('domain_name'),
a0c5eb00 157 'enabled_users' => $this->get('wallabag_user.user_repository')->getSumEnabledUsers(),
4094ea47 158 ]);
4d85d7e9
J
159 }
160
a0c5eb00
JB
161 /**
162 * Enable 2FA using email.
163 *
164 * @param Request $request
165 *
166 * @Route("/config/otp/email", name="config_otp_email")
167 */
168 public function otpEmailAction(Request $request)
169 {
170 if (!$this->getParameter('twofactor_auth')) {
171 return $this->createNotFoundException('two_factor not enabled');
172 }
173
174 $user = $this->getUser();
175
176 $user->setGoogleAuthenticatorSecret(null);
177 $user->setBackupCodes(null);
178 $user->setEmailTwoFactor(true);
179
180 $this->container->get('fos_user.user_manager')->updateUser($user, true);
181
182 $this->addFlash(
183 'notice',
184 'flashes.config.notice.otp_enabled'
185 );
186
187 return $this->redirect($this->generateUrl('config') . '#set3');
188 }
189
190 /**
191 * Enable 2FA using OTP app, user will need to confirm the generated code from the app.
192 *
193 * @Route("/config/otp/app", name="config_otp_app")
194 */
195 public function otpAppAction()
196 {
197 if (!$this->getParameter('twofactor_auth')) {
198 return $this->createNotFoundException('two_factor not enabled');
199 }
200
201 $user = $this->getUser();
202
203 if (!$user->isGoogleTwoFactor()) {
204 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
205
206 $user->setGoogleAuthenticatorSecret($secret);
207 $user->setEmailTwoFactor(false);
208 $user->setBackupCodes((new BackupCodes())->toArray());
209
210 $this->container->get('fos_user.user_manager')->updateUser($user, true);
211 }
212
213 return $this->render('WallabagCoreBundle:Config:otp_app.html.twig', [
214 'qr_code' => $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user),
215 ]);
216 }
217
218 /**
219 * Cancelling 2FA using OTP app.
220 *
221 * @Route("/config/otp/app/cancel", name="config_otp_app_cancel")
222 */
223 public function otpAppCancelAction()
224 {
225 if (!$this->getParameter('twofactor_auth')) {
226 return $this->createNotFoundException('two_factor not enabled');
227 }
228
229 $user = $this->getUser();
230 $user->setGoogleAuthenticatorSecret(null);
231 $user->setBackupCodes(null);
232
233 $this->container->get('fos_user.user_manager')->updateUser($user, true);
234
235 return $this->redirect($this->generateUrl('config') . '#set3');
236 }
237
238 /**
239 * Validate OTP code.
240 *
241 * @param Request $request
242 *
243 * @Route("/config/otp/app/check", name="config_otp_app_check")
244 */
245 public function otpAppCheckAction(Request $request)
246 {
247 $isValid = $this->get('scheb_two_factor.security.google_authenticator')->checkCode(
248 $this->getUser(),
249 $request->get('_auth_code')
250 );
251
252 if (true === $isValid) {
253 $this->addFlash(
254 'notice',
255 'flashes.config.notice.otp_enabled'
256 );
257
258 return $this->redirect($this->generateUrl('config') . '#set3');
259 }
260
261 $this->addFlash(
262 'two_factor',
263 'scheb_two_factor.code_invalid'
264 );
265
266 return $this->redirect($this->generateUrl('config_otp_app'));
267 }
268
0c83fd59
J
269 /**
270 * @param Request $request
271 *
272 * @Route("/generate-token", name="generate_token")
273 *
98568055 274 * @return RedirectResponse|JsonResponse
0c83fd59
J
275 */
276 public function generateTokenAction(Request $request)
277 {
278 $config = $this->getConfig();
279 $config->setRssToken(Utils::generateToken());
280
281 $em = $this->getDoctrine()->getManager();
282 $em->persist($config);
283 $em->flush();
284
285 if ($request->isXmlHttpRequest()) {
4094ea47 286 return new JsonResponse(['token' => $config->getRssToken()]);
0c83fd59
J
287 }
288
a6b242a1 289 $this->addFlash(
c7a4f74f 290 'notice',
4204a06b 291 'flashes.config.notice.rss_token_updated'
c7a4f74f
JB
292 );
293
f808b016 294 return $this->redirect($this->generateUrl('config') . '#set2');
0c83fd59
J
295 }
296
52e423f3
KG
297 /**
298 * Deletes a tagging rule and redirect to the config homepage.
299 *
300 * @param TaggingRule $rule
301 *
302 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
303 *
98568055 304 * @return RedirectResponse
52e423f3 305 */
5f8a7857 306 public function deleteTaggingRuleAction(TaggingRule $rule)
52e423f3 307 {
8799bde0 308 $this->validateRuleAction($rule);
52e423f3
KG
309
310 $em = $this->getDoctrine()->getManager();
311 $em->remove($rule);
312 $em->flush();
313
a6b242a1 314 $this->addFlash(
52e423f3 315 'notice',
4204a06b 316 'flashes.config.notice.tagging_rules_deleted'
52e423f3
KG
317 );
318
f808b016 319 return $this->redirect($this->generateUrl('config') . '#set5');
52e423f3
KG
320 }
321
bf3dc999
JB
322 /**
323 * Edit a tagging rule.
324 *
325 * @param TaggingRule $rule
326 *
327 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
328 *
329 * @return RedirectResponse
330 */
331 public function editTaggingRuleAction(TaggingRule $rule)
8799bde0
JB
332 {
333 $this->validateRuleAction($rule);
334
f808b016 335 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
8799bde0
JB
336 }
337
206bade5
JB
338 /**
339 * Remove all annotations OR tags OR entries for the current user.
340 *
341 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
342 *
343 * @return RedirectResponse
344 */
345 public function resetAction($type)
346 {
206bade5
JB
347 switch ($type) {
348 case 'annotations':
191564b7
JB
349 $this->getDoctrine()
350 ->getRepository('WallabagAnnotationBundle:Annotation')
351 ->removeAllByUserId($this->getUser()->getId());
206bade5 352 break;
206bade5 353 case 'tags':
191564b7
JB
354 $this->removeAllTagsByUserId($this->getUser()->getId());
355 break;
191564b7 356 case 'entries':
6da1aebc 357 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
191564b7 358 // otherwise they won't be removed ...
7ab5eb95 359 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
191564b7 360 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
206bade5
JB
361 }
362
8c61fd12 363 // manually remove tags to avoid orphan tag
f71e55ac
JB
364 $this->removeAllTagsByUserId($this->getUser()->getId());
365
25203e50 366 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
6da1aebc
TC
367 break;
368 case 'archived':
7ab5eb95 369 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
6da1aebc
TC
370 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
371 }
372
373 // manually remove tags to avoid orphan tag
374 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
375
25203e50 376 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
6da1aebc 377 break;
206bade5
JB
378 }
379
a6b242a1 380 $this->addFlash(
206bade5 381 'notice',
f808b016 382 'flashes.config.notice.' . $type . '_reset'
206bade5
JB
383 );
384
f808b016
JB
385 return $this->redirect($this->generateUrl('config') . '#set3');
386 }
387
388 /**
389 * Delete account for current user.
390 *
391 * @Route("/account/delete", name="delete_account")
392 *
393 * @param Request $request
394 *
395 * @throws AccessDeniedHttpException
396 *
397 * @return \Symfony\Component\HttpFoundation\RedirectResponse
398 */
399 public function deleteAccountAction(Request $request)
400 {
401 $enabledUsers = $this->get('wallabag_user.user_repository')
402 ->getSumEnabledUsers();
403
404 if ($enabledUsers <= 1) {
405 throw new AccessDeniedHttpException();
406 }
407
408 $user = $this->getUser();
409
410 // logout current user
411 $this->get('security.token_storage')->setToken(null);
412 $request->getSession()->invalidate();
413
414 $em = $this->get('fos_user.user_manager');
415 $em->deleteUser($user);
416
417 return $this->redirect($this->generateUrl('fos_user_security_login'));
418 }
419
420 /**
421 * Switch view mode for current user.
422 *
423 * @Route("/config/view-mode", name="switch_view_mode")
424 *
425 * @param Request $request
426 *
427 * @return \Symfony\Component\HttpFoundation\RedirectResponse
428 */
429 public function changeViewModeAction(Request $request)
430 {
431 $user = $this->getUser();
432 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
433
434 $em = $this->getDoctrine()->getManager();
435 $em->persist($user);
436 $em->flush();
437
438 return $this->redirect($request->headers->get('referer'));
206bade5
JB
439 }
440
be417ef2
NL
441 /**
442 * Change the locale for the current user.
443 *
444 * @param Request $request
445 * @param string $language
446 *
447 * @Route("/locale/{language}", name="changeLocale")
448 *
449 * @return \Symfony\Component\HttpFoundation\RedirectResponse
450 */
451 public function setLocaleAction(Request $request, $language = null)
452 {
4d4147b2
JB
453 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
454
455 if (0 === \count($errors)) {
456 $request->getSession()->set('_locale', $language);
be417ef2
NL
457 }
458
4d4147b2 459 return $this->redirect($request->headers->get('referer', $this->generateUrl('homepage')));
be417ef2
NL
460 }
461
191564b7 462 /**
e682a70f 463 * Remove all tags for given tags and a given user and cleanup orphan tags.
191564b7 464 *
e682a70f
NL
465 * @param array $tags
466 * @param int $userId
191564b7 467 */
e682a70f 468 private function removeAllTagsByStatusAndUserId($tags, $userId)
191564b7 469 {
191564b7
JB
470 if (empty($tags)) {
471 return;
472 }
473
25203e50 474 $this->get('wallabag_core.entry_repository')
191564b7 475 ->removeTags($userId, $tags);
f71e55ac 476
8c61fd12 477 // cleanup orphan tags
f71e55ac
JB
478 $em = $this->getDoctrine()->getManager();
479
480 foreach ($tags as $tag) {
2a1ceb67 481 if (0 === \count($tag->getEntries())) {
f71e55ac
JB
482 $em->remove($tag);
483 }
484 }
485
486 $em->flush();
191564b7
JB
487 }
488
e682a70f
NL
489 /**
490 * Remove all tags for a given user and cleanup orphan tags.
491 *
492 * @param int $userId
493 */
494 private function removeAllTagsByUserId($userId)
495 {
25203e50 496 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
e682a70f
NL
497 $this->removeAllTagsByStatusAndUserId($tags, $userId);
498 }
499
6da1aebc
TC
500 /**
501 * Remove all tags for a given user and cleanup orphan tags.
502 *
503 * @param int $userId
504 */
505 private function removeTagsForArchivedByUserId($userId)
506 {
25203e50 507 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
e682a70f 508 $this->removeAllTagsByStatusAndUserId($tags, $userId);
6da1aebc
TC
509 }
510
511 private function removeAnnotationsForArchivedByUserId($userId)
512 {
513 $em = $this->getDoctrine()->getManager();
514
515 $archivedEntriesAnnotations = $this->getDoctrine()
516 ->getRepository('WallabagAnnotationBundle:Annotation')
13a592a1 517 ->findAllArchivedEntriesByUser($userId);
6da1aebc
TC
518
519 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
520 $em->remove($archivedEntriesAnnotation);
521 }
522
523 $em->flush();
524 }
525
8799bde0 526 /**
2455472e 527 * Validate that a rule can be edited/deleted by the current user.
8799bde0 528 *
2455472e 529 * @param TaggingRule $rule
8799bde0
JB
530 */
531 private function validateRuleAction(TaggingRule $rule)
bf3dc999 532 {
f808b016 533 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
bf3dc999
JB
534 throw $this->createAccessDeniedException('You can not access this tagging rule.');
535 }
bf3dc999
JB
536 }
537
d9085c63
J
538 /**
539 * Retrieve config for the current user.
540 * If no config were found, create a new one.
541 *
4094ea47 542 * @return Config
d9085c63 543 */
4d85d7e9
J
544 private function getConfig()
545 {
546 $config = $this->getDoctrine()
547 ->getRepository('WallabagCoreBundle:Config')
548 ->findOneByUser($this->getUser());
549
ca17abce 550 // should NEVER HAPPEN ...
4d85d7e9
J
551 if (!$config) {
552 $config = new Config($this->getUser());
553 }
554
555 return $config;
556 }
557}