]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Controller/ConfigController.php
Add backup codes
[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
a6b242a1 84 // `googleTwoFactor` isn't a field within the User entity, we need to define it's value in a different way
2dfbe9e5 85 if ($this->getParameter('twofactor_auth') && true === $user->isGoogleAuthenticatorEnabled() && false === $userForm->isSubmitted()) {
a6b242a1
JB
86 $userForm->get('googleTwoFactor')->setData(true);
87 }
88
21e7ccef 89 if ($userForm->isSubmitted() && $userForm->isValid()) {
a6b242a1 90 // handle creation / reset of the OTP secret if checkbox changed from the previous state
2dfbe9e5
JB
91 if ($this->getParameter('twofactor_auth')) {
92 if (true === $userForm->get('googleTwoFactor')->getData() && false === $user->isGoogleAuthenticatorEnabled()) {
93 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
a6b242a1 94
2dfbe9e5
JB
95 $user->setGoogleAuthenticatorSecret($secret);
96 $user->setEmailTwoFactor(false);
dfd0a7bc 97 $user->setBackupCodes((new BackupCodes())->toArray());
a6b242a1 98
2dfbe9e5
JB
99 $this->addFlash('OtpQrCode', $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user));
100 } elseif (false === $userForm->get('googleTwoFactor')->getData() && true === $user->isGoogleAuthenticatorEnabled()) {
101 $user->setGoogleAuthenticatorSecret(null);
dfd0a7bc 102 $user->setBackupCodes(null);
2dfbe9e5 103 }
a6b242a1
JB
104 }
105
fcb1fba5 106 $userManager->updateUser($user, true);
c0d9eba0 107
a6b242a1 108 $this->addFlash(
c0d9eba0 109 'notice',
4204a06b 110 'flashes.config.notice.user_updated'
c0d9eba0
J
111 );
112
f808b016 113 return $this->redirect($this->generateUrl('config') . '#set3');
c0d9eba0
J
114 }
115
0c83fd59 116 // handle rss information
f808b016 117 $rssForm = $this->createForm(RssType::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
0c83fd59
J
118 $rssForm->handleRequest($request);
119
21e7ccef 120 if ($rssForm->isSubmitted() && $rssForm->isValid()) {
0c83fd59
J
121 $em->persist($config);
122 $em->flush();
123
a6b242a1 124 $this->addFlash(
0c83fd59 125 'notice',
4204a06b 126 'flashes.config.notice.rss_updated'
0c83fd59
J
127 );
128
f808b016 129 return $this->redirect($this->generateUrl('config') . '#set2');
0c83fd59
J
130 }
131
f19f9f62
KG
132 // handle tagging rule
133 $taggingRule = new TaggingRule();
f808b016 134 $action = $this->generateUrl('config') . '#set5';
bf3dc999
JB
135
136 if ($request->query->has('tagging-rule')) {
137 $taggingRule = $this->getDoctrine()
138 ->getRepository('WallabagCoreBundle:TaggingRule')
139 ->find($request->query->get('tagging-rule'));
140
141 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
142 return $this->redirect($action);
143 }
144
f808b016 145 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
bf3dc999
JB
146 }
147
148 $newTaggingRule = $this->createForm(TaggingRuleType::class, $taggingRule, ['action' => $action]);
f19f9f62
KG
149 $newTaggingRule->handleRequest($request);
150
21e7ccef 151 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
f19f9f62
KG
152 $taggingRule->setConfig($config);
153 $em->persist($taggingRule);
154 $em->flush();
155
a6b242a1 156 $this->addFlash(
f19f9f62 157 'notice',
4204a06b 158 'flashes.config.notice.tagging_rules_updated'
f19f9f62
KG
159 );
160
f808b016 161 return $this->redirect($this->generateUrl('config') . '#set5');
f19f9f62
KG
162 }
163
4094ea47
JB
164 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
165 'form' => [
0c83fd59
J
166 'config' => $configForm->createView(),
167 'rss' => $rssForm->createView(),
168 'pwd' => $pwdForm->createView(),
169 'user' => $userForm->createView(),
f19f9f62 170 'new_tagging_rule' => $newTaggingRule->createView(),
4094ea47
JB
171 ],
172 'rss' => [
0c83fd59
J
173 'username' => $user->getUsername(),
174 'token' => $config->getRssToken(),
4094ea47 175 ],
63e40f2d 176 'twofactor_auth' => $this->getParameter('twofactor_auth'),
be9d693e 177 'wallabag_url' => $this->getParameter('domain_name'),
25203e50 178 'enabled_users' => $this->get('wallabag_user.user_repository')
bb0c78f4 179 ->getSumEnabledUsers(),
4094ea47 180 ]);
4d85d7e9
J
181 }
182
0c83fd59
J
183 /**
184 * @param Request $request
185 *
186 * @Route("/generate-token", name="generate_token")
187 *
98568055 188 * @return RedirectResponse|JsonResponse
0c83fd59
J
189 */
190 public function generateTokenAction(Request $request)
191 {
192 $config = $this->getConfig();
193 $config->setRssToken(Utils::generateToken());
194
195 $em = $this->getDoctrine()->getManager();
196 $em->persist($config);
197 $em->flush();
198
199 if ($request->isXmlHttpRequest()) {
4094ea47 200 return new JsonResponse(['token' => $config->getRssToken()]);
0c83fd59
J
201 }
202
a6b242a1 203 $this->addFlash(
c7a4f74f 204 'notice',
4204a06b 205 'flashes.config.notice.rss_token_updated'
c7a4f74f
JB
206 );
207
f808b016 208 return $this->redirect($this->generateUrl('config') . '#set2');
0c83fd59
J
209 }
210
52e423f3
KG
211 /**
212 * Deletes a tagging rule and redirect to the config homepage.
213 *
214 * @param TaggingRule $rule
215 *
216 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
217 *
98568055 218 * @return RedirectResponse
52e423f3 219 */
5f8a7857 220 public function deleteTaggingRuleAction(TaggingRule $rule)
52e423f3 221 {
8799bde0 222 $this->validateRuleAction($rule);
52e423f3
KG
223
224 $em = $this->getDoctrine()->getManager();
225 $em->remove($rule);
226 $em->flush();
227
a6b242a1 228 $this->addFlash(
52e423f3 229 'notice',
4204a06b 230 'flashes.config.notice.tagging_rules_deleted'
52e423f3
KG
231 );
232
f808b016 233 return $this->redirect($this->generateUrl('config') . '#set5');
52e423f3
KG
234 }
235
bf3dc999
JB
236 /**
237 * Edit a tagging rule.
238 *
239 * @param TaggingRule $rule
240 *
241 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
242 *
243 * @return RedirectResponse
244 */
245 public function editTaggingRuleAction(TaggingRule $rule)
8799bde0
JB
246 {
247 $this->validateRuleAction($rule);
248
f808b016 249 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
8799bde0
JB
250 }
251
206bade5
JB
252 /**
253 * Remove all annotations OR tags OR entries for the current user.
254 *
255 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
256 *
257 * @return RedirectResponse
258 */
259 public function resetAction($type)
260 {
206bade5
JB
261 switch ($type) {
262 case 'annotations':
191564b7
JB
263 $this->getDoctrine()
264 ->getRepository('WallabagAnnotationBundle:Annotation')
265 ->removeAllByUserId($this->getUser()->getId());
206bade5 266 break;
206bade5 267 case 'tags':
191564b7
JB
268 $this->removeAllTagsByUserId($this->getUser()->getId());
269 break;
191564b7 270 case 'entries':
6da1aebc 271 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
191564b7 272 // otherwise they won't be removed ...
7ab5eb95 273 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
191564b7 274 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
206bade5
JB
275 }
276
8c61fd12 277 // manually remove tags to avoid orphan tag
f71e55ac
JB
278 $this->removeAllTagsByUserId($this->getUser()->getId());
279
25203e50 280 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
6da1aebc
TC
281 break;
282 case 'archived':
7ab5eb95 283 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
6da1aebc
TC
284 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
285 }
286
287 // manually remove tags to avoid orphan tag
288 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
289
25203e50 290 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
6da1aebc 291 break;
206bade5
JB
292 }
293
a6b242a1 294 $this->addFlash(
206bade5 295 'notice',
f808b016 296 'flashes.config.notice.' . $type . '_reset'
206bade5
JB
297 );
298
f808b016
JB
299 return $this->redirect($this->generateUrl('config') . '#set3');
300 }
301
302 /**
303 * Delete account for current user.
304 *
305 * @Route("/account/delete", name="delete_account")
306 *
307 * @param Request $request
308 *
309 * @throws AccessDeniedHttpException
310 *
311 * @return \Symfony\Component\HttpFoundation\RedirectResponse
312 */
313 public function deleteAccountAction(Request $request)
314 {
315 $enabledUsers = $this->get('wallabag_user.user_repository')
316 ->getSumEnabledUsers();
317
318 if ($enabledUsers <= 1) {
319 throw new AccessDeniedHttpException();
320 }
321
322 $user = $this->getUser();
323
324 // logout current user
325 $this->get('security.token_storage')->setToken(null);
326 $request->getSession()->invalidate();
327
328 $em = $this->get('fos_user.user_manager');
329 $em->deleteUser($user);
330
331 return $this->redirect($this->generateUrl('fos_user_security_login'));
332 }
333
334 /**
335 * Switch view mode for current user.
336 *
337 * @Route("/config/view-mode", name="switch_view_mode")
338 *
339 * @param Request $request
340 *
341 * @return \Symfony\Component\HttpFoundation\RedirectResponse
342 */
343 public function changeViewModeAction(Request $request)
344 {
345 $user = $this->getUser();
346 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
347
348 $em = $this->getDoctrine()->getManager();
349 $em->persist($user);
350 $em->flush();
351
352 return $this->redirect($request->headers->get('referer'));
206bade5
JB
353 }
354
be417ef2
NL
355 /**
356 * Change the locale for the current user.
357 *
358 * @param Request $request
359 * @param string $language
360 *
361 * @Route("/locale/{language}", name="changeLocale")
362 *
363 * @return \Symfony\Component\HttpFoundation\RedirectResponse
364 */
365 public function setLocaleAction(Request $request, $language = null)
366 {
4d4147b2
JB
367 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
368
369 if (0 === \count($errors)) {
370 $request->getSession()->set('_locale', $language);
be417ef2
NL
371 }
372
4d4147b2 373 return $this->redirect($request->headers->get('referer', $this->generateUrl('homepage')));
be417ef2
NL
374 }
375
191564b7 376 /**
e682a70f 377 * Remove all tags for given tags and a given user and cleanup orphan tags.
191564b7 378 *
e682a70f
NL
379 * @param array $tags
380 * @param int $userId
191564b7 381 */
e682a70f 382 private function removeAllTagsByStatusAndUserId($tags, $userId)
191564b7 383 {
191564b7
JB
384 if (empty($tags)) {
385 return;
386 }
387
25203e50 388 $this->get('wallabag_core.entry_repository')
191564b7 389 ->removeTags($userId, $tags);
f71e55ac 390
8c61fd12 391 // cleanup orphan tags
f71e55ac
JB
392 $em = $this->getDoctrine()->getManager();
393
394 foreach ($tags as $tag) {
2a1ceb67 395 if (0 === \count($tag->getEntries())) {
f71e55ac
JB
396 $em->remove($tag);
397 }
398 }
399
400 $em->flush();
191564b7
JB
401 }
402
e682a70f
NL
403 /**
404 * Remove all tags for a given user and cleanup orphan tags.
405 *
406 * @param int $userId
407 */
408 private function removeAllTagsByUserId($userId)
409 {
25203e50 410 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
e682a70f
NL
411 $this->removeAllTagsByStatusAndUserId($tags, $userId);
412 }
413
6da1aebc
TC
414 /**
415 * Remove all tags for a given user and cleanup orphan tags.
416 *
417 * @param int $userId
418 */
419 private function removeTagsForArchivedByUserId($userId)
420 {
25203e50 421 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
e682a70f 422 $this->removeAllTagsByStatusAndUserId($tags, $userId);
6da1aebc
TC
423 }
424
425 private function removeAnnotationsForArchivedByUserId($userId)
426 {
427 $em = $this->getDoctrine()->getManager();
428
429 $archivedEntriesAnnotations = $this->getDoctrine()
430 ->getRepository('WallabagAnnotationBundle:Annotation')
13a592a1 431 ->findAllArchivedEntriesByUser($userId);
6da1aebc
TC
432
433 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
434 $em->remove($archivedEntriesAnnotation);
435 }
436
437 $em->flush();
438 }
439
8799bde0 440 /**
2455472e 441 * Validate that a rule can be edited/deleted by the current user.
8799bde0 442 *
2455472e 443 * @param TaggingRule $rule
8799bde0
JB
444 */
445 private function validateRuleAction(TaggingRule $rule)
bf3dc999 446 {
f808b016 447 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
bf3dc999
JB
448 throw $this->createAccessDeniedException('You can not access this tagging rule.');
449 }
bf3dc999
JB
450 }
451
d9085c63
J
452 /**
453 * Retrieve config for the current user.
454 * If no config were found, create a new one.
455 *
4094ea47 456 * @return Config
d9085c63 457 */
4d85d7e9
J
458 private function getConfig()
459 {
460 $config = $this->getDoctrine()
461 ->getRepository('WallabagCoreBundle:Config')
462 ->findOneByUser($this->getUser());
463
ca17abce 464 // should NEVER HAPPEN ...
4d85d7e9
J
465 if (!$config) {
466 $config = new Config($this->getUser());
467 }
468
469 return $config;
470 }
471}