src/Service/JwtService.php line 45

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use Symfony\Component\HttpFoundation\Cookie;
  4. use Symfony\Component\Config\Definition\Exception\Exception;
  5. use Firebase\JWT\JWT;
  6. use Firebase\JWT\ExpiredException;
  7. use Psr\Log\LoggerInterface;
  8. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  9. class JwtService
  10. {
  11. private $logger;
  12. private $timeout;
  13. // Allow overriding cookie domain
  14. public $domain;
  15. private $server_url;
  16. private $key;
  17. public function __construct(LoggerInterface $logger)
  18. {
  19. $this->logger = $logger;
  20. $this->timeout = $_ENV['JWT_TIMEOUT'];
  21. $this->key = $_ENV['JWT_KEY'];
  22. $this->timeForRefresh = time() + ($_ENV['JWT_TIMEOUT'] / 2); // if we have less than half the time left, refresh token
  23. }
  24. function setNewToken($userName, $roles, $timeout = null)
  25. {
  26. if (!$timeout) {
  27. $timeout = $this->timeout;
  28. }
  29. $payload = [
  30. "user" => $userName,
  31. "roles" => $roles,
  32. "exp" => time() + $timeout,
  33. ];
  34. return JWT::encode($payload, $this->key);
  35. }
  36. function getDecodedToken($jwt)
  37. {
  38. return (array) JWT::decode(
  39. $jwt,
  40. $_ENV['JWT_KEY'],
  41. ['HS256']
  42. );
  43. }
  44. public function getUser($jwt)
  45. {
  46. try {
  47. if (!$jwt) {
  48. throw new Exception('JWT not set.');
  49. }
  50. $decoded_jwt = $this->getDecodedToken($jwt);
  51. if (!$decoded_jwt['user']) {
  52. throw new Exception('User not set.');
  53. }
  54. } catch (ExpiredException $e) {
  55. throw new Exception($e->getMessage());
  56. }
  57. return $decoded_jwt['user'];
  58. }
  59. public function setRefreshedJwt($jwt)
  60. {
  61. $jwt['exp'] = time() + $this->timeout;
  62. return JWT::encode($jwt, $this->key);
  63. }
  64. }