CredentialValidator.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. <?php
  2. namespace App\Module\ThirdParty\Validators;
  3. use App\Module\ThirdParty\Models\ThirdPartyService;
  4. use App\Module\ThirdParty\Models\ThirdPartyCredential;
  5. use App\Module\ThirdParty\Enums\AUTH_TYPE;
  6. /**
  7. * 第三方服务认证凭证验证器
  8. */
  9. class CredentialValidator
  10. {
  11. /**
  12. * 错误信息
  13. *
  14. * @var array
  15. */
  16. protected array $errors = [];
  17. /**
  18. * 验证创建凭证数据
  19. *
  20. * @param array $data
  21. * @return bool
  22. */
  23. public function validateCreate(array $data): bool
  24. {
  25. $this->errors = [];
  26. // 验证必填字段
  27. $this->validateRequired($data, [
  28. 'service_id' => '服务ID',
  29. 'name' => '凭证名称',
  30. 'type' => '认证类型',
  31. 'credentials' => '凭证信息',
  32. ]);
  33. // 验证字段格式
  34. $this->validateCredentialData($data);
  35. // 验证服务和认证类型匹配
  36. if (isset($data['service_id']) && isset($data['type'])) {
  37. $this->validateServiceAuthType($data['service_id'], $data['type']);
  38. }
  39. // 验证环境下的唯一性
  40. if (isset($data['service_id']) && isset($data['environment']) && ($data['is_active'] ?? true)) {
  41. $this->validateEnvironmentUnique($data['service_id'], $data['environment']);
  42. }
  43. return empty($this->errors);
  44. }
  45. /**
  46. * 验证更新凭证数据
  47. *
  48. * @param array $data
  49. * @param int $credentialId
  50. * @return bool
  51. */
  52. public function validateUpdate(array $data, int $credentialId): bool
  53. {
  54. $this->errors = [];
  55. // 验证字段格式
  56. $this->validateCredentialData($data);
  57. $credential = ThirdPartyCredential::find($credentialId);
  58. if (!$credential) {
  59. $this->addError('credential', '凭证不存在');
  60. return false;
  61. }
  62. // 验证服务和认证类型匹配
  63. if (isset($data['type'])) {
  64. $this->validateServiceAuthType($credential->service_id, $data['type']);
  65. }
  66. // 验证环境下的唯一性
  67. if (isset($data['is_active']) && $data['is_active']) {
  68. $environment = $data['environment'] ?? $credential->environment;
  69. $this->validateEnvironmentUnique($credential->service_id, $environment, $credentialId);
  70. }
  71. return empty($this->errors);
  72. }
  73. /**
  74. * 验证删除凭证
  75. *
  76. * @param int $credentialId
  77. * @return bool
  78. */
  79. public function validateDelete(int $credentialId): bool
  80. {
  81. $this->errors = [];
  82. $credential = ThirdPartyCredential::find($credentialId);
  83. if (!$credential) {
  84. $this->addError('credential', '凭证不存在');
  85. return false;
  86. }
  87. // 检查凭证状态
  88. if ($credential->is_active) {
  89. $this->addError('status', '激活状态的凭证无法删除,请先停用凭证');
  90. }
  91. // 检查最近使用记录
  92. if ($credential->last_used_at && $credential->last_used_at->gt(now()->subHours(1))) {
  93. $this->addError('usage', '凭证在1小时内有使用记录,无法删除');
  94. }
  95. return empty($this->errors);
  96. }
  97. /**
  98. * 验证凭证激活
  99. *
  100. * @param int $credentialId
  101. * @return bool
  102. */
  103. public function validateActivation(int $credentialId): bool
  104. {
  105. $this->errors = [];
  106. $credential = ThirdPartyCredential::find($credentialId);
  107. if (!$credential) {
  108. $this->addError('credential', '凭证不存在');
  109. return false;
  110. }
  111. // 检查凭证是否过期
  112. if ($credential->isExpired()) {
  113. $this->addError('expired', '凭证已过期,无法激活');
  114. }
  115. // 检查同环境下是否已有其他激活的凭证
  116. $existingActive = ThirdPartyCredential::where('service_id', $credential->service_id)
  117. ->where('environment', $credential->environment)
  118. ->where('is_active', true)
  119. ->where('id', '!=', $credentialId)
  120. ->exists();
  121. if ($existingActive) {
  122. $this->addError('environment', "环境 {$credential->environment} 下已有其他激活的凭证,请先停用其他凭证");
  123. }
  124. return empty($this->errors);
  125. }
  126. /**
  127. * 验证凭证数据
  128. *
  129. * @param array $data
  130. * @return void
  131. */
  132. protected function validateCredentialData(array $data): void
  133. {
  134. // 验证认证类型
  135. if (isset($data['type']) && !AUTH_TYPE::tryFrom($data['type'])) {
  136. $this->addError('type', '不支持的认证类型');
  137. }
  138. // 验证名称长度
  139. if (isset($data['name'])) {
  140. if (strlen($data['name']) < 2) {
  141. $this->addError('name', '凭证名称至少需要2个字符');
  142. }
  143. if (strlen($data['name']) > 100) {
  144. $this->addError('name', '凭证名称不能超过100个字符');
  145. }
  146. }
  147. // 验证环境
  148. if (isset($data['environment'])) {
  149. $validEnvironments = ['production', 'staging', 'development', 'testing'];
  150. if (!in_array($data['environment'], $validEnvironments)) {
  151. $this->addError('environment', '无效的环境类型');
  152. }
  153. }
  154. // 验证过期时间
  155. if (isset($data['expires_at']) && !empty($data['expires_at'])) {
  156. try {
  157. $expiresAt = new \DateTime($data['expires_at']);
  158. if ($expiresAt <= now()) {
  159. $this->addError('expires_at', '过期时间必须在未来');
  160. }
  161. } catch (\Exception $e) {
  162. $this->addError('expires_at', '过期时间格式无效');
  163. }
  164. }
  165. // 验证凭证信息
  166. if (isset($data['credentials']) && isset($data['type'])) {
  167. $this->validateCredentialsData($data['type'], $data['credentials']);
  168. }
  169. }
  170. /**
  171. * 验证凭证信息数据
  172. *
  173. * @param string $authType
  174. * @param array $credentials
  175. * @return void
  176. */
  177. protected function validateCredentialsData(string $authType, array $credentials): void
  178. {
  179. $authTypeEnum = AUTH_TYPE::tryFrom($authType);
  180. if (!$authTypeEnum) {
  181. return;
  182. }
  183. $requiredFields = $authTypeEnum->getRequiredFields();
  184. $missingFields = [];
  185. foreach ($requiredFields as $field) {
  186. if (empty($credentials[$field])) {
  187. $missingFields[] = $field;
  188. }
  189. }
  190. if (!empty($missingFields)) {
  191. $this->addError('credentials', '凭证配置不完整,缺少字段: ' . implode(', ', $missingFields));
  192. }
  193. // 验证特定字段格式
  194. $this->validateSpecificCredentialFields($authTypeEnum, $credentials);
  195. }
  196. /**
  197. * 验证特定凭证字段格式
  198. *
  199. * @param AUTH_TYPE $authType
  200. * @param array $credentials
  201. * @return void
  202. */
  203. protected function validateSpecificCredentialFields(AUTH_TYPE $authType, array $credentials): void
  204. {
  205. switch ($authType) {
  206. case AUTH_TYPE::API_KEY:
  207. if (isset($credentials['api_key']) && strlen($credentials['api_key']) < 10) {
  208. $this->addError('credentials', 'API Key长度至少需要10个字符');
  209. }
  210. break;
  211. case AUTH_TYPE::OAUTH2:
  212. if (isset($credentials['client_id']) && strlen($credentials['client_id']) < 5) {
  213. $this->addError('credentials', 'Client ID长度至少需要5个字符');
  214. }
  215. if (isset($credentials['client_secret']) && strlen($credentials['client_secret']) < 10) {
  216. $this->addError('credentials', 'Client Secret长度至少需要10个字符');
  217. }
  218. break;
  219. case AUTH_TYPE::JWT:
  220. if (isset($credentials['jwt_token'])) {
  221. $parts = explode('.', $credentials['jwt_token']);
  222. if (count($parts) !== 3) {
  223. $this->addError('credentials', 'JWT Token格式无效');
  224. }
  225. }
  226. break;
  227. case AUTH_TYPE::BASIC:
  228. if (isset($credentials['username']) && strlen($credentials['username']) < 2) {
  229. $this->addError('credentials', '用户名长度至少需要2个字符');
  230. }
  231. if (isset($credentials['password']) && strlen($credentials['password']) < 6) {
  232. $this->addError('credentials', '密码长度至少需要6个字符');
  233. }
  234. break;
  235. }
  236. }
  237. /**
  238. * 验证服务和认证类型匹配
  239. *
  240. * @param int $serviceId
  241. * @param string $authType
  242. * @return void
  243. */
  244. protected function validateServiceAuthType(int $serviceId, string $authType): void
  245. {
  246. $service = ThirdPartyService::find($serviceId);
  247. if (!$service) {
  248. $this->addError('service_id', '服务不存在');
  249. return;
  250. }
  251. if ($authType !== $service->auth_type) {
  252. $this->addError('type', "认证类型 {$authType} 与服务要求的 {$service->auth_type} 不匹配");
  253. }
  254. }
  255. /**
  256. * 验证环境下的唯一性
  257. *
  258. * @param int $serviceId
  259. * @param string $environment
  260. * @param int|null $excludeId
  261. * @return void
  262. */
  263. protected function validateEnvironmentUnique(int $serviceId, string $environment, ?int $excludeId = null): void
  264. {
  265. $query = ThirdPartyCredential::where('service_id', $serviceId)
  266. ->where('environment', $environment)
  267. ->where('is_active', true);
  268. if ($excludeId) {
  269. $query->where('id', '!=', $excludeId);
  270. }
  271. if ($query->exists()) {
  272. $this->addError('environment', "环境 {$environment} 下已有激活的凭证,请先停用现有凭证");
  273. }
  274. }
  275. /**
  276. * 验证必填字段
  277. *
  278. * @param array $data
  279. * @param array $required
  280. * @return void
  281. */
  282. protected function validateRequired(array $data, array $required): void
  283. {
  284. foreach ($required as $field => $label) {
  285. if (!isset($data[$field]) || empty($data[$field])) {
  286. $this->addError($field, "{$label}不能为空");
  287. }
  288. }
  289. }
  290. /**
  291. * 添加错误信息
  292. *
  293. * @param string $field
  294. * @param string $message
  295. * @return void
  296. */
  297. protected function addError(string $field, string $message): void
  298. {
  299. if (!isset($this->errors[$field])) {
  300. $this->errors[$field] = [];
  301. }
  302. $this->errors[$field][] = $message;
  303. }
  304. /**
  305. * 获取错误信息
  306. *
  307. * @return array
  308. */
  309. public function getErrors(): array
  310. {
  311. return $this->errors;
  312. }
  313. /**
  314. * 获取第一个错误信息
  315. *
  316. * @return string|null
  317. */
  318. public function getFirstError(): ?string
  319. {
  320. if (empty($this->errors)) {
  321. return null;
  322. }
  323. $firstField = array_key_first($this->errors);
  324. return $this->errors[$firstField][0] ?? null;
  325. }
  326. /**
  327. * 检查是否有错误
  328. *
  329. * @return bool
  330. */
  331. public function hasErrors(): bool
  332. {
  333. return !empty($this->errors);
  334. }
  335. }