Driver.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace app\common\library\token;
  3. use think\facade\Config;
  4. /**
  5. * Token 驱动抽象类
  6. */
  7. abstract class Driver
  8. {
  9. /**
  10. * 具体驱动的句柄 Mysql|Redis
  11. * @var object
  12. */
  13. protected object $handler;
  14. /**
  15. * @var array 配置数据
  16. */
  17. protected array $options = [];
  18. /**
  19. * 设置 token
  20. * @param string $token Token
  21. * @param string $type Type:admin|user
  22. * @param int $user_id 用户ID
  23. * @param int $expire 过期时间
  24. * @return bool
  25. */
  26. abstract function set(string $token, string $type, int $user_id, int $expire = 0): bool;
  27. /**
  28. * 获取 token 的数据
  29. * @param string $token Token
  30. * @param bool $expirationException 过期直接抛出异常
  31. * @return array
  32. */
  33. abstract function get(string $token, bool $expirationException = true): array;
  34. /**
  35. * 检查token是否有效
  36. * @param string $token
  37. * @param string $type
  38. * @param int $user_id
  39. * @param bool $expirationException
  40. * @return bool
  41. */
  42. abstract function check(string $token, string $type, int $user_id, bool $expirationException = true): bool;
  43. /**
  44. * 删除一个token
  45. * @param string $token
  46. * @return bool
  47. */
  48. abstract function delete(string $token): bool;
  49. /**
  50. * 清理一个用户的所有token
  51. * @param string $type
  52. * @param int $user_id
  53. * @return bool
  54. */
  55. abstract function clear(string $type, int $user_id): bool;
  56. /**
  57. * 返回句柄对象
  58. * @access public
  59. * @return object|null
  60. */
  61. public function handler(): ?object
  62. {
  63. return $this->handler;
  64. }
  65. /**
  66. * @param string $token
  67. * @return string
  68. */
  69. protected function getEncryptedToken(string $token): string
  70. {
  71. $config = Config::get('buildadmin.token');
  72. return hash_hmac($config['algo'], $token, $config['key']);
  73. }
  74. /**
  75. * @param int $expireTime
  76. * @return int
  77. */
  78. protected function getExpiredIn(int $expireTime): int
  79. {
  80. return $expireTime ? max(0, $expireTime - time()) : 365 * 86400;
  81. }
  82. }