ApiController.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. return json_decode(base64_decode($info),true);
  57. }
  58. public function makeEncryptData($data)
  59. {
  60. $key = Config::get('gm.key');
  61. $info = Gm::encrypt($key,(base64_encode(json_encode($data))));
  62. return $info;
  63. }
  64. public function getHeaderToken(): string
  65. {
  66. $header = getallheaders();
  67. $auth = $header['Authorization'];
  68. $data = explode(' ',$auth);
  69. return $data[1];
  70. }
  71. }