OAuthRepository.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace App\Module\OAuth\Repositories;
  3. use App\Module\OAuth\Models\OAuthClient;
  4. use App\Module\OAuth\Models\OAuthAccessToken;
  5. use Carbon\Carbon;
  6. use Dcat\Admin\Repositories\EloquentRepository;
  7. class OAuthRepository extends EloquentRepository
  8. {
  9. protected $eloquentClass = OAuthClient::class;
  10. /**
  11. * 获取所有客户端列表
  12. */
  13. public function getClientList(array $params = [])
  14. {
  15. $query = OAuthClient::query();
  16. // 按名称搜索
  17. if (!empty($params['name'])) {
  18. $query->where('name', 'like', "%{$params['name']}%");
  19. }
  20. // 按客户端ID搜索
  21. if (!empty($params['client_id'])) {
  22. $query->where('client_id', $params['client_id']);
  23. }
  24. return $query->paginate($params['per_page'] ?? 15);
  25. }
  26. /**
  27. * 获取客户端的令牌列表
  28. */
  29. public function getClientTokens(string $clientId, array $params = [])
  30. {
  31. $query = OAuthAccessToken::where('client_id', $clientId);
  32. // 按用户ID搜索
  33. if (!empty($params['user_id'])) {
  34. $query->where('user_id', $params['user_id']);
  35. }
  36. // 是否只显示有效的
  37. if (!empty($params['active_only'])) {
  38. $query->where('expires_at', '>', now());
  39. }
  40. return $query->paginate($params['per_page'] ?? 15);
  41. }
  42. /**
  43. * 批量撤销令牌
  44. */
  45. public function revokeTokens(array $tokenIds): int
  46. {
  47. return OAuthAccessToken::whereIn('id', $tokenIds)->delete();
  48. }
  49. /**
  50. * 更新客户端信息
  51. */
  52. public function updateClient(int $id, array $data): bool
  53. {
  54. return OAuthClient::where('id', $id)->update($data);
  55. }
  56. /**
  57. * 删除客户端
  58. */
  59. public function deleteClient(int $id): bool
  60. {
  61. // 删除客户端的同时删除其所有令牌
  62. OAuthAccessToken::where('client_id', function ($query) use ($id) {
  63. $query->select('client_id')
  64. ->from('oauth_clients')
  65. ->where('id', $id);
  66. })->delete();
  67. return OAuthClient::where('id', $id)->delete();
  68. }
  69. /**
  70. * 获取OAuth统计数据
  71. *
  72. * @return array
  73. */
  74. public function getStats()
  75. {
  76. $now = Carbon::now();
  77. return [
  78. 'total_clients' => OAuthClient::count(),
  79. 'total_tokens' => OAuthAccessToken::count(),
  80. 'active_tokens' => OAuthAccessToken::where('expires_at', '>', $now)->count(),
  81. 'expired_tokens' => OAuthAccessToken::where('expires_at', '<=', $now)->count(),
  82. ];
  83. }
  84. }