ApiController.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\BlurUtils;
  4. use app\common\library\Gm;
  5. use think\facade\Cache;
  6. use think\facade\Config;
  7. class ApiController extends Api
  8. {
  9. /**
  10. * 无需解码的方法
  11. * 访问本控制器的此方法,无需解码
  12. * @var array
  13. */
  14. protected array $noAuth = [];
  15. protected $tokenData = null;
  16. protected function needAuthToken(): bool
  17. {
  18. return !action_in_arr($this->noAuth);
  19. }
  20. protected function initialize(): void
  21. {
  22. header("Access-Control-Allow-Origin: *");
  23. header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
  24. header("Access-Control-Allow-Headers: X-Requested-With");
  25. if($this->needAuthToken()) {
  26. $token = $this->getHeaderToken();
  27. $data = Cache::get($token);
  28. $this->tokenData = $data;
  29. if(empty($data))
  30. {
  31. // $this->error('无效的token');
  32. }
  33. }
  34. BlurUtils::setNotNeedBlur();
  35. }
  36. /**
  37. * $params $data
  38. */
  39. public function makeModelData($data,$mapping): array
  40. {
  41. $info = [];
  42. foreach ($data as $k=>$v)
  43. {
  44. if($info[$mapping[$k]] ?? '')
  45. {
  46. continue;
  47. }
  48. $info[$mapping[$k]] = $v;
  49. }
  50. return $info;
  51. }
  52. public function getDecryptData($data): array
  53. {
  54. $key = 'zLxapoeqWYpoeqWY';
  55. $info = Gm::decrypt($key,$data);
  56. if(empty($return))
  57. {
  58. return [];
  59. }else{
  60. return json_decode(base64_decode($info),true);
  61. }
  62. }
  63. public function makeEncryptData($data)
  64. {
  65. $key = Config::get('gm.key');
  66. $info = Gm::encrypt($key,(base64_encode(json_encode($data))));
  67. return $info;
  68. }
  69. public function getHeaderToken(): string
  70. {
  71. $header = getallheaders();
  72. $auth = $header['Authorization'] ?? '';
  73. $data = explode(' ',$auth);
  74. return $data[1] ?? '';
  75. }
  76. }