Driver.php 2.1 KB

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