TokenRequestValidation.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Module\OpenAPI\Validations;
  3. use App\Module\OpenAPI\Models\OpenApiApp;
  4. use App\Module\OpenAPI\Validators\AppExistenceValidator;
  5. use App\Module\OpenAPI\Validators\AppStatusValidator;
  6. use App\Module\OpenAPI\Validators\ScopePermissionValidator;
  7. use UCore\ValidationCore;
  8. /**
  9. * 令牌请求验证类
  10. */
  11. class TokenRequestValidation extends ValidationCore
  12. {
  13. /** @var OpenApiApp|null 应用对象,由 AppExistenceValidator 设置 */
  14. public ?OpenApiApp $app = null;
  15. /** @var array|null 权限范围列表,由验证器处理后设置 */
  16. public ?array $scopes = null;
  17. /**
  18. * 验证规则
  19. */
  20. public function rules($rules = []): array
  21. {
  22. return [
  23. // 基础验证
  24. ['grant_type', 'required'],
  25. ['grant_type', 'in', 'range' => ['client_credentials', 'authorization_code', 'refresh_token']],
  26. // 客户端凭证验证
  27. ['client_id', 'required', 'when' => function($data) {
  28. return in_array($data['grant_type'] ?? '', ['client_credentials', 'authorization_code']);
  29. }],
  30. ['client_secret', 'required', 'when' => function($data) {
  31. return in_array($data['grant_type'] ?? '', ['client_credentials', 'authorization_code']);
  32. }],
  33. // 授权码验证
  34. ['code', 'required', 'when' => function($data) {
  35. return ($data['grant_type'] ?? '') === 'authorization_code';
  36. }],
  37. // 刷新令牌验证
  38. ['refresh_token', 'required', 'when' => function($data) {
  39. return ($data['grant_type'] ?? '') === 'refresh_token';
  40. }],
  41. // 业务验证(按顺序执行)
  42. [
  43. 'client_id', new AppExistenceValidator($this, ['client_secret', 'app']),
  44. 'msg' => '应用不存在或密钥错误',
  45. 'when' => function($data) {
  46. return isset($data['client_id']) && isset($data['client_secret']);
  47. }
  48. ],
  49. [
  50. 'client_id', new AppStatusValidator($this, ['app']),
  51. 'msg' => '应用状态异常',
  52. 'when' => function($data) {
  53. return isset($data['client_id']);
  54. }
  55. ],
  56. [
  57. 'scope', new ScopePermissionValidator($this, ['app', 'scopes']),
  58. 'msg' => '权限范围验证失败',
  59. 'when' => function($data) {
  60. return isset($data['scope']) && isset($data['client_id']);
  61. }
  62. ],
  63. ];
  64. }
  65. /**
  66. * 默认值
  67. */
  68. public function default(): array
  69. {
  70. return [
  71. 'scope' => '',
  72. ];
  73. }
  74. }