BaseController.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. declare (strict_types=1);
  3. namespace app\api;
  4. use app\api\exception\ApiException;
  5. use app\common\until\Token;
  6. use app\common\until\Until;
  7. use think\App;
  8. use think\exception\ValidateException;
  9. use think\facade\Session;
  10. use think\Validate;
  11. /**
  12. * 控制器基础类
  13. */
  14. abstract class BaseController {
  15. /**
  16. * Request实例
  17. * @var \think\Request
  18. */
  19. protected $request;
  20. /**
  21. * 应用实例
  22. * @var \think\App
  23. */
  24. protected $app;
  25. /**
  26. * 是否批量验证
  27. * @var bool
  28. */
  29. protected $batchValidate = false;
  30. /**
  31. * 控制器中间件
  32. * @var array
  33. */
  34. protected $middleware = [];
  35. public $userId = 0;
  36. public $isAdmin = 0;
  37. public $adminId = 0;
  38. /**
  39. * 构造方法
  40. * @access public
  41. * @param App $app 应用对象
  42. */
  43. public function __construct(App $app) {
  44. $this->app = $app;
  45. $this->request = $this->app->request;
  46. Session::start();
  47. //$this->request['Accept'] = 'application/json';
  48. Until::$startTime = time();
  49. $route = [
  50. 'token/getToken',
  51. 'index',
  52. 'user/login',
  53. 'user/save',
  54. 'admin/login',
  55. 'admin/verifyimg',
  56. 'order/notifyorder',
  57. 'product/typelist',
  58. 'store/getstore',
  59. 'product/index',
  60. 'Server/callService',
  61. 'Server/callList'
  62. ];
  63. foreach ($route as &$rule){
  64. $rule = '/api/'.strtolower($rule);
  65. }
  66. unset($rule);
  67. if (!in_array(strtolower($this->request->baseUrl()), $route)) {
  68. if (empty($this->request->header('token'))) {
  69. throw new ApiException('token不为空');
  70. }
  71. $token = new Token();
  72. $decodeToken = $token->decodeToken();
  73. $this->userId = $decodeToken['userId'];
  74. Until::$userId = $this->userId;
  75. $this->isAdmin = $decodeToken['isAdmin'];
  76. Until::$isAdmin = $this->isAdmin();
  77. $this->adminId = $decodeToken['adminId'];
  78. Until::$adminId = $this->adminId;
  79. }
  80. // 控制器初始化
  81. $this->initialize();
  82. }
  83. // 初始化
  84. protected function initialize() {
  85. }
  86. protected function isAdmin() {
  87. if ($this->isAdmin == 1) {
  88. Until::$isAdmin = true;
  89. return true;
  90. }
  91. Until::$isAdmin = false;
  92. return false;
  93. }
  94. }