| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- <?php
- namespace App\Module\OpenAPI\Validators;
- use App\Module\OpenAPI\Models\OpenApiApp;
- use UCore\Validator;
- /**
- * 应用存在性验证器
- */
- class AppExistenceValidator extends Validator
- {
- /**
- * 验证应用是否存在且密钥正确
- *
- * @param mixed $value 应用ID
- * @param array $data 包含应用密钥的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- // 从 args 获取参数
- $secretKey = $this->args[0] ?? 'client_secret';
- $appKey = $this->args[1] ?? 'app';
- $appSecret = $data[$secretKey] ?? null;
- if (!$appSecret) {
- $this->addError('应用密钥不能为空');
- return false;
- }
- // 验证应用ID格式
- if (!$this->validateAppIdFormat($value)) {
- return false;
- }
- // 验证应用密钥格式
- if (!$this->validateAppSecretFormat($appSecret)) {
- return false;
- }
- try {
- // 查询应用
- $app = OpenApiApp::where('app_id', $value)->first();
- if (!$app) {
- $this->addError('应用不存在');
- return false;
- }
- // 验证密钥
- if ($app->app_secret !== $appSecret) {
- $this->addError('应用密钥错误');
- return false;
- }
- // 将应用对象保存到验证对象中,供后续验证器使用
- $this->validation->$appKey = $app;
- return true;
- } catch (\Exception $e) {
- $this->addError('验证应用信息时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- /**
- * 验证应用ID格式
- *
- * @param string $appId
- * @return bool
- */
- protected function validateAppIdFormat(string $appId): bool
- {
- if (empty($appId)) {
- $this->addError('应用ID不能为空');
- return false;
- }
- if (strlen($appId) !== 32) {
- $this->addError('应用ID长度必须为32位');
- return false;
- }
- if (!ctype_alnum($appId)) {
- $this->addError('应用ID只能包含字母和数字');
- return false;
- }
- return true;
- }
- /**
- * 验证应用密钥格式
- *
- * @param string $appSecret
- * @return bool
- */
- protected function validateAppSecretFormat(string $appSecret): bool
- {
- if (empty($appSecret)) {
- $this->addError('应用密钥不能为空');
- return false;
- }
- if (strlen($appSecret) !== 64) {
- $this->addError('应用密钥长度必须为64位');
- return false;
- }
- if (!ctype_alnum($appSecret)) {
- $this->addError('应用密钥只能包含字母和数字');
- return false;
- }
- return true;
- }
- }
|