ThirdPartyCredential.php 8.5 KB

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