vendor/uvdesk/api-bundle/API/Sessions.php line 17

Open in your IDE?
  1. <?php
  2. namespace Webkul\UVDesk\ApiBundle\API;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Webkul\UVDesk\ApiBundle\Entity\ApiAccessCredential;
  9. use Webkul\UVDesk\CoreFrameworkBundle\Entity\User;
  10. use Webkul\UVDesk\CoreFrameworkBundle\Utils\TokenGenerator;
  11. use Webkul\UVDesk\CoreFrameworkBundle\Services\UVDeskService as Uvdesk;
  12. class Sessions extends AbstractController
  13. {
  14. public function loginSession(Request $request, EntityManagerInterface $entityManager, Uvdesk $uvdesk)
  15. {
  16. $user = $this->getUser();
  17. $userInstance = $user->getCurrentInstance();
  18. if (empty($user)) {
  19. return new JsonResponse([
  20. 'success' => false,
  21. 'message' => "Invalid or no user credentials were provided.",
  22. ], 403);
  23. }
  24. $accessCredential = new ApiAccessCredential();
  25. $accessCredential
  26. ->setUser($user)
  27. ->setName('API Session')
  28. ->setToken(strtoupper(TokenGenerator::generateToken(64)))
  29. ->setCreatedOn(new \DateTime('now'))
  30. ->setIsEnabled(true)
  31. ->setIsExpired(false)
  32. ;
  33. $entityManager->persist($accessCredential);
  34. $entityManager->flush();
  35. return new JsonResponse([
  36. 'success' => true,
  37. 'accessToken' => $accessCredential->getToken(),
  38. 'scopes' => $uvdesk->getAvailableUserAccessScopes($user, $userInstance),
  39. ]);
  40. }
  41. public function logoutSession(Request $request, EntityManagerInterface $entityManager)
  42. {
  43. $user = $this->getUser();
  44. $accessToken = null;
  45. $authorization = $request->headers->get('Authorization');
  46. if (!empty($authorization) && strpos(strtolower($authorization), 'basic') === 0) {
  47. $accessToken = substr($authorization, 6);
  48. } else if (!empty($authorization) && strpos(strtolower($authorization), 'bearer') === 0) {
  49. $accessToken = substr($authorization, 7);
  50. }
  51. if (empty($accessToken)) {
  52. return new JsonResponse([
  53. 'success' => false,
  54. 'message' => "Unsupported or invalid credentials provided.",
  55. ]);
  56. }
  57. $apiAccessCredential = $entityManager->getRepository(ApiAccessCredential::class)->findOneByToken($accessToken);
  58. if (empty($apiAccessCredential)) {
  59. return new JsonResponse([
  60. 'success' => false,
  61. 'message' => "Invalid credentials provided.",
  62. ]);
  63. }
  64. $apiAccessCredential
  65. ->setIsEnabled(false)
  66. ->setIsExpired(true)
  67. ;
  68. $entityManager->persist($apiAccessCredential);
  69. $entityManager->flush();
  70. return new JsonResponse([
  71. 'status' => true,
  72. 'message' => 'Session token has been expired successfully.'
  73. ]);
  74. }
  75. }