]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Controller/ConfigController.php
Add ability to revoke feed token
[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\FeedType;
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 feed information
96 $feedForm = $this->createForm(FeedType::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
97 $feedForm->handleRequest($request);
98
99 if ($feedForm->isSubmitted() && $feedForm->isValid()) {
100 $em->persist($config);
101 $em->flush();
102
103 $this->addFlash(
104 'notice',
105 'flashes.config.notice.feed_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 'feed' => $feedForm->createView(),
147 'pwd' => $pwdForm->createView(),
148 'user' => $userForm->createView(),
149 'new_tagging_rule' => $newTaggingRule->createView(),
150 ],
151 'feed' => [
152 'username' => $user->getUsername(),
153 'token' => $config->getFeedToken(),
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 * @Route("/config/otp/email", name="config_otp_email")
165 */
166 public function otpEmailAction()
167 {
168 if (!$this->getParameter('twofactor_auth')) {
169 return $this->createNotFoundException('two_factor not enabled');
170 }
171
172 $user = $this->getUser();
173
174 $user->setGoogleAuthenticatorSecret(null);
175 $user->setBackupCodes(null);
176 $user->setEmailTwoFactor(true);
177
178 $this->container->get('fos_user.user_manager')->updateUser($user, true);
179
180 $this->addFlash(
181 'notice',
182 'flashes.config.notice.otp_enabled'
183 );
184
185 return $this->redirect($this->generateUrl('config') . '#set3');
186 }
187
188 /**
189 * Enable 2FA using OTP app, user will need to confirm the generated code from the app.
190 *
191 * @Route("/config/otp/app", name="config_otp_app")
192 */
193 public function otpAppAction()
194 {
195 if (!$this->getParameter('twofactor_auth')) {
196 return $this->createNotFoundException('two_factor not enabled');
197 }
198
199 $user = $this->getUser();
200 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
201
202 $user->setGoogleAuthenticatorSecret($secret);
203 $user->setEmailTwoFactor(false);
204
205 $backupCodes = (new BackupCodes())->toArray();
206 $backupCodesHashed = array_map(
207 function ($backupCode) {
208 return password_hash($backupCode, PASSWORD_DEFAULT);
209 },
210 $backupCodes
211 );
212
213 $user->setBackupCodes($backupCodesHashed);
214
215 $this->container->get('fos_user.user_manager')->updateUser($user, true);
216
217 return $this->render('WallabagCoreBundle:Config:otp_app.html.twig', [
218 'backupCodes' => $backupCodes,
219 'qr_code' => $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user),
220 ]);
221 }
222
223 /**
224 * Cancelling 2FA using OTP app.
225 *
226 * @Route("/config/otp/app/cancel", name="config_otp_app_cancel")
227 */
228 public function otpAppCancelAction()
229 {
230 if (!$this->getParameter('twofactor_auth')) {
231 return $this->createNotFoundException('two_factor not enabled');
232 }
233
234 $user = $this->getUser();
235 $user->setGoogleAuthenticatorSecret(null);
236 $user->setBackupCodes(null);
237
238 $this->container->get('fos_user.user_manager')->updateUser($user, true);
239
240 return $this->redirect($this->generateUrl('config') . '#set3');
241 }
242
243 /**
244 * Validate OTP code.
245 *
246 * @param Request $request
247 *
248 * @Route("/config/otp/app/check", name="config_otp_app_check")
249 */
250 public function otpAppCheckAction(Request $request)
251 {
252 $isValid = $this->get('scheb_two_factor.security.google_authenticator')->checkCode(
253 $this->getUser(),
254 $request->get('_auth_code')
255 );
256
257 if (true === $isValid) {
258 $this->addFlash(
259 'notice',
260 'flashes.config.notice.otp_enabled'
261 );
262
263 return $this->redirect($this->generateUrl('config') . '#set3');
264 }
265
266 $this->addFlash(
267 'two_factor',
268 'scheb_two_factor.code_invalid'
269 );
270
271 return $this->redirect($this->generateUrl('config_otp_app'));
272 }
273
274 /**
275 * @param Request $request
276 *
277 * @Route("/generate-token", name="generate_token")
278 *
279 * @return RedirectResponse|JsonResponse
280 */
281 public function generateTokenAction(Request $request)
282 {
283 $config = $this->getConfig();
284 $config->setFeedToken(Utils::generateToken());
285
286 $em = $this->getDoctrine()->getManager();
287 $em->persist($config);
288 $em->flush();
289
290 if ($request->isXmlHttpRequest()) {
291 return new JsonResponse(['token' => $config->getFeedToken()]);
292 }
293
294 $this->addFlash(
295 'notice',
296 'flashes.config.notice.feed_token_updated'
297 );
298
299 return $this->redirect($this->generateUrl('config') . '#set2');
300 }
301
302 /**
303 * @param Request $request
304 *
305 * @Route("/revoke-token", name="revoke_token")
306 *
307 * @return RedirectResponse|JsonResponse
308 */
309 public function revokeTokenAction(Request $request)
310 {
311 $config = $this->getConfig();
312 $config->setFeedToken(null);
313
314 $em = $this->getDoctrine()->getManager();
315 $em->persist($config);
316 $em->flush();
317
318 if ($request->isXmlHttpRequest()) {
319 return new JsonResponse();
320 }
321
322 $this->addFlash(
323 'notice',
324 'flashes.config.notice.feed_token_revoked'
325 );
326
327 return $this->redirect($this->generateUrl('config') . '#set2');
328 }
329
330 /**
331 * Deletes a tagging rule and redirect to the config homepage.
332 *
333 * @param TaggingRule $rule
334 *
335 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
336 *
337 * @return RedirectResponse
338 */
339 public function deleteTaggingRuleAction(TaggingRule $rule)
340 {
341 $this->validateRuleAction($rule);
342
343 $em = $this->getDoctrine()->getManager();
344 $em->remove($rule);
345 $em->flush();
346
347 $this->addFlash(
348 'notice',
349 'flashes.config.notice.tagging_rules_deleted'
350 );
351
352 return $this->redirect($this->generateUrl('config') . '#set5');
353 }
354
355 /**
356 * Edit a tagging rule.
357 *
358 * @param TaggingRule $rule
359 *
360 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
361 *
362 * @return RedirectResponse
363 */
364 public function editTaggingRuleAction(TaggingRule $rule)
365 {
366 $this->validateRuleAction($rule);
367
368 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
369 }
370
371 /**
372 * Remove all annotations OR tags OR entries for the current user.
373 *
374 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
375 *
376 * @return RedirectResponse
377 */
378 public function resetAction($type)
379 {
380 switch ($type) {
381 case 'annotations':
382 $this->getDoctrine()
383 ->getRepository('WallabagAnnotationBundle:Annotation')
384 ->removeAllByUserId($this->getUser()->getId());
385 break;
386 case 'tags':
387 $this->removeAllTagsByUserId($this->getUser()->getId());
388 break;
389 case 'entries':
390 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
391 // otherwise they won't be removed ...
392 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
393 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
394 }
395
396 // manually remove tags to avoid orphan tag
397 $this->removeAllTagsByUserId($this->getUser()->getId());
398
399 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
400 break;
401 case 'archived':
402 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
403 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
404 }
405
406 // manually remove tags to avoid orphan tag
407 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
408
409 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
410 break;
411 }
412
413 $this->addFlash(
414 'notice',
415 'flashes.config.notice.' . $type . '_reset'
416 );
417
418 return $this->redirect($this->generateUrl('config') . '#set3');
419 }
420
421 /**
422 * Delete account for current user.
423 *
424 * @Route("/account/delete", name="delete_account")
425 *
426 * @param Request $request
427 *
428 * @throws AccessDeniedHttpException
429 *
430 * @return \Symfony\Component\HttpFoundation\RedirectResponse
431 */
432 public function deleteAccountAction(Request $request)
433 {
434 $enabledUsers = $this->get('wallabag_user.user_repository')
435 ->getSumEnabledUsers();
436
437 if ($enabledUsers <= 1) {
438 throw new AccessDeniedHttpException();
439 }
440
441 $user = $this->getUser();
442
443 // logout current user
444 $this->get('security.token_storage')->setToken(null);
445 $request->getSession()->invalidate();
446
447 $em = $this->get('fos_user.user_manager');
448 $em->deleteUser($user);
449
450 return $this->redirect($this->generateUrl('fos_user_security_login'));
451 }
452
453 /**
454 * Switch view mode for current user.
455 *
456 * @Route("/config/view-mode", name="switch_view_mode")
457 *
458 * @param Request $request
459 *
460 * @return \Symfony\Component\HttpFoundation\RedirectResponse
461 */
462 public function changeViewModeAction(Request $request)
463 {
464 $user = $this->getUser();
465 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
466
467 $em = $this->getDoctrine()->getManager();
468 $em->persist($user);
469 $em->flush();
470
471 return $this->redirect($request->headers->get('referer'));
472 }
473
474 /**
475 * Change the locale for the current user.
476 *
477 * @param Request $request
478 * @param string $language
479 *
480 * @Route("/locale/{language}", name="changeLocale")
481 *
482 * @return \Symfony\Component\HttpFoundation\RedirectResponse
483 */
484 public function setLocaleAction(Request $request, $language = null)
485 {
486 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
487
488 if (0 === \count($errors)) {
489 $request->getSession()->set('_locale', $language);
490 }
491
492 return $this->redirect($request->headers->get('referer', $this->generateUrl('homepage')));
493 }
494
495 /**
496 * Remove all tags for given tags and a given user and cleanup orphan tags.
497 *
498 * @param array $tags
499 * @param int $userId
500 */
501 private function removeAllTagsByStatusAndUserId($tags, $userId)
502 {
503 if (empty($tags)) {
504 return;
505 }
506
507 $this->get('wallabag_core.entry_repository')
508 ->removeTags($userId, $tags);
509
510 // cleanup orphan tags
511 $em = $this->getDoctrine()->getManager();
512
513 foreach ($tags as $tag) {
514 if (0 === \count($tag->getEntries())) {
515 $em->remove($tag);
516 }
517 }
518
519 $em->flush();
520 }
521
522 /**
523 * Remove all tags for a given user and cleanup orphan tags.
524 *
525 * @param int $userId
526 */
527 private function removeAllTagsByUserId($userId)
528 {
529 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
530 $this->removeAllTagsByStatusAndUserId($tags, $userId);
531 }
532
533 /**
534 * Remove all tags for a given user and cleanup orphan tags.
535 *
536 * @param int $userId
537 */
538 private function removeTagsForArchivedByUserId($userId)
539 {
540 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
541 $this->removeAllTagsByStatusAndUserId($tags, $userId);
542 }
543
544 private function removeAnnotationsForArchivedByUserId($userId)
545 {
546 $em = $this->getDoctrine()->getManager();
547
548 $archivedEntriesAnnotations = $this->getDoctrine()
549 ->getRepository('WallabagAnnotationBundle:Annotation')
550 ->findAllArchivedEntriesByUser($userId);
551
552 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
553 $em->remove($archivedEntriesAnnotation);
554 }
555
556 $em->flush();
557 }
558
559 /**
560 * Validate that a rule can be edited/deleted by the current user.
561 *
562 * @param TaggingRule $rule
563 */
564 private function validateRuleAction(TaggingRule $rule)
565 {
566 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
567 throw $this->createAccessDeniedException('You can not access this tagging rule.');
568 }
569 }
570
571 /**
572 * Retrieve config for the current user.
573 * If no config were found, create a new one.
574 *
575 * @return Config
576 */
577 private function getConfig()
578 {
579 $config = $this->getDoctrine()
580 ->getRepository('WallabagCoreBundle:Config')
581 ->findOneByUser($this->getUser());
582
583 // should NEVER HAPPEN ...
584 if (!$config) {
585 $config = new Config($this->getUser());
586 }
587
588 return $config;
589 }
590 }