UserToken.php 1.1 KB

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