]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Controller/ConfigController.php
Enable OTP 2FA
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Controller / ConfigController.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Controller;
4
5 use Symfony\Bundle\FrameworkBundle\Controller\Controller;
6 use Symfony\Component\HttpFoundation\JsonResponse;
7 use Symfony\Component\HttpFoundation\RedirectResponse;
8 use Symfony\Component\HttpFoundation\Request;
9 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
10 use Symfony\Component\Routing\Annotation\Route;
11 use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint;
12 use Wallabag\CoreBundle\Entity\Config;
13 use Wallabag\CoreBundle\Entity\TaggingRule;
14 use Wallabag\CoreBundle\Form\Type\ChangePasswordType;
15 use Wallabag\CoreBundle\Form\Type\ConfigType;
16 use Wallabag\CoreBundle\Form\Type\RssType;
17 use Wallabag\CoreBundle\Form\Type\TaggingRuleType;
18 use Wallabag\CoreBundle\Form\Type\UserInformationType;
19 use Wallabag\CoreBundle\Tools\Utils;
20
21 class ConfigController extends Controller
22 {
23 /**
24 * @param Request $request
25 *
26 * @Route("/config", name="config")
27 */
28 public function indexAction(Request $request)
29 {
30 $em = $this->getDoctrine()->getManager();
31 $config = $this->getConfig();
32 $userManager = $this->container->get('fos_user.user_manager');
33 $user = $this->getUser();
34
35 // handle basic config detail (this form is defined as a service)
36 $configForm = $this->createForm(ConfigType::class, $config, ['action' => $this->generateUrl('config')]);
37 $configForm->handleRequest($request);
38
39 if ($configForm->isSubmitted() && $configForm->isValid()) {
40 $em->persist($config);
41 $em->flush();
42
43 $request->getSession()->set('_locale', $config->getLanguage());
44
45 // switch active theme
46 $activeTheme = $this->get('liip_theme.active_theme');
47 $activeTheme->setName($config->getTheme());
48
49 $this->addFlash(
50 'notice',
51 'flashes.config.notice.config_saved'
52 );
53
54 return $this->redirect($this->generateUrl('config'));
55 }
56
57 // handle changing password
58 $pwdForm = $this->createForm(ChangePasswordType::class, null, ['action' => $this->generateUrl('config') . '#set4']);
59 $pwdForm->handleRequest($request);
60
61 if ($pwdForm->isSubmitted() && $pwdForm->isValid()) {
62 if ($this->get('craue_config')->get('demo_mode_enabled') && $this->get('craue_config')->get('demo_mode_username') === $user->getUsername()) {
63 $message = 'flashes.config.notice.password_not_updated_demo';
64 } else {
65 $message = 'flashes.config.notice.password_updated';
66
67 $user->setPlainPassword($pwdForm->get('new_password')->getData());
68 $userManager->updateUser($user, true);
69 }
70
71 $this->addFlash('notice', $message);
72
73 return $this->redirect($this->generateUrl('config') . '#set4');
74 }
75
76 // handle changing user information
77 $userForm = $this->createForm(UserInformationType::class, $user, [
78 'validation_groups' => ['Profile'],
79 'action' => $this->generateUrl('config') . '#set3',
80 ]);
81 $userForm->handleRequest($request);
82
83 // `googleTwoFactor` isn't a field within the User entity, we need to define it's value in a different way
84 if (true === $user->isGoogleAuthenticatorEnabled() && false === $userForm->isSubmitted()) {
85 $userForm->get('googleTwoFactor')->setData(true);
86 }
87
88 if ($userForm->isSubmitted() && $userForm->isValid()) {
89 // handle creation / reset of the OTP secret if checkbox changed from the previous state
90 if (true === $userForm->get('googleTwoFactor')->getData() && false === $user->isGoogleAuthenticatorEnabled()) {
91 $secret = $this->get('scheb_two_factor.security.google_authenticator')->generateSecret();
92
93 $user->setGoogleAuthenticatorSecret($secret);
94 $user->setEmailTwoFactor(false);
95
96 $qrCode = $this->get('scheb_two_factor.security.google_authenticator')->getQRContent($user);
97
98 $this->addFlash('OTPSecret', ['code' => $secret, 'qrCode' => $qrCode]);
99 } elseif (false === $userForm->get('googleTwoFactor')->getData() && true === $user->isGoogleAuthenticatorEnabled()) {
100 $user->setGoogleAuthenticatorSecret(null);
101 }
102
103 $userManager->updateUser($user, true);
104
105 $this->addFlash(
106 'notice',
107 'flashes.config.notice.user_updated'
108 );
109
110 return $this->redirect($this->generateUrl('config') . '#set3');
111 }
112
113 // handle rss information
114 $rssForm = $this->createForm(RssType::class, $config, ['action' => $this->generateUrl('config') . '#set2']);
115 $rssForm->handleRequest($request);
116
117 if ($rssForm->isSubmitted() && $rssForm->isValid()) {
118 $em->persist($config);
119 $em->flush();
120
121 $this->addFlash(
122 'notice',
123 'flashes.config.notice.rss_updated'
124 );
125
126 return $this->redirect($this->generateUrl('config') . '#set2');
127 }
128
129 // handle tagging rule
130 $taggingRule = new TaggingRule();
131 $action = $this->generateUrl('config') . '#set5';
132
133 if ($request->query->has('tagging-rule')) {
134 $taggingRule = $this->getDoctrine()
135 ->getRepository('WallabagCoreBundle:TaggingRule')
136 ->find($request->query->get('tagging-rule'));
137
138 if ($this->getUser()->getId() !== $taggingRule->getConfig()->getUser()->getId()) {
139 return $this->redirect($action);
140 }
141
142 $action = $this->generateUrl('config') . '?tagging-rule=' . $taggingRule->getId() . '#set5';
143 }
144
145 $newTaggingRule = $this->createForm(TaggingRuleType::class, $taggingRule, ['action' => $action]);
146 $newTaggingRule->handleRequest($request);
147
148 if ($newTaggingRule->isSubmitted() && $newTaggingRule->isValid()) {
149 $taggingRule->setConfig($config);
150 $em->persist($taggingRule);
151 $em->flush();
152
153 $this->addFlash(
154 'notice',
155 'flashes.config.notice.tagging_rules_updated'
156 );
157
158 return $this->redirect($this->generateUrl('config') . '#set5');
159 }
160
161 return $this->render('WallabagCoreBundle:Config:index.html.twig', [
162 'form' => [
163 'config' => $configForm->createView(),
164 'rss' => $rssForm->createView(),
165 'pwd' => $pwdForm->createView(),
166 'user' => $userForm->createView(),
167 'new_tagging_rule' => $newTaggingRule->createView(),
168 ],
169 'rss' => [
170 'username' => $user->getUsername(),
171 'token' => $config->getRssToken(),
172 ],
173 'twofactor_auth' => $this->getParameter('twofactor_auth'),
174 'wallabag_url' => $this->getParameter('domain_name'),
175 'enabled_users' => $this->get('wallabag_user.user_repository')
176 ->getSumEnabledUsers(),
177 ]);
178 }
179
180 /**
181 * @param Request $request
182 *
183 * @Route("/generate-token", name="generate_token")
184 *
185 * @return RedirectResponse|JsonResponse
186 */
187 public function generateTokenAction(Request $request)
188 {
189 $config = $this->getConfig();
190 $config->setRssToken(Utils::generateToken());
191
192 $em = $this->getDoctrine()->getManager();
193 $em->persist($config);
194 $em->flush();
195
196 if ($request->isXmlHttpRequest()) {
197 return new JsonResponse(['token' => $config->getRssToken()]);
198 }
199
200 $this->addFlash(
201 'notice',
202 'flashes.config.notice.rss_token_updated'
203 );
204
205 return $this->redirect($this->generateUrl('config') . '#set2');
206 }
207
208 /**
209 * Deletes a tagging rule and redirect to the config homepage.
210 *
211 * @param TaggingRule $rule
212 *
213 * @Route("/tagging-rule/delete/{id}", requirements={"id" = "\d+"}, name="delete_tagging_rule")
214 *
215 * @return RedirectResponse
216 */
217 public function deleteTaggingRuleAction(TaggingRule $rule)
218 {
219 $this->validateRuleAction($rule);
220
221 $em = $this->getDoctrine()->getManager();
222 $em->remove($rule);
223 $em->flush();
224
225 $this->addFlash(
226 'notice',
227 'flashes.config.notice.tagging_rules_deleted'
228 );
229
230 return $this->redirect($this->generateUrl('config') . '#set5');
231 }
232
233 /**
234 * Edit a tagging rule.
235 *
236 * @param TaggingRule $rule
237 *
238 * @Route("/tagging-rule/edit/{id}", requirements={"id" = "\d+"}, name="edit_tagging_rule")
239 *
240 * @return RedirectResponse
241 */
242 public function editTaggingRuleAction(TaggingRule $rule)
243 {
244 $this->validateRuleAction($rule);
245
246 return $this->redirect($this->generateUrl('config') . '?tagging-rule=' . $rule->getId() . '#set5');
247 }
248
249 /**
250 * Remove all annotations OR tags OR entries for the current user.
251 *
252 * @Route("/reset/{type}", requirements={"id" = "annotations|tags|entries"}, name="config_reset")
253 *
254 * @return RedirectResponse
255 */
256 public function resetAction($type)
257 {
258 switch ($type) {
259 case 'annotations':
260 $this->getDoctrine()
261 ->getRepository('WallabagAnnotationBundle:Annotation')
262 ->removeAllByUserId($this->getUser()->getId());
263 break;
264 case 'tags':
265 $this->removeAllTagsByUserId($this->getUser()->getId());
266 break;
267 case 'entries':
268 // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff
269 // otherwise they won't be removed ...
270 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
271 $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId());
272 }
273
274 // manually remove tags to avoid orphan tag
275 $this->removeAllTagsByUserId($this->getUser()->getId());
276
277 $this->get('wallabag_core.entry_repository')->removeAllByUserId($this->getUser()->getId());
278 break;
279 case 'archived':
280 if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) {
281 $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId());
282 }
283
284 // manually remove tags to avoid orphan tag
285 $this->removeTagsForArchivedByUserId($this->getUser()->getId());
286
287 $this->get('wallabag_core.entry_repository')->removeArchivedByUserId($this->getUser()->getId());
288 break;
289 }
290
291 $this->addFlash(
292 'notice',
293 'flashes.config.notice.' . $type . '_reset'
294 );
295
296 return $this->redirect($this->generateUrl('config') . '#set3');
297 }
298
299 /**
300 * Delete account for current user.
301 *
302 * @Route("/account/delete", name="delete_account")
303 *
304 * @param Request $request
305 *
306 * @throws AccessDeniedHttpException
307 *
308 * @return \Symfony\Component\HttpFoundation\RedirectResponse
309 */
310 public function deleteAccountAction(Request $request)
311 {
312 $enabledUsers = $this->get('wallabag_user.user_repository')
313 ->getSumEnabledUsers();
314
315 if ($enabledUsers <= 1) {
316 throw new AccessDeniedHttpException();
317 }
318
319 $user = $this->getUser();
320
321 // logout current user
322 $this->get('security.token_storage')->setToken(null);
323 $request->getSession()->invalidate();
324
325 $em = $this->get('fos_user.user_manager');
326 $em->deleteUser($user);
327
328 return $this->redirect($this->generateUrl('fos_user_security_login'));
329 }
330
331 /**
332 * Switch view mode for current user.
333 *
334 * @Route("/config/view-mode", name="switch_view_mode")
335 *
336 * @param Request $request
337 *
338 * @return \Symfony\Component\HttpFoundation\RedirectResponse
339 */
340 public function changeViewModeAction(Request $request)
341 {
342 $user = $this->getUser();
343 $user->getConfig()->setListMode(!$user->getConfig()->getListMode());
344
345 $em = $this->getDoctrine()->getManager();
346 $em->persist($user);
347 $em->flush();
348
349 return $this->redirect($request->headers->get('referer'));
350 }
351
352 /**
353 * Change the locale for the current user.
354 *
355 * @param Request $request
356 * @param string $language
357 *
358 * @Route("/locale/{language}", name="changeLocale")
359 *
360 * @return \Symfony\Component\HttpFoundation\RedirectResponse
361 */
362 public function setLocaleAction(Request $request, $language = null)
363 {
364 $errors = $this->get('validator')->validate($language, (new LocaleConstraint()));
365
366 if (0 === \count($errors)) {
367 $request->getSession()->set('_locale', $language);
368 }
369
370 return $this->redirect($request->headers->get('referer', $this->generateUrl('homepage')));
371 }
372
373 /**
374 * Remove all tags for given tags and a given user and cleanup orphan tags.
375 *
376 * @param array $tags
377 * @param int $userId
378 */
379 private function removeAllTagsByStatusAndUserId($tags, $userId)
380 {
381 if (empty($tags)) {
382 return;
383 }
384
385 $this->get('wallabag_core.entry_repository')
386 ->removeTags($userId, $tags);
387
388 // cleanup orphan tags
389 $em = $this->getDoctrine()->getManager();
390
391 foreach ($tags as $tag) {
392 if (0 === \count($tag->getEntries())) {
393 $em->remove($tag);
394 }
395 }
396
397 $em->flush();
398 }
399
400 /**
401 * Remove all tags for a given user and cleanup orphan tags.
402 *
403 * @param int $userId
404 */
405 private function removeAllTagsByUserId($userId)
406 {
407 $tags = $this->get('wallabag_core.tag_repository')->findAllTags($userId);
408 $this->removeAllTagsByStatusAndUserId($tags, $userId);
409 }
410
411 /**
412 * Remove all tags for a given user and cleanup orphan tags.
413 *
414 * @param int $userId
415 */
416 private function removeTagsForArchivedByUserId($userId)
417 {
418 $tags = $this->get('wallabag_core.tag_repository')->findForArchivedArticlesByUser($userId);
419 $this->removeAllTagsByStatusAndUserId($tags, $userId);
420 }
421
422 private function removeAnnotationsForArchivedByUserId($userId)
423 {
424 $em = $this->getDoctrine()->getManager();
425
426 $archivedEntriesAnnotations = $this->getDoctrine()
427 ->getRepository('WallabagAnnotationBundle:Annotation')
428 ->findAllArchivedEntriesByUser($userId);
429
430 foreach ($archivedEntriesAnnotations as $archivedEntriesAnnotation) {
431 $em->remove($archivedEntriesAnnotation);
432 }
433
434 $em->flush();
435 }
436
437 /**
438 * Validate that a rule can be edited/deleted by the current user.
439 *
440 * @param TaggingRule $rule
441 */
442 private function validateRuleAction(TaggingRule $rule)
443 {
444 if ($this->getUser()->getId() !== $rule->getConfig()->getUser()->getId()) {
445 throw $this->createAccessDeniedException('You can not access this tagging rule.');
446 }
447 }
448
449 /**
450 * Retrieve config for the current user.
451 * If no config were found, create a new one.
452 *
453 * @return Config
454 */
455 private function getConfig()
456 {
457 $config = $this->getDoctrine()
458 ->getRepository('WallabagCoreBundle:Config')
459 ->findOneByUser($this->getUser());
460
461 // should NEVER HAPPEN ...
462 if (!$config) {
463 $config = new Config($this->getUser());
464 }
465
466 return $config;
467 }
468 }