UserController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. <?php
  2. /*
  3. * This file is part of Packagist.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. * Nils Adermann <naderman@naderman.de>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Packagist\WebBundle\Controller;
  12. use Doctrine\ORM\NoResultException;
  13. use FOS\UserBundle\Model\UserInterface;
  14. use Packagist\WebBundle\Entity\Job;
  15. use Packagist\WebBundle\Entity\Package;
  16. use Packagist\WebBundle\Entity\Version;
  17. use Packagist\WebBundle\Entity\User;
  18. use Packagist\WebBundle\Entity\VersionRepository;
  19. use Packagist\WebBundle\Form\Model\EnableTwoFactorRequest;
  20. use Packagist\WebBundle\Form\Type\EnableTwoFactorAuthType;
  21. use Packagist\WebBundle\Model\RedisAdapter;
  22. use Packagist\WebBundle\Security\TwoFactorAuthManager;
  23. use Pagerfanta\Adapter\DoctrineORMAdapter;
  24. use Pagerfanta\Pagerfanta;
  25. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  26. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  27. use Symfony\Component\Form\FormError;
  28. use Symfony\Component\HttpFoundation\Request;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  31. use Symfony\Component\Routing\Annotation\Route;
  32. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  33. /**
  34. * @author Jordi Boggiano <j.boggiano@seld.be>
  35. */
  36. class UserController extends Controller
  37. {
  38. /**
  39. * @Template()
  40. * @Route("/users/{name}/packages/", name="user_packages")
  41. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  42. */
  43. public function packagesAction(Request $req, User $user)
  44. {
  45. $packages = $this->getUserPackages($req, $user);
  46. return array(
  47. 'packages' => $packages,
  48. 'meta' => $this->getPackagesMetadata($packages),
  49. 'user' => $user,
  50. );
  51. }
  52. /**
  53. * @Route("/trigger-github-sync/", name="user_github_sync")
  54. */
  55. public function triggerGitHubSyncAction()
  56. {
  57. $user = $this->getUser();
  58. if (!$user) {
  59. throw new AccessDeniedException();
  60. }
  61. if (!$user->getGithubToken()) {
  62. $this->get('session')->getFlashBag()->set('error', 'You must connect your user account to github to sync packages.');
  63. return $this->redirectToRoute('fos_user_profile_show');
  64. }
  65. if (!$user->getGithubScope()) {
  66. $this->get('session')->getFlashBag()->set('error', 'Please log out and log in with GitHub again to make sure the correct GitHub permissions are granted.');
  67. return $this->redirectToRoute('fos_user_profile_show');
  68. }
  69. $this->get('scheduler')->scheduleUserScopeMigration($user->getId(), '', $user->getGithubScope());
  70. sleep(5);
  71. $this->get('session')->getFlashBag()->set('success', 'User sync scheduled. It might take a few seconds to run through, make sure you refresh then to check if any packages still need sync.');
  72. return $this->redirectToRoute('fos_user_profile_show');
  73. }
  74. /**
  75. * @Route("/spammers/{name}/", name="mark_spammer", methods={"POST"})
  76. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  77. */
  78. public function markSpammerAction(Request $req, User $user)
  79. {
  80. if (!$this->isGranted('ROLE_ANTISPAM')) {
  81. throw new AccessDeniedException('This user can not mark others as spammers');
  82. }
  83. $form = $this->createFormBuilder(array())->getForm();
  84. $form->submit($req->request->get('form'));
  85. if ($form->isValid()) {
  86. $user->addRole('ROLE_SPAMMER');
  87. $user->setEnabled(false);
  88. $this->get('fos_user.user_manager')->updateUser($user);
  89. $doctrine = $this->getDoctrine();
  90. $doctrine->getConnection()->executeUpdate(
  91. 'UPDATE package p JOIN maintainers_packages mp ON mp.package_id = p.id
  92. SET abandoned = 1, replacementPackage = "spam/spam", suspect = "spam", indexedAt = NULL, dumpedAt = "2100-01-01 00:00:00"
  93. WHERE mp.user_id = :userId',
  94. ['userId' => $user->getId()]
  95. );
  96. /** @var VersionRepository $versionRepo */
  97. $versionRepo = $doctrine->getRepository(Version::class);
  98. $packages = $doctrine
  99. ->getRepository(Package::class)
  100. ->getFilteredQueryBuilder(array('maintainer' => $user->getId()), true)
  101. ->getQuery()->getResult();
  102. $providerManager = $this->get('packagist.provider_manager');
  103. foreach ($packages as $package) {
  104. foreach ($package->getVersions() as $version) {
  105. $versionRepo->remove($version);
  106. }
  107. $providerManager->deletePackage($package);
  108. }
  109. $this->getDoctrine()->getManager()->flush();
  110. $this->get('session')->getFlashBag()->set('success', $user->getUsername().' has been marked as a spammer');
  111. }
  112. return $this->redirect(
  113. $this->generateUrl("user_profile", array("name" => $user->getUsername()))
  114. );
  115. }
  116. /**
  117. * @param Request $req
  118. * @return Response
  119. */
  120. public function viewProfileAction(Request $req)
  121. {
  122. $user = $this->container->get('security.token_storage')->getToken()->getUser();
  123. if (!is_object($user) || !$user instanceof UserInterface) {
  124. throw new AccessDeniedException('This user does not have access to this section.');
  125. }
  126. $packages = $this->getUserPackages($req, $user);
  127. $lastGithubSync = $this->getDoctrine()->getRepository(Job::class)->getLastGitHubSyncJob($user->getId());
  128. $data = array(
  129. 'packages' => $packages,
  130. 'meta' => $this->getPackagesMetadata($packages),
  131. 'user' => $user,
  132. 'githubSync' => $lastGithubSync,
  133. );
  134. if (!count($packages)) {
  135. $data['deleteForm'] = $this->createFormBuilder(array())->getForm()->createView();
  136. }
  137. return $this->container->get('templating')->renderResponse(
  138. 'FOSUserBundle:Profile:show.html.twig',
  139. $data
  140. );
  141. }
  142. /**
  143. * @Template()
  144. * @Route("/users/{name}/", name="user_profile")
  145. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  146. */
  147. public function profileAction(Request $req, User $user)
  148. {
  149. $packages = $this->getUserPackages($req, $user);
  150. $data = array(
  151. 'packages' => $packages,
  152. 'meta' => $this->getPackagesMetadata($packages),
  153. 'user' => $user,
  154. );
  155. if ($this->isGranted('ROLE_ANTISPAM')) {
  156. $data['spammerForm'] = $this->createFormBuilder(array())->getForm()->createView();
  157. }
  158. if (!count($packages) && ($this->isGranted('ROLE_ADMIN') || ($this->getUser() && $this->getUser()->getId() === $user->getId()))) {
  159. $data['deleteForm'] = $this->createFormBuilder(array())->getForm()->createView();
  160. }
  161. return $data;
  162. }
  163. /**
  164. * @Route("/oauth/github/disconnect", name="user_github_disconnect")
  165. */
  166. public function disconnectGitHubAction(Request $req)
  167. {
  168. $user = $this->getUser();
  169. $token = $this->get('security.csrf.token_manager')->getToken('unlink_github')->getValue();
  170. if (!hash_equals($token, $req->query->get('token', '')) || !$user) {
  171. throw new AccessDeniedException('Invalid CSRF token');
  172. }
  173. if ($user->getGithubId()) {
  174. $user->setGithubId(null);
  175. $user->setGithubToken(null);
  176. $user->setGithubScope(null);
  177. $this->getDoctrine()->getEntityManager()->flush();
  178. }
  179. return $this->redirectToRoute('fos_user_profile_edit');
  180. }
  181. /**
  182. * @Template()
  183. * @Route("/users/{name}/favorites/", name="user_favorites", methods={"GET"})
  184. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  185. */
  186. public function favoritesAction(Request $req, User $user)
  187. {
  188. try {
  189. if (!$this->get('snc_redis.default')->isConnected()) {
  190. $this->get('snc_redis.default')->connect();
  191. }
  192. } catch (\Exception $e) {
  193. $this->get('session')->getFlashBag()->set('error', 'Could not connect to the Redis database.');
  194. $this->get('logger')->notice($e->getMessage(), array('exception' => $e));
  195. return array('user' => $user, 'packages' => array());
  196. }
  197. $paginator = new Pagerfanta(
  198. new RedisAdapter($this->get('packagist.favorite_manager'), $user, 'getFavorites', 'getFavoriteCount')
  199. );
  200. $paginator->setMaxPerPage(15);
  201. $paginator->setCurrentPage(max(1, (int) $req->query->get('page', 1)), false, true);
  202. return array('packages' => $paginator, 'user' => $user);
  203. }
  204. /**
  205. * @Route("/users/{name}/favorites/", name="user_add_fav", defaults={"_format" = "json"}, methods={"POST"})
  206. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  207. */
  208. public function postFavoriteAction(Request $req, User $user)
  209. {
  210. if (!$this->getUser() || $user->getId() !== $this->getUser()->getId()) {
  211. throw new AccessDeniedException('You can only change your own favorites');
  212. }
  213. $package = $req->request->get('package');
  214. try {
  215. $package = $this->getDoctrine()
  216. ->getRepository(Package::class)
  217. ->findOneByName($package);
  218. } catch (NoResultException $e) {
  219. throw new NotFoundHttpException('The given package "'.$package.'" was not found.');
  220. }
  221. $this->get('packagist.favorite_manager')->markFavorite($user, $package);
  222. return new Response('{"status": "success"}', 201);
  223. }
  224. /**
  225. * @Route("/users/{name}/favorites/{package}", name="user_remove_fav", defaults={"_format" = "json"}, requirements={"package"="[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+?"}, methods={"DELETE"})
  226. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  227. * @ParamConverter("package", options={"mapping": {"package": "name"}})
  228. */
  229. public function deleteFavoriteAction(User $user, Package $package)
  230. {
  231. if (!$this->getUser() || $user->getId() !== $this->getUser()->getId()) {
  232. throw new AccessDeniedException('You can only change your own favorites');
  233. }
  234. $this->get('packagist.favorite_manager')->removeFavorite($user, $package);
  235. return new Response('{"status": "success"}', 204);
  236. }
  237. /**
  238. * @Route("/users/{name}/delete", name="user_delete", defaults={"_format" = "json"}, methods={"POST"})
  239. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  240. */
  241. public function deleteUserAction(User $user, Request $req)
  242. {
  243. if (!($this->isGranted('ROLE_ADMIN') || ($this->getUser() && $user->getId() === $this->getUser()->getId()))) {
  244. throw new AccessDeniedException('You cannot delete this user');
  245. }
  246. if (count($user->getPackages()) > 0) {
  247. throw new AccessDeniedException('The user has packages so it can not be deleted');
  248. }
  249. $form = $this->createFormBuilder(array())->getForm();
  250. $form->submit($req->request->get('form'));
  251. if ($form->isValid()) {
  252. $em = $this->getDoctrine()->getManager();
  253. $em->remove($user);
  254. $em->flush();
  255. $this->container->get('security.token_storage')->setToken(null);
  256. return $this->redirectToRoute('home');
  257. }
  258. return $this->redirectToRoute('user_profile', ['name' => $user->getName()]);
  259. }
  260. /**
  261. * @Template()
  262. * @Route("/users/{name}/2fa/", name="user_2fa_configure", methods={"GET"})
  263. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  264. */
  265. public function configureTwoFactorAuthAction(User $user)
  266. {
  267. if (!($this->isGranted('ROLE_DISABLE_2FA') || ($this->getUser() && $user->getId() === $this->getUser()->getId()))) {
  268. throw new AccessDeniedException('You cannot change this user\'s two-factor authentication settings');
  269. }
  270. if ($user->getId() === $this->getUser()->getId()) {
  271. $backupCode = $this->get('session')->remove('backup_code');
  272. }
  273. return array('user' => $user, 'backup_code' => $backupCode ?? null);
  274. }
  275. /**
  276. * @Template()
  277. * @Route("/users/{name}/2fa/enable", name="user_2fa_enable", methods={"GET", "POST"})
  278. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  279. */
  280. public function enableTwoFactorAuthAction(Request $req, User $user)
  281. {
  282. if (!$this->getUser() || $user->getId() !== $this->getUser()->getId()) {
  283. throw new AccessDeniedException('You cannot change this user\'s two-factor authentication settings');
  284. }
  285. $authenticator = $this->get("scheb_two_factor.security.totp_authenticator");
  286. $enableRequest = new EnableTwoFactorRequest($authenticator->generateSecret());
  287. $form = $this->createForm(EnableTwoFactorAuthType::class, $enableRequest);
  288. $form->handleRequest($req);
  289. // Temporarily store this code on the user, as we'll need it there to generate the
  290. // QR code and to check the confirmation code. We won't actually save this change
  291. // until we've confirmed the code
  292. $user->setTotpSecret($enableRequest->getSecret());
  293. if ($form->isSubmitted()) {
  294. // Validate the code using the secret that was submitted in the form
  295. if (!$authenticator->checkCode($user, $enableRequest->getCode())) {
  296. $form->get('code')->addError(new FormError('Invalid authenticator code'));
  297. }
  298. if ($form->isValid()) {
  299. $authManager = $this->get(TwoFactorAuthManager::class);
  300. $authManager->enableTwoFactorAuth($user, $enableRequest->getSecret());
  301. $backupCode = $authManager->generateAndSaveNewBackupCode($user);
  302. $this->addFlash('success', 'Two-factor authentication has been enabled.');
  303. $this->get('session')->set('backup_code', $backupCode);
  304. return $this->redirectToRoute('user_2fa_confirm', array('name' => $user->getUsername()));
  305. }
  306. }
  307. return array('user' => $user, 'provisioningUri' => $authenticator->getQRContent($user), 'secret' => $enableRequest->getSecret(), 'form' => $form->createView());
  308. }
  309. /**
  310. * @Template()
  311. * @Route("/users/{name}/2fa/confirm", name="user_2fa_confirm", methods={"GET"})
  312. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  313. */
  314. public function confirmTwoFactorAuthAction(User $user)
  315. {
  316. if (!$this->getUser() || $user->getId() !== $this->getUser()->getId()) {
  317. throw new AccessDeniedException('You cannot change this user\'s two-factor authentication settings');
  318. }
  319. $backupCode = $this->get('session')->remove('backup_code');
  320. if (empty($backupCode)) {
  321. return $this->redirectToRoute('user_2fa_configure', ['name' => $user->getUsername()]);
  322. }
  323. return array('user' => $user, 'backup_code' => $backupCode);
  324. }
  325. /**
  326. * @Template()
  327. * @Route("/users/{name}/2fa/disable", name="user_2fa_disable", methods={"GET"})
  328. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  329. */
  330. public function disableTwoFactorAuthAction(Request $req, User $user)
  331. {
  332. if (!($this->isGranted('ROLE_DISABLE_2FA') || ($this->getUser() && $user->getId() === $this->getUser()->getId()))) {
  333. throw new AccessDeniedException('You cannot change this user\'s two-factor authentication settings');
  334. }
  335. $token = $this->get('security.csrf.token_manager')->getToken('disable_2fa')->getValue();
  336. if (hash_equals($token, $req->query->get('token', ''))) {
  337. $this->get(TwoFactorAuthManager::class)->disableTwoFactorAuth($user, 'Manually disabled');
  338. $this->addFlash('success', 'Two-factor authentication has been disabled.');
  339. return $this->redirectToRoute('user_2fa_configure', array('name' => $user->getUsername()));
  340. }
  341. return array('user' => $user);
  342. }
  343. /**
  344. * @param Request $req
  345. * @param User $user
  346. * @return Pagerfanta
  347. */
  348. protected function getUserPackages($req, $user)
  349. {
  350. $packages = $this->getDoctrine()
  351. ->getRepository(Package::class)
  352. ->getFilteredQueryBuilder(array('maintainer' => $user->getId()), true);
  353. $paginator = new Pagerfanta(new DoctrineORMAdapter($packages, true));
  354. $paginator->setMaxPerPage(15);
  355. $paginator->setCurrentPage(max(1, (int) $req->query->get('page', 1)), false, true);
  356. return $paginator;
  357. }
  358. }