Driver.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\common\library\token;
  12. /**
  13. * Token基础类
  14. */
  15. abstract class Driver
  16. {
  17. protected $handler = null;
  18. protected $options = [];
  19. /**
  20. * 存储Token
  21. * @param string $token Token
  22. * @param int $user_id 会员ID
  23. * @param int $expire 过期时长,0表示无限,单位秒
  24. * @return bool
  25. */
  26. abstract function set($token, $user_id, $expire = 0);
  27. /**
  28. * 获取Token内的信息
  29. * @param string $token
  30. * @return array
  31. */
  32. abstract function get($token);
  33. /**
  34. * 判断Token是否可用
  35. * @param string $token Token
  36. * @param int $user_id 会员ID
  37. * @return boolean
  38. */
  39. abstract function check($token, $user_id);
  40. /**
  41. * 删除Token
  42. * @param string $token
  43. * @return boolean
  44. */
  45. abstract function delete($token);
  46. /**
  47. * 删除指定用户的所有Token
  48. * @param int $user_id
  49. * @return boolean
  50. */
  51. abstract function clear($user_id);
  52. /**
  53. * 返回句柄对象,可执行其它高级方法
  54. *
  55. * @access public
  56. * @return object
  57. */
  58. public function handler()
  59. {
  60. return $this->handler;
  61. }
  62. /**
  63. * 获取加密后的Token
  64. * @param string $token Token标识
  65. * @return string
  66. */
  67. protected function getEncryptedToken($token)
  68. {
  69. $config = \think\Config::get('token');
  70. $token = $token ?? ''; // 为兼容 php8
  71. return hash_hmac($config['hashalgo'], $token, $config['key']);
  72. }
  73. /**
  74. * 获取过期剩余时长
  75. * @param $expiretime
  76. * @return float|int|mixed
  77. */
  78. protected function getExpiredIn($expiretime)
  79. {
  80. return $expiretime ? max(0, $expiretime - time()) : 365 * 86400;
  81. }
  82. }