| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- <?php
- namespace App\Module\OAuth\Repositories;
- use App\Module\OAuth\Models\OAuthClient;
- use App\Module\OAuth\Models\OAuthAccessToken;
- use Carbon\Carbon;
- use Dcat\Admin\Repositories\EloquentRepository;
- class OAuthRepository extends EloquentRepository
- {
- protected $eloquentClass = OAuthClient::class;
- /**
- * 获取所有客户端列表
- */
- public function getClientList(array $params = [])
- {
- $query = OAuthClient::query();
- // 按名称搜索
- if (!empty($params['name'])) {
- $query->where('name', 'like', "%{$params['name']}%");
- }
- // 按客户端ID搜索
- if (!empty($params['client_id'])) {
- $query->where('client_id', $params['client_id']);
- }
- return $query->paginate($params['per_page'] ?? 15);
- }
- /**
- * 获取客户端的令牌列表
- */
- public function getClientTokens(string $clientId, array $params = [])
- {
- $query = OAuthAccessToken::where('client_id', $clientId);
- // 按用户ID搜索
- if (!empty($params['user_id'])) {
- $query->where('user_id', $params['user_id']);
- }
- // 是否只显示有效的
- if (!empty($params['active_only'])) {
- $query->where('expires_at', '>', now());
- }
- return $query->paginate($params['per_page'] ?? 15);
- }
- /**
- * 批量撤销令牌
- */
- public function revokeTokens(array $tokenIds): int
- {
- return OAuthAccessToken::whereIn('id', $tokenIds)->delete();
- }
- /**
- * 更新客户端信息
- */
- public function updateClient(int $id, array $data): bool
- {
- return OAuthClient::where('id', $id)->update($data);
- }
- /**
- * 删除客户端
- */
- public function deleteClient(int $id): bool
- {
- // 删除客户端的同时删除其所有令牌
- OAuthAccessToken::where('client_id', function ($query) use ($id) {
- $query->select('client_id')
- ->from('oauth_clients')
- ->where('id', $id);
- })->delete();
- return OAuthClient::where('id', $id)->delete();
- }
- /**
- * 获取OAuth统计数据
- *
- * @return array
- */
- public function getStats()
- {
- $now = Carbon::now();
- return [
- 'total_clients' => OAuthClient::count(),
- 'total_tokens' => OAuthAccessToken::count(),
- 'active_tokens' => OAuthAccessToken::where('expires_at', '>', $now)->count(),
- 'expired_tokens' => OAuthAccessToken::where('expires_at', '<=', $now)->count(),
- ];
- }
- }
|