]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Controller/ConfigController.php
Hash backup codes in the database using `password_hash`
[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 * @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->setRssToken(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->getRssToken()]);
292 }
293
294 $this->addFlash(
295 'notice',
296 'flashes.config.notice.rss_token_updated'
297 );
298
299 return $this->redirect($this->generateUrl('config') . '#set2');
300 }
301
302 /**
303 * Deletes a tagging rule and redirect to the config homepage.
304 *
305 * @param TaggingRule $rule
306 *
307 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
308 *
309 * @return RedirectResponse
310 */
311 public function deleteTaggingRuleAction(TaggingRule $rule)
312 {
313 $this->validateRuleAction($rule);
314
315 $em = $this->getDoctrine()->getManager();
316 $em->remove($rule);
317 $em->flush();
318
319 $this->addFlash(
320 'notice',
321 'flashes.config.notice.tagging_rules_deleted'
322 );
323
324 return $this->redirect($this->generateUrl('config') . '#set5');
325 }
326
327 /**
328 * Edit a tagging rule.
329 *
330 * @param TaggingRule $rule
331 *
332 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
333 *
334 * @return RedirectResponse
335 */
336 public function editTaggingRuleAction(TaggingRule $rule)
337 {
338 $this->validateRuleAction($rule);
339
340 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
341 }
342
343 /**
344 * Remove all annotations OR tags OR entries for the current user.
345 *
346 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
347 *
348 * @return RedirectResponse
349 */
350 public function resetAction($type)
351 {
352 switch ($type) {
353 case 'annotations':
354 $this->getDoctrine()
355 ->getRepository('WallabagAnnotationBundle:Annotation')
356 ->removeAllByUserId($this->getUser()->getId());
357 break;
358 case 'tags':
359 $this->removeAllTagsByUserId($this->getUser()->getId());
360 break;
361 case 'entries':
362 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
363 // otherwise they won't be removed ...
364 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
365 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
366 }
367
368 // manually remove tags to avoid orphan tag
369 $this->removeAllTagsByUserId($this->getUser()->getId());
370
371 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
372 break;
373 case 'archived':
374 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
375 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
376 }
377
378 // manually remove tags to avoid orphan tag
379 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
380
381 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
382 break;
383 }
384
385 $this->addFlash(
386 'notice',
387 'flashes.config.notice.' . $type . '_reset'
388 );
389
390 return $this->redirect($this->generateUrl('config') . '#set3');
391 }
392
393 /**
394 * Delete account for current user.
395 *
396 * @Route("/account/delete", name="delete_account")
397 *
398 * @param Request $request
399 *
400 * @throws AccessDeniedHttpException
401 *
402 * @return \Symfony\Component\HttpFoundation\RedirectResponse
403 */
404 public function deleteAccountAction(Request $request)
405 {
406 $enabledUsers = $this->get('wallabag_user.user_repository')
407 ->getSumEnabledUsers();
408
409 if ($enabledUsers <= 1) {
410 throw new AccessDeniedHttpException();
411 }
412
413 $user = $this->getUser();
414
415 // logout current user
416 $this->get('security.token_storage')->setToken(null);
417 $request->getSession()->invalidate();
418
419 $em = $this->get('fos_user.user_manager');
420 $em->deleteUser($user);
421
422 return $this->redirect($this->generateUrl('fos_user_security_login'));
423 }
424
425 /**
426 * Switch view mode for current user.
427 *
428 * @Route("/config/view-mode", name="switch_view_mode")
429 *
430 * @param Request $request
431 *
432 * @return \Symfony\Component\HttpFoundation\RedirectResponse
433 */
434 public function changeViewModeAction(Request $request)
435 {
436 $user = $this->getUser();
437 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
438
439 $em = $this->getDoctrine()->getManager();
440 $em->persist($user);
441 $em->flush();
442
443 return $this->redirect($request->headers->get('referer'));
444 }
445
446 /**
447 * Change the locale for the current user.
448 *
449 * @param Request $request
450 * @param string $language
451 *
452 * @Route("/locale/{language}", name="changeLocale")
453 *
454 * @return \Symfony\Component\HttpFoundation\RedirectResponse
455 */
456 public function setLocaleAction(Request $request, $language = null)
457 {
458 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
459
460 if (0 === \count($errors)) {
461 $request->getSession()->set('_locale', $language);
462 }
463
464 return $this->redirect($request->headers->get('referer', $this->generateUrl('homepage')));
465 }
466
467 /**
468 * Remove all tags for given tags and a given user and cleanup orphan tags.
469 *
470 * @param array $tags
471 * @param int $userId
472 */
473 private function removeAllTagsByStatusAndUserId($tags, $userId)
474 {
475 if (empty($tags)) {
476 return;
477 }
478
479 $this->get('wallabag_core.entry_repository')
480 ->removeTags($userId, $tags);
481
482 // cleanup orphan tags
483 $em = $this->getDoctrine()->getManager();
484
485 foreach ($tags as $tag) {
486 if (0 === \count($tag->getEntries())) {
487 $em->remove($tag);
488 }
489 }
490
491 $em->flush();
492 }
493
494 /**
495 * Remove all tags for a given user and cleanup orphan tags.
496 *
497 * @param int $userId
498 */
499 private function removeAllTagsByUserId($userId)
500 {
501 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
502 $this->removeAllTagsByStatusAndUserId($tags, $userId);
503 }
504
505 /**
506 * Remove all tags for a given user and cleanup orphan tags.
507 *
508 * @param int $userId
509 */
510 private function removeTagsForArchivedByUserId($userId)
511 {
512 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
513 $this->removeAllTagsByStatusAndUserId($tags, $userId);
514 }
515
516 private function removeAnnotationsForArchivedByUserId($userId)
517 {
518 $em = $this->getDoctrine()->getManager();
519
520 $archivedEntriesAnnotations = $this->getDoctrine()
521 ->getRepository('WallabagAnnotationBundle:Annotation')
522 ->findAllArchivedEntriesByUser($userId);
523
524 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
525 $em->remove($archivedEntriesAnnotation);
526 }
527
528 $em->flush();
529 }
530
531 /**
532 * Validate that a rule can be edited/deleted by the current user.
533 *
534 * @param TaggingRule $rule
535 */
536 private function validateRuleAction(TaggingRule $rule)
537 {
538 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
539 throw $this->createAccessDeniedException('You can not access this tagging rule.');
540 }
541 }
542
543 /**
544 * Retrieve config for the current user.
545 * If no config were found, create a new one.
546 *
547 * @return Config
548 */
549 private function getConfig()
550 {
551 $config = $this->getDoctrine()
552 ->getRepository('WallabagCoreBundle:Config')
553 ->findOneByUser($this->getUser());
554
555 // should NEVER HAPPEN ...
556 if (!$config) {
557 $config = new Config($this->getUser());
558 }
559
560 return $config;
561 }
562 }