ThirdPartyCredential.php 8.5 KB

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