AppExistenceValidator.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. namespace App\Module\OpenAPI\Validators;
  3. use App\Module\OpenAPI\Models\OpenApiApp;
  4. use UCore\Validator;
  5. /**
  6. * 应用存在性验证器
  7. */
  8. class AppExistenceValidator extends Validator
  9. {
  10. /**
  11. * 验证应用是否存在且密钥正确
  12. *
  13. * @param mixed $value 应用ID
  14. * @param array $data 包含应用密钥的数组
  15. * @return bool 验证是否通过
  16. */
  17. public function validate(mixed $value, array $data): bool
  18. {
  19. // 从 args 获取参数
  20. $secretKey = $this->args[0] ?? 'client_secret';
  21. $appKey = $this->args[1] ?? 'app';
  22. $appSecret = $data[$secretKey] ?? null;
  23. if (!$appSecret) {
  24. $this->addError('应用密钥不能为空');
  25. return false;
  26. }
  27. // 验证应用ID格式
  28. if (!$this->validateAppIdFormat($value)) {
  29. return false;
  30. }
  31. // 验证应用密钥格式
  32. if (!$this->validateAppSecretFormat($appSecret)) {
  33. return false;
  34. }
  35. try {
  36. // 查询应用
  37. $app = OpenApiApp::where('app_id', $value)->first();
  38. if (!$app) {
  39. $this->addError('应用不存在');
  40. return false;
  41. }
  42. // 验证密钥
  43. if ($app->app_secret !== $appSecret) {
  44. $this->addError('应用密钥错误');
  45. return false;
  46. }
  47. // 将应用对象保存到验证对象中,供后续验证器使用
  48. $this->validation->$appKey = $app;
  49. return true;
  50. } catch (\Exception $e) {
  51. $this->addError('验证应用信息时发生错误: ' . $e->getMessage());
  52. return false;
  53. }
  54. }
  55. /**
  56. * 验证应用ID格式
  57. *
  58. * @param string $appId
  59. * @return bool
  60. */
  61. protected function validateAppIdFormat(string $appId): bool
  62. {
  63. if (empty($appId)) {
  64. $this->addError('应用ID不能为空');
  65. return false;
  66. }
  67. if (strlen($appId) !== 32) {
  68. $this->addError('应用ID长度必须为32位');
  69. return false;
  70. }
  71. if (!ctype_alnum($appId)) {
  72. $this->addError('应用ID只能包含字母和数字');
  73. return false;
  74. }
  75. return true;
  76. }
  77. /**
  78. * 验证应用密钥格式
  79. *
  80. * @param string $appSecret
  81. * @return bool
  82. */
  83. protected function validateAppSecretFormat(string $appSecret): bool
  84. {
  85. if (empty($appSecret)) {
  86. $this->addError('应用密钥不能为空');
  87. return false;
  88. }
  89. if (strlen($appSecret) !== 64) {
  90. $this->addError('应用密钥长度必须为64位');
  91. return false;
  92. }
  93. if (!ctype_alnum($appSecret)) {
  94. $this->addError('应用密钥只能包含字母和数字');
  95. return false;
  96. }
  97. return true;
  98. }
  99. }