| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <?php
- namespace App\Module\OpenAPI\Validations;
- use App\Module\OpenAPI\Models\OpenApiApp;
- use App\Module\OpenAPI\Validators\AppExistenceValidator;
- use App\Module\OpenAPI\Validators\AppStatusValidator;
- use App\Module\OpenAPI\Validators\ScopePermissionValidator;
- use UCore\ValidationCore;
- /**
- * 令牌请求验证类
- */
- class TokenRequestValidation extends ValidationCore
- {
- /** @var OpenApiApp|null 应用对象,由 AppExistenceValidator 设置 */
- public ?OpenApiApp $app = null;
- /** @var array|null 权限范围列表,由验证器处理后设置 */
- public ?array $scopes = null;
- /**
- * 验证规则
- */
- public function rules($rules = []): array
- {
- return [
- // 基础验证
- ['grant_type', 'required'],
- ['grant_type', 'in', 'range' => ['client_credentials', 'authorization_code', 'refresh_token']],
-
- // 客户端凭证验证
- ['client_id', 'required', 'when' => function($data) {
- return in_array($data['grant_type'] ?? '', ['client_credentials', 'authorization_code']);
- }],
- ['client_secret', 'required', 'when' => function($data) {
- return in_array($data['grant_type'] ?? '', ['client_credentials', 'authorization_code']);
- }],
-
- // 授权码验证
- ['code', 'required', 'when' => function($data) {
- return ($data['grant_type'] ?? '') === 'authorization_code';
- }],
-
- // 刷新令牌验证
- ['refresh_token', 'required', 'when' => function($data) {
- return ($data['grant_type'] ?? '') === 'refresh_token';
- }],
- // 业务验证(按顺序执行)
- [
- 'client_id', new AppExistenceValidator($this, ['client_secret', 'app']),
- 'msg' => '应用不存在或密钥错误',
- 'when' => function($data) {
- return isset($data['client_id']) && isset($data['client_secret']);
- }
- ],
- [
- 'client_id', new AppStatusValidator($this, ['app']),
- 'msg' => '应用状态异常',
- 'when' => function($data) {
- return isset($data['client_id']);
- }
- ],
- [
- 'scope', new ScopePermissionValidator($this, ['app', 'scopes']),
- 'msg' => '权限范围验证失败',
- 'when' => function($data) {
- return isset($data['scope']) && isset($data['client_id']);
- }
- ],
- ];
- }
- /**
- * 默认值
- */
- public function default(): array
- {
- return [
- 'scope' => '',
- ];
- }
- }
|