AiModelResource.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Http\Resources;
  3. use App\Http\Api\AiAssistantApi;
  4. use App\Services\AuthService;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Http\Resources\Json\JsonResource;
  7. class AiModelResource extends JsonResource
  8. {
  9. /**
  10. * 把资源转成数组。
  11. *
  12. * 字段白名单:绝不能回落到 parent::toArray(),那会把 key(第三方 API key)
  13. * 和 system_prompt 一并吐出去,而 index() 的 view=all / view=usable 分支
  14. * 对任何登录用户可见,等于公开泄漏所有模型的 API key。
  15. *
  16. * key / system_prompt 仅在请求者是 owner 本人时附带——dashboard 的模型编辑页
  17. * (AiModelEdit)需要回填这两个字段。
  18. *
  19. * @param Request $request
  20. * @return array
  21. */
  22. public function toArray($request)
  23. {
  24. $data = [
  25. 'uid' => $this->uid,
  26. 'name' => $this->name,
  27. 'description' => $this->description,
  28. 'url' => $this->url,
  29. 'model' => $this->model,
  30. 'privacy' => $this->privacy,
  31. 'owner_id' => $this->owner_id,
  32. 'editor_id' => $this->editor_id,
  33. 'created_at' => $this->created_at,
  34. 'updated_at' => $this->updated_at,
  35. 'user' => AiAssistantApi::userInfo($this),
  36. ];
  37. if ($this->isRequestedByOwner($request)) {
  38. $data['key'] = $this->key;
  39. $data['system_prompt'] = $this->system_prompt;
  40. }
  41. return $data;
  42. }
  43. /**
  44. * 请求者是否为本模型的 owner。
  45. *
  46. * 结果按请求缓存:index() 一次可返回上千行,逐行解一次 JWT 代价过高。
  47. */
  48. private function isRequestedByOwner($request): bool
  49. {
  50. if (! $request->attributes->has('auth.current')) {
  51. $request->attributes->set('auth.current', AuthService::current($request));
  52. }
  53. $user = $request->attributes->get('auth.current');
  54. return $user && $user['user_uid'] === $this->owner_id;
  55. }
  56. }