]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Controller/ConfigController.php
Change the way to enable 2FA
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Controller / ConfigController.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Controller;
4
5 use PragmaRX\Recovery\Recovery as BackupCodes;
6 use Symfony\Bundle\FrameworkBundle\Controller\Controller;
7 use Symfony\Component\HttpFoundation\JsonResponse;
8 use Symfony\Component\HttpFoundation\RedirectResponse;
9 use Symfony\Component\HttpFoundation\Request;
10 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
11 use Symfony\Component\Routing\Annotation\Route;
12 use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint;
13 use Wallabag\CoreBundle\Entity\Config;
14 use Wallabag\CoreBundle\Entity\TaggingRule;
15 use Wallabag\CoreBundle\Form\Type\ChangePasswordType;
16 use Wallabag\CoreBundle\Form\Type\ConfigType;
17 use Wallabag\CoreBundle\Form\Type\RssType;
18 use Wallabag\CoreBundle\Form\Type\TaggingRuleType;
19 use Wallabag\CoreBundle\Form\Type\UserInformationType;
20 use Wallabag\CoreBundle\Tools\Utils;
21
22 class ConfigController extends Controller
23 {
24 /**
25 * @param Request $request
26 *
27 * @Route("/config", name="config")
28 */
29 public function indexAction(Request $request)
30 {
31 $em = $this->getDoctrine()->getManager();
32 $config = $this->getConfig();
33 $userManager = $this->container->get('fos_user.user_manager');
34 $user = $this->getUser();
35
36 // handle basic config detail (this form is defined as a service)
37 $configForm = $this->createForm(ConfigType::class, $config, ['action' => $this->generateUrl('config')]);
38 $configForm->handleRequest($request);
39
40 if ($configForm->isSubmitted() && $configForm->isValid()) {
41 $em->persist($config);
42 $em->flush();
43
44 $request->getSession()->set('_locale', $config->getLanguage());
45
46 // switch active theme
47 $activeTheme = $this->get('liip_theme.active_theme');
48 $activeTheme->setName($config->getTheme());
49
50 $this->addFlash(
51 'notice',
52 'flashes.config.notice.config_saved'
53 );
54
55 return $this->redirect($this->generateUrl('config'));
56 }
57
58 // handle changing password
59 $pwdForm = $this->createForm(ChangePasswordType::class, null, ['action' => $this->generateUrl('config') . '#set4']);
60 $pwdForm->handleRequest($request);
61
62 if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
63 if ($this->get('craue_config')->get('demo_mode_enabled') && $this->get('craue_config')->get('demo_mode_username') === $user->getUsername()) {
64 $message = 'flashes.config.notice.password_not_updated_demo';
65 } else {
66 $message = 'flashes.config.notice.password_updated';
67
68 $user->setPlainPassword($pwdForm->get('new_password')->getData());
69 $userManager->updateUser($user, true);
70 }
71
72 $this->addFlash('notice', $message);
73
74 return $this->redirect($this->generateUrl('config') . '#set4');
75 }
76
77 // handle changing user information
78 $userForm = $this->createForm(UserInformationType::class, $user, [
79 'validation_groups' => ['Profile'],
80 'action' => $this->generateUrl('config') . '#set3',
81 ]);
82 $userForm->handleRequest($request);
83
84 if ($userForm->isSubmitted() && $userForm->isValid()) {
85 $userManager->updateUser($user, true);
86
87 $this->addFlash(
88 'notice',
89 'flashes.config.notice.user_updated'
90 );
91
92 return $this->redirect($this->generateUrl('config') . '#set3');
93 }
94
95 // handle rss information
96 $rssForm = $this->createForm(RssType::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
97 $rssForm->handleRequest($request);
98
99 if ($rssForm->isSubmitted() && $rssForm->isValid()) {
100 $em->persist($config);
101 $em->flush();
102
103 $this->addFlash(
104 'notice',
105 'flashes.config.notice.rss_updated'
106 );
107
108 return $this->redirect($this->generateUrl('config') . '#set2');
109 }
110
111 // handle tagging rule
112 $taggingRule = new TaggingRule();
113 $action = $this->generateUrl('config') . '#set5';
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
124 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
125 }
126
127 $newTaggingRule = $this->createForm(TaggingRuleType::class, $taggingRule, ['action' => $action]);
128 $newTaggingRule->handleRequest($request);
129
130 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
131 $taggingRule->setConfig($config);
132 $em->persist($taggingRule);
133 $em->flush();
134
135 $this->addFlash(
136 'notice',
137 'flashes.config.notice.tagging_rules_updated'
138 );
139
140 return $this->redirect($this->generateUrl('config') . '#set5');
141 }
142
143 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
144 'form' => [
145 'config' => $configForm->createView(),
146 'rss' => $rssForm->createView(),
147 'pwd' => $pwdForm->createView(),
148 'user' => $userForm->createView(),
149 'new_tagging_rule' => $newTaggingRule->createView(),
150 ],
151 'rss' => [
152 'username' => $user->getUsername(),
153 'token' => $config->getRssToken(),
154 ],
155 'twofactor_auth' => $this->getParameter('twofactor_auth'),
156 'wallabag_url' => $this->getParameter('domain_name'),
157 'enabled_users' => $this->get('wallabag_user.user_repository')->getSumEnabledUsers(),
158 ]);
159 }
160
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
269 /**
270 * @param Request $request
271 *
272 * @Route("/generate-token", name="generate_token")
273 *
274 * @return RedirectResponse|JsonResponse
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()) {
286 return new JsonResponse(['token' => $config->getRssToken()]);
287 }
288
289 $this->addFlash(
290 'notice',
291 'flashes.config.notice.rss_token_updated'
292 );
293
294 return $this->redirect($this->generateUrl('config') . '#set2');
295 }
296
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 *
304 * @return RedirectResponse
305 */
306 public function deleteTaggingRuleAction(TaggingRule $rule)
307 {
308 $this->validateRuleAction($rule);
309
310 $em = $this->getDoctrine()->getManager();
311 $em->remove($rule);
312 $em->flush();
313
314 $this->addFlash(
315 'notice',
316 'flashes.config.notice.tagging_rules_deleted'
317 );
318
319 return $this->redirect($this->generateUrl('config') . '#set5');
320 }
321
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)
332 {
333 $this->validateRuleAction($rule);
334
335 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
336 }
337
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 {
347 switch ($type) {
348 case 'annotations':
349 $this->getDoctrine()
350 ->getRepository('WallabagAnnotationBundle:Annotation')
351 ->removeAllByUserId($this->getUser()->getId());
352 break;
353 case 'tags':
354 $this->removeAllTagsByUserId($this->getUser()->getId());
355 break;
356 case 'entries':
357 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
358 // otherwise they won't be removed ...
359 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
360 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
361 }
362
363 // manually remove tags to avoid orphan tag
364 $this->removeAllTagsByUserId($this->getUser()->getId());
365
366 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
367 break;
368 case 'archived':
369 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
370 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
371 }
372
373 // manually remove tags to avoid orphan tag
374 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
375
376 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
377 break;
378 }
379
380 $this->addFlash(
381 'notice',
382 'flashes.config.notice.' . $type . '_reset'
383 );
384
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'));
439 }
440
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 {
453 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
454
455 if (0 === \count($errors)) {
456 $request->getSession()->set('_locale', $language);
457 }
458
459 return $this->redirect($request->headers->get('referer', $this->generateUrl('homepage')));
460 }
461
462 /**
463 * Remove all tags for given tags and a given user and cleanup orphan tags.
464 *
465 * @param array $tags
466 * @param int $userId
467 */
468 private function removeAllTagsByStatusAndUserId($tags, $userId)
469 {
470 if (empty($tags)) {
471 return;
472 }
473
474 $this->get('wallabag_core.entry_repository')
475 ->removeTags($userId, $tags);
476
477 // cleanup orphan tags
478 $em = $this->getDoctrine()->getManager();
479
480 foreach ($tags as $tag) {
481 if (0 === \count($tag->getEntries())) {
482 $em->remove($tag);
483 }
484 }
485
486 $em->flush();
487 }
488
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 {
496 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
497 $this->removeAllTagsByStatusAndUserId($tags, $userId);
498 }
499
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 {
507 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
508 $this->removeAllTagsByStatusAndUserId($tags, $userId);
509 }
510
511 private function removeAnnotationsForArchivedByUserId($userId)
512 {
513 $em = $this->getDoctrine()->getManager();
514
515 $archivedEntriesAnnotations = $this->getDoctrine()
516 ->getRepository('WallabagAnnotationBundle:Annotation')
517 ->findAllArchivedEntriesByUser($userId);
518
519 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
520 $em->remove($archivedEntriesAnnotation);
521 }
522
523 $em->flush();
524 }
525
526 /**
527 * Validate that a rule can be edited/deleted by the current user.
528 *
529 * @param TaggingRule $rule
530 */
531 private function validateRuleAction(TaggingRule $rule)
532 {
533 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
534 throw $this->createAccessDeniedException('You can not access this tagging rule.');
535 }
536 }
537
538 /**
539 * Retrieve config for the current user.
540 * If no config were found, create a new one.
541 *
542 * @return Config
543 */
544 private function getConfig()
545 {
546 $config = $this->getDoctrine()
547 ->getRepository('WallabagCoreBundle:Config')
548 ->findOneByUser($this->getUser());
549
550 // should NEVER HAPPEN ...
551 if (!$config) {
552 $config = new Config($this->getUser());
553 }
554
555 return $config;
556 }
557 }