ThirdPartyCredential.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. <?php
  2. namespace App\Module\ThirdParty\Models;
  3. use UCore\ModelCore;
  4. use App\Module\ThirdParty\Enums\AUTH_TYPE;
  5. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  6. use Illuminate\Support\Facades\Crypt;
  7. /**
  8. * 第三方服务认证凭证模型
  9. *
  10. * field start
  11. * @property int $id 主键ID
  12. * @property int $service_id 服务ID
  13. * @property string $name 凭证名称
  14. * @property string $type 凭证类型
  15. * @property array $credentials 凭证信息(加密存储)
  16. * @property string $environment 环境(production/staging/development)
  17. * @property bool $is_active 是否激活
  18. * @property \Carbon\Carbon $expires_at 过期时间
  19. * @property \Carbon\Carbon $last_used_at 最后使用时间
  20. * @property int $usage_count 使用次数
  21. * @property \Carbon\Carbon $created_at 创建时间
  22. * @property \Carbon\Carbon $updated_at 更新时间
  23. * field end
  24. */
  25. class ThirdPartyCredential extends ModelCore
  26. {
  27. /**
  28. * 数据表名
  29. *
  30. * @var string
  31. */
  32. protected $table = 'thirdparty_credentials';
  33. /**
  34. * 属性类型转换
  35. *
  36. * @var array
  37. */
  38. protected $casts = [
  39. 'service_id' => 'integer',
  40. 'credentials' => 'array',
  41. 'is_active' => 'boolean',
  42. 'expires_at' => 'datetime',
  43. 'last_used_at' => 'datetime',
  44. 'usage_count' => 'integer',
  45. 'created_at' => 'datetime',
  46. 'updated_at' => 'datetime',
  47. ];
  48. /**
  49. * 隐藏的属性
  50. *
  51. * @var array
  52. */
  53. protected $hidden = [
  54. 'credentials',
  55. ];
  56. /**
  57. * 获取认证类型枚举
  58. *
  59. * @return AUTH_TYPE
  60. */
  61. public function getAuthTypeEnum(): AUTH_TYPE
  62. {
  63. return AUTH_TYPE::from($this->type);
  64. }
  65. /**
  66. * 获取认证类型标签
  67. *
  68. * @return string
  69. */
  70. public function getTypeLabel(): string
  71. {
  72. return $this->getAuthTypeEnum()->getLabel();
  73. }
  74. /**
  75. * 检查凭证是否已过期
  76. *
  77. * @return bool
  78. */
  79. public function isExpired(): bool
  80. {
  81. if (!$this->expires_at) {
  82. return false;
  83. }
  84. return now()->gt($this->expires_at);
  85. }
  86. /**
  87. * 检查凭证是否即将过期
  88. *
  89. * @param int $days 提前天数
  90. * @return bool
  91. */
  92. public function isExpiringSoon(int $days = 7): bool
  93. {
  94. if (!$this->expires_at) {
  95. return false;
  96. }
  97. return now()->addDays($days)->gte($this->expires_at);
  98. }
  99. /**
  100. * 检查凭证是否可用
  101. *
  102. * @return bool
  103. */
  104. public function isUsable(): bool
  105. {
  106. return $this->is_active && !$this->isExpired();
  107. }
  108. /**
  109. * 获取解密后的凭证信息
  110. *
  111. * @return array
  112. */
  113. public function getDecryptedCredentials(): array
  114. {
  115. if (!$this->credentials) {
  116. return [];
  117. }
  118. $decrypted = [];
  119. foreach ($this->credentials as $key => $value) {
  120. try {
  121. // 尝试解密,如果失败则返回原值
  122. $decrypted[$key] = is_string($value) ? Crypt::decryptString($value) : $value;
  123. } catch (\Exception $e) {
  124. $decrypted[$key] = $value;
  125. }
  126. }
  127. return $decrypted;
  128. }
  129. /**
  130. * 设置加密的凭证信息
  131. *
  132. * @param array $credentials
  133. * @return void
  134. */
  135. public function setEncryptedCredentials(array $credentials): void
  136. {
  137. $encrypted = [];
  138. foreach ($credentials as $key => $value) {
  139. // 只加密字符串类型的敏感信息
  140. if (is_string($value) && $this->isSensitiveField($key)) {
  141. $encrypted[$key] = Crypt::encryptString($value);
  142. } else {
  143. $encrypted[$key] = $value;
  144. }
  145. }
  146. $this->credentials = $encrypted;
  147. }
  148. /**
  149. * 检查字段是否为敏感信息
  150. *
  151. * @param string $field
  152. * @return bool
  153. */
  154. protected function isSensitiveField(string $field): bool
  155. {
  156. $sensitiveFields = [
  157. 'api_key',
  158. 'api_secret',
  159. 'access_token',
  160. 'refresh_token',
  161. 'client_secret',
  162. 'private_key',
  163. 'password',
  164. 'secret',
  165. 'app_secret',
  166. 'webhook_secret',
  167. ];
  168. return in_array(strtolower($field), $sensitiveFields);
  169. }
  170. /**
  171. * 获取特定的凭证值
  172. *
  173. * @param string $key
  174. * @param mixed $default
  175. * @return mixed
  176. */
  177. public function getCredential(string $key, $default = null)
  178. {
  179. $credentials = $this->getDecryptedCredentials();
  180. return $credentials[$key] ?? $default;
  181. }
  182. /**
  183. * 更新使用统计
  184. *
  185. * @return bool
  186. */
  187. public function updateUsageStats(): bool
  188. {
  189. return $this->update([
  190. 'last_used_at' => now(),
  191. 'usage_count' => $this->usage_count + 1,
  192. ]);
  193. }
  194. /**
  195. * 生成认证头
  196. *
  197. * @return array
  198. */
  199. public function generateAuthHeaders(): array
  200. {
  201. $authType = $this->getAuthTypeEnum();
  202. $credentials = $this->getDecryptedCredentials();
  203. $headers = [];
  204. switch ($authType) {
  205. case AUTH_TYPE::API_KEY:
  206. $headers[$authType->getHeaderName()] = $credentials['api_key'] ?? '';
  207. break;
  208. case AUTH_TYPE::BEARER:
  209. $headers[$authType->getHeaderName()] = $authType->getHeaderPrefix() . ($credentials['access_token'] ?? '');
  210. break;
  211. case AUTH_TYPE::BASIC:
  212. $username = $credentials['username'] ?? '';
  213. $password = $credentials['password'] ?? '';
  214. $headers[$authType->getHeaderName()] = $authType->getHeaderPrefix() . base64_encode($username . ':' . $password);
  215. break;
  216. case AUTH_TYPE::JWT:
  217. $headers[$authType->getHeaderName()] = $authType->getHeaderPrefix() . ($credentials['jwt_token'] ?? '');
  218. break;
  219. case AUTH_TYPE::SIGNATURE:
  220. // 签名认证需要根据具体的签名算法生成
  221. $headers['X-Signature'] = $this->generateSignature($credentials);
  222. break;
  223. case AUTH_TYPE::CUSTOM:
  224. // 自定义认证方式
  225. $headers = $credentials['custom_headers'] ?? [];
  226. break;
  227. }
  228. return $headers;
  229. }
  230. /**
  231. * 生成签名
  232. *
  233. * @param array $credentials
  234. * @return string
  235. */
  236. protected function generateSignature(array $credentials): string
  237. {
  238. // 这里需要根据具体的第三方服务的签名算法实现
  239. // 这是一个示例实现
  240. $appKey = $credentials['app_key'] ?? '';
  241. $appSecret = $credentials['app_secret'] ?? '';
  242. $timestamp = time();
  243. $nonce = uniqid();
  244. $signString = $appKey . $timestamp . $nonce . $appSecret;
  245. return hash('sha256', $signString);
  246. }
  247. /**
  248. * 关联第三方服务
  249. *
  250. * @return BelongsTo
  251. */
  252. public function service(): BelongsTo
  253. {
  254. return $this->belongsTo(ThirdPartyService::class, 'service_id');
  255. }
  256. /**
  257. * 验证凭证配置是否完整
  258. *
  259. * @return array ['valid' => bool, 'missing_fields' => array]
  260. */
  261. public function validateCredentials(): array
  262. {
  263. $authType = $this->getAuthTypeEnum();
  264. $requiredFields = $authType->getRequiredFields();
  265. $credentials = $this->getDecryptedCredentials();
  266. $missingFields = [];
  267. foreach ($requiredFields as $field) {
  268. if (empty($credentials[$field])) {
  269. $missingFields[] = $field;
  270. }
  271. }
  272. return [
  273. 'valid' => empty($missingFields),
  274. 'missing_fields' => $missingFields,
  275. ];
  276. }
  277. /**
  278. * 创建新的凭证
  279. *
  280. * @param array $data
  281. * @return static
  282. */
  283. public static function createCredential(array $data): static
  284. {
  285. $credential = new static();
  286. $credential->fill($data);
  287. // 加密敏感信息
  288. if (isset($data['credentials'])) {
  289. $credential->setEncryptedCredentials($data['credentials']);
  290. }
  291. $credential->save();
  292. return $credential;
  293. }
  294. }