| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439 |
- <?php
- namespace App\Module\OpenAPI\Models;
- use App\Module\OpenAPI\Enums\APP_STATUS;
- use App\Module\OpenAPI\Enums\AUTH_TYPE;
- use UCore\ModelCore;
- /**
- * 开放API应用模型
- *
- * @property int $id
- * @property string $app_id 应用ID
- * @property string $app_secret 应用密钥
- * @property string $name 应用名称
- * @property string $description 应用描述
- * @property string $website 应用网站
- * @property string $logo 应用Logo
- * @property string $callback_url 回调地址
- * @property string $contact_email 联系邮箱
- * @property string $status 应用状态
- * @property string $auth_type 认证类型
- * @property array $scopes 权限范围
- * @property array $rate_limits 限流配置
- * @property array $ip_whitelist IP白名单
- * @property int $user_id 创建用户ID
- * @property string $user_name 创建用户名称
- * @property \Carbon\Carbon $approved_at 审核时间
- * @property int $approved_by 审核人ID
- * @property string $approved_note 审核备注
- * @property \Carbon\Carbon $expires_at 过期时间
- * @property \Carbon\Carbon $last_used_at 最后使用时间
- * @property \Carbon\Carbon $created_at 创建时间
- * @property \Carbon\Carbon $updated_at 更新时间
- */
- class OpenApiApp extends ModelCore
- {
- /**
- * 数据表名
- *
- * @var string
- */
- protected $table = 'openapi_apps';
- /**
- * 可批量赋值的属性
- *
- * @var array
- */
- protected $fillable = [
- 'app_id',
- 'app_secret',
- 'name',
- 'description',
- 'website',
- 'logo',
- 'callback_url',
- 'contact_email',
- 'status',
- 'auth_type',
- 'scopes',
- 'rate_limits',
- 'ip_whitelist',
- 'user_id',
- 'user_name',
- 'approved_at',
- 'approved_by',
- 'approved_note',
- 'expires_at',
- 'last_used_at',
- ];
- /**
- * 属性类型转换
- *
- * @var array
- */
- protected $casts = [
- 'scopes' => 'array',
- 'rate_limits' => 'array',
- 'ip_whitelist' => 'array',
- 'user_id' => 'integer',
- 'approved_by' => 'integer',
- 'approved_at' => 'datetime',
- 'expires_at' => 'datetime',
- 'last_used_at' => 'datetime',
- 'created_at' => 'datetime',
- 'updated_at' => 'datetime',
- ];
- /**
- * 隐藏的属性
- *
- * @var array
- */
- protected $hidden = [
- 'app_secret',
- ];
- /**
- * 获取应用状态枚举
- *
- * @return APP_STATUS|null
- */
- public function getStatusEnumAttribute(): ?APP_STATUS
- {
- try {
- return APP_STATUS::from($this->status);
- } catch (\ValueError $e) {
- return null;
- }
- }
- /**
- * 获取认证类型枚举
- *
- * @return AUTH_TYPE|null
- */
- public function getAuthTypeEnumAttribute(): ?AUTH_TYPE
- {
- try {
- return AUTH_TYPE::from($this->auth_type);
- } catch (\ValueError $e) {
- return null;
- }
- }
- /**
- * 获取状态标签
- *
- * @return string
- */
- public function getStatusLabelAttribute(): string
- {
- $enum = $this->getStatusEnumAttribute();
- return $enum ? $enum->getLabel() : $this->status;
- }
- /**
- * 获取状态颜色
- *
- * @return string
- */
- public function getStatusColorAttribute(): string
- {
- $enum = $this->getStatusEnumAttribute();
- return $enum ? $enum->getColor() : 'secondary';
- }
- /**
- * 获取认证类型标签
- *
- * @return string
- */
- public function getAuthTypeLabelAttribute(): string
- {
- $enum = $this->getAuthTypeEnumAttribute();
- return $enum ? $enum->getLabel() : $this->auth_type;
- }
- /**
- * 判断应用是否可以调用API
- *
- * @return bool
- */
- public function getCanCallApiAttribute(): bool
- {
- $enum = $this->getStatusEnumAttribute();
- return $enum ? $enum->canCallApi() : false;
- }
- /**
- * 判断应用是否已过期
- *
- * @return bool
- */
- public function getIsExpiredAttribute(): bool
- {
- return $this->expires_at && $this->expires_at->isPast();
- }
- /**
- * 判断应用是否需要审核
- *
- * @return bool
- */
- public function getNeedsApprovalAttribute(): bool
- {
- $enum = $this->getStatusEnumAttribute();
- return $enum ? $enum->needsApproval() : false;
- }
- /**
- * 获取权限范围标签
- *
- * @return array
- */
- public function getScopeLabelsAttribute(): array
- {
- if (empty($this->scopes)) {
- return [];
- }
- $labels = [];
- foreach ($this->scopes as $scope) {
- try {
- $enum = \App\Module\OpenAPI\Enums\SCOPE_TYPE::from($scope);
- $labels[] = $enum->getLabel();
- } catch (\ValueError $e) {
- $labels[] = $scope;
- }
- }
- return $labels;
- }
- /**
- * 获取掩码后的应用密钥
- *
- * @return string
- */
- public function getMaskedSecretAttribute(): string
- {
- if (empty($this->app_secret)) {
- return '';
- }
- $length = strlen($this->app_secret);
- if ($length <= 8) {
- return str_repeat('*', $length);
- }
- return substr($this->app_secret, 0, 4) . str_repeat('*', $length - 8) . substr($this->app_secret, -4);
- }
- /**
- * 生成新的应用ID
- *
- * @return string
- */
- public static function generateAppId(): string
- {
- $prefix = config('openapi.api_key.prefix', 'ak_');
- $length = config('openapi.api_key.length', 32);
-
- do {
- $appId = $prefix . bin2hex(random_bytes($length / 2));
- } while (self::where('app_id', $appId)->exists());
- return $appId;
- }
- /**
- * 生成新的应用密钥
- *
- * @return string
- */
- public static function generateAppSecret(): string
- {
- $prefix = config('openapi.api_key.secret_prefix', 'sk_');
- $length = config('openapi.api_key.secret_length', 64);
-
- return $prefix . bin2hex(random_bytes($length / 2));
- }
- /**
- * 按状态查询
- *
- * @param \Illuminate\Database\Eloquent\Builder $query
- * @param string|APP_STATUS $status
- * @return \Illuminate\Database\Eloquent\Builder
- */
- public function scopeByStatus($query, $status)
- {
- if ($status instanceof APP_STATUS) {
- $status = $status->value;
- }
- return $query->where('status', $status);
- }
- /**
- * 按用户查询
- *
- * @param \Illuminate\Database\Eloquent\Builder $query
- * @param int $userId
- * @return \Illuminate\Database\Eloquent\Builder
- */
- public function scopeByUser($query, int $userId)
- {
- return $query->where('user_id', $userId);
- }
- /**
- * 查询活跃应用
- *
- * @param \Illuminate\Database\Eloquent\Builder $query
- * @return \Illuminate\Database\Eloquent\Builder
- */
- public function scopeActive($query)
- {
- return $query->where('status', APP_STATUS::ACTIVE->value)
- ->where(function ($q) {
- $q->whereNull('expires_at')
- ->orWhere('expires_at', '>', now());
- });
- }
- /**
- * 查询需要审核的应用
- *
- * @param \Illuminate\Database\Eloquent\Builder $query
- * @return \Illuminate\Database\Eloquent\Builder
- */
- public function scopePendingApproval($query)
- {
- return $query->where('status', APP_STATUS::PENDING->value);
- }
- /**
- * 查询即将过期的应用
- *
- * @param \Illuminate\Database\Eloquent\Builder $query
- * @param int $days
- * @return \Illuminate\Database\Eloquent\Builder
- */
- public function scopeExpiringSoon($query, int $days = 30)
- {
- return $query->whereNotNull('expires_at')
- ->whereBetween('expires_at', [now(), now()->addDays($days)]);
- }
- /**
- * 更新最后使用时间
- *
- * @return void
- */
- public function updateLastUsed(): void
- {
- $this->update(['last_used_at' => now()]);
- }
- /**
- * 检查是否有指定权限
- *
- * @param string $scope
- * @return bool
- */
- public function hasScope(string $scope): bool
- {
- if (empty($this->scopes)) {
- return false;
- }
- return in_array($scope, $this->scopes) || in_array('*', $this->scopes);
- }
- /**
- * 检查应用是否激活
- *
- * @return bool
- */
- public function isActive(): bool
- {
- return $this->status === APP_STATUS::ACTIVE->value;
- }
- /**
- * 检查应用是否被暂停
- *
- * @return bool
- */
- public function isSuspended(): bool
- {
- return $this->status === APP_STATUS::SUSPENDED->value;
- }
- /**
- * 检查应用是否过期
- *
- * @return bool
- */
- public function isExpired(): bool
- {
- return $this->expires_at && $this->expires_at->isPast();
- }
- /**
- * 检查IP是否在白名单中
- *
- * @param string $ip
- * @return bool
- */
- public function isIpAllowed(string $ip): bool
- {
- if (empty($this->ip_whitelist)) {
- return true; // 没有设置白名单,允许所有IP
- }
- foreach ($this->ip_whitelist as $allowedIp) {
- if ($this->matchIp($ip, $allowedIp)) {
- return true;
- }
- }
- return false;
- }
- /**
- * 匹配IP地址
- *
- * @param string $ip
- * @param string $pattern
- * @return bool
- */
- protected function matchIp(string $ip, string $pattern): bool
- {
- // 精确匹配
- if ($ip === $pattern) {
- return true;
- }
- // CIDR匹配
- if (strpos($pattern, '/') !== false) {
- list($subnet, $mask) = explode('/', $pattern);
- return (ip2long($ip) & ~((1 << (32 - $mask)) - 1)) === ip2long($subnet);
- }
- // 通配符匹配
- if (strpos($pattern, '*') !== false) {
- $pattern = str_replace('*', '.*', $pattern);
- return preg_match('/^' . $pattern . '$/', $ip);
- }
- return false;
- }
- }
|