token-functions.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. trait TokenFunctions
  3. {
  4. public function configToken()
  5. {
  6. return Lcobucci\JWT\Configuration::forSymmetricSigner(
  7. // You may use any HMAC variations (256, 384, and 512)
  8. new Lcobucci\JWT\Signer\Hmac\Sha256(),
  9. // replace the value below with a key of your own!
  10. Lcobucci\JWT\Signer\Key\InMemory::plainText($this->config['organizrHash'])
  11. // You may also override the JOSE encoder/decoder if needed by providing extra arguments here
  12. );
  13. }
  14. public function validationConstraints()
  15. {
  16. return [
  17. new Lcobucci\JWT\Validation\Constraint\IssuedBy('Organizr'),
  18. new Lcobucci\JWT\Validation\Constraint\PermittedFor('Organizr'),
  19. new Lcobucci\JWT\Validation\Constraint\LooseValidAt(Lcobucci\Clock\SystemClock::fromUTC())
  20. ];
  21. }
  22. public function jwtParse($userToken)
  23. {
  24. try {
  25. $result = [];
  26. // Check Token with JWT
  27. // Set key
  28. if (!isset($this->config['organizrHash'])) {
  29. return null;
  30. }
  31. $config = $this->configToken();
  32. assert($config instanceof Lcobucci\JWT\Configuration);
  33. $token = $config->parser()->parse($userToken);
  34. assert($token instanceof Lcobucci\JWT\UnencryptedToken);
  35. $constraints = $this->validationConstraints();
  36. if (!$config->validator()->validate($token, ...$constraints)) {
  37. return false;
  38. }
  39. $result['username'] = ($token->claims()->has('name')) ? $token->claims()->get('name') : 'N/A';
  40. $result['group'] = ($token->claims()->has('group')) ? $token->claims()->get('group') : 'N/A';
  41. $result['groupID'] = $token->claims()->get('groupID');
  42. $result['userID'] = $token->claims()->get('userID');
  43. $result['email'] = $token->claims()->get('email');
  44. $result['image'] = $token->claims()->get('image');
  45. $result['tokenExpire'] = $token->claims()->get('exp');
  46. $result['tokenDate'] = $token->claims()->get('iat');
  47. return $result;
  48. } catch (\OutOfBoundsException | \RunTimeException | \InvalidArgumentException | \Lcobucci\JWT\Validation\RequiredConstraintsViolated $e) {
  49. $this->setLoggerChannel('Token Error')->error($e);
  50. return false;
  51. }
  52. }
  53. }