UserToken.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace app\models\user;
  3. use crmeb\services\CacheService;
  4. use think\Model;
  5. class UserToken extends Model
  6. {
  7. protected $name = 'user_token';
  8. protected $type = [
  9. 'create_time' => 'datetime',
  10. 'login_ip' => 'string'
  11. ];
  12. protected $autoWriteTimestamp = true;
  13. protected $updateTime = false;
  14. public static function onBeforeInsert(UserToken $token)
  15. {
  16. if (!isset($token['login_ip']))
  17. $token['login_ip'] = app()->request->ip();
  18. }
  19. /**
  20. * @param User|array|Model $user
  21. * @param $type
  22. * @return array|bool
  23. */
  24. public static function createToken(User $user, $type)
  25. {
  26. $tokenInfo = $user->getToken($type);
  27. $expires = $tokenInfo['params']['exp'] - time() + 60;
  28. $res = CacheService::setTokenBucket($tokenInfo['token'], [
  29. 'token' => $tokenInfo['token'],
  30. 'exp' => $expires,
  31. 'uid' => $user->getData('uid'),
  32. 'type' => $type
  33. ], $expires, 'api');
  34. if ($res) return $tokenInfo;
  35. return false;
  36. }
  37. /**
  38. * 删除一天前的过期token
  39. * @return bool
  40. * @throws \Exception
  41. */
  42. public static function delToken()
  43. {
  44. //return self::where('expires_time', '<', date('Y-m-d H:i:s', strtotime('-1 day')))->delete();
  45. }
  46. }