Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

113 Zeilen
2.8 KiB

  1. <?php
  2. namespace app\common\library\token\driver;
  3. use app\common\library\token\Driver;
  4. /**
  5. * Token操作类
  6. */
  7. class Mysql extends Driver
  8. {
  9. /**
  10. * 默认配置
  11. * @var array
  12. */
  13. protected $options = [
  14. 'table' => 'user_token',
  15. 'expire' => 2592000,
  16. 'connection' => [],
  17. ];
  18. /**
  19. * 构造函数
  20. * @param array $options 参数
  21. * @access public
  22. */
  23. public function __construct($options = [])
  24. {
  25. if (!empty($options)) {
  26. $this->options = array_merge($this->options, $options);
  27. }
  28. if ($this->options['connection']) {
  29. $this->handler = \think\Db::connect($this->options['connection'])->name($this->options['table']);
  30. } else {
  31. $this->handler = \think\Db::name($this->options['table']);
  32. }
  33. }
  34. /**
  35. * 存储Token
  36. * @param string $token Token
  37. * @param int $user_id 会员ID
  38. * @param int $expire 过期时长,0表示无限,单位秒
  39. * @return bool
  40. */
  41. public function set($token, $user_id, $expire = null)
  42. {
  43. $expiretime = !is_null($expire) && $expire !== 0 ? time() + $expire : 0;
  44. $token = $this->getEncryptedToken($token);
  45. $this->handler->insert(['token' => $token, 'user_id' => $user_id, 'createtime' => time(), 'expiretime' => $expiretime]);
  46. return TRUE;
  47. }
  48. /**
  49. * 获取Token内的信息
  50. * @param string $token
  51. * @return array
  52. */
  53. public function get($token)
  54. {
  55. $data = $this->handler->where('token', $this->getEncryptedToken($token))->find();
  56. if ($data) {
  57. if (!$data['expiretime'] || $data['expiretime'] > time()) {
  58. //返回未加密的token给客户端使用
  59. $data['token'] = $token;
  60. //返回剩余有效时间
  61. $data['expires_in'] = $this->getExpiredIn($data['expiretime']);
  62. return $data;
  63. } else {
  64. self::delete($token);
  65. }
  66. }
  67. return [];
  68. }
  69. /**
  70. * 判断Token是否可用
  71. * @param string $token Token
  72. * @param int $user_id 会员ID
  73. * @return boolean
  74. */
  75. public function check($token, $user_id)
  76. {
  77. $data = $this->get($token);
  78. return $data && $data['user_id'] == $user_id ? true : false;
  79. }
  80. /**
  81. * 删除Token
  82. * @param string $token
  83. * @return boolean
  84. */
  85. public function delete($token)
  86. {
  87. $this->handler->where('token', $this->getEncryptedToken($token))->delete();
  88. return true;
  89. }
  90. /**
  91. * 删除指定用户的所有Token
  92. * @param int $user_id
  93. * @return boolean
  94. */
  95. public function clear($user_id)
  96. {
  97. $this->handler->where('user_id', $user_id)->delete();
  98. return true;
  99. }
  100. }