Controller.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. <?php
  2. /**
  3. * Controller is the customized base controller class.
  4. * All controller classes for this application should extend from this base class.
  5. */
  6. class Controller extends CController
  7. {
  8. /**
  9. * @var string the default layout for the controller view. Defaults to '//layouts/column1',
  10. * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
  11. */
  12. public $layout='//layouts/column1';
  13. public array $authIds = [];
  14. public array $companyIds = [];
  15. public array $schoolIds = [];
  16. private int $_userId = 0;
  17. /**
  18. * 检查请求方是否合法
  19. * @return void
  20. * @throws CHttpException
  21. */
  22. public function checkRequest(): void
  23. {
  24. if (LWM_ENV == 'dev') {
  25. header("Access-Control-Allow-Origin: *");
  26. } else {
  27. if (!str_contains(Yii::app()->request->hostInfo, Yii::app()->params['url'])) {
  28. throw new CHttpException(403, '非法访问');
  29. }
  30. header("Access-Control-Allow-Origin:" . Yii::app()->request->hostInfo);
  31. }
  32. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  33. header("Access-Control-Allow-Headers: Content-Type, Authorization, Cookie");
  34. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  35. exit(0); // 预检请求直接返回
  36. }
  37. }
  38. public function checkSign()
  39. {
  40. if (!\Yii::app()->request->isPostRequest || !empty($_FILES)) {
  41. return true;
  42. }
  43. if (!isset($_POST['sign'])) {
  44. return false;
  45. }
  46. if (!isset($_POST['timestamp']) || $_POST['timestamp'] < time() - 10) {
  47. return false;
  48. }
  49. $postSign = $_POST['sign'];
  50. unset($_POST['sign']); // 签名不计算sign
  51. $stringArray = []; // 对参与签名的参数进行排序
  52. foreach ($_POST as $k => $v) {
  53. if (is_array($v)) {
  54. $v = implode(',', $v);
  55. }
  56. $stringArray[] = $k . '=' . trim($v);
  57. }
  58. sort($stringArray, SORT_STRING);
  59. $query = implode('&', $stringArray);
  60. $sign = strtoupper(hash('sha256', $query . 'qwer'));
  61. if ($sign != $postSign) {
  62. Logger::errorMult($query, $sign);
  63. \CVarDumper::dump([$query, $sign, $postSign], 6, 1);die;
  64. }
  65. return $postSign == $sign;
  66. }
  67. /**
  68. * @throws CHttpException
  69. */
  70. public function beforeAction($action): bool
  71. {
  72. $this->checkRequest();
  73. $token = $_SERVER['HTTP_AUTHORIZATION']?? '';
  74. $data = RedisInstance::getInstance()->get('user_token:'.$token);
  75. $this->_userId = $data['id']?? 0;
  76. Yii::app()->language = 'zh_cn';
  77. $controller = Yii::app()->controller->id;
  78. $action = $this->getAction()->getId();
  79. $path = strtolower($controller . '/'. $action);
  80. if( !in_array($controller, ['site'])
  81. &&!in_array($path, LewaimaiAdminPingtaiAuth::$noLoginRouters)
  82. && !$this->_userId
  83. ){
  84. Helper::error('请先登入', 401);
  85. }
  86. if (!$this->checkSign()) {
  87. Helper::error('签名错误', 402);
  88. }
  89. // 获取权限相关数据
  90. $this->_formatAuth();
  91. if (!LewaimaiAdminPingtaiAuth::adminAuth($controller, $action)
  92. && (!$this->_userId && $this->_userId != 1)
  93. ) {
  94. Helper::error('您没有相应的权限');
  95. }
  96. return true;
  97. }
  98. private function _formatAuth(): void
  99. {
  100. $key = 'user_auth_' . $this->_userId;
  101. $data = RedisInstance::getInstance()->get($key);
  102. if (!$data) {
  103. $model = Useradmin::model()->findByPk($this->_userId);
  104. $authIds = DB::getScalerWithCriteria(
  105. 'role',
  106. DbCriteria::simpleCompare(['id' => $model->role_id])->setSelect('auth_ids')
  107. );
  108. $this->authIds = $authIds ? explode(',', $authIds) : [];
  109. $this->companyIds = $model->company_ids ? explode(',', $model->company_ids) : [];
  110. $this->schoolIds = $model->school_ids ? explode(',', $model->school_ids) : [];
  111. $json = json_encode([
  112. 'authIds' => $this->authIds,
  113. 'companyIds' => $this->companyIds,
  114. 'schoolIds' => $this->schoolIds,
  115. ]);
  116. RedisInstance::getInstance()->set($key, $json, 86400);
  117. } else {
  118. $data = json_decode($data, true);
  119. $this->authIds = $data['authIds'];
  120. $this->companyIds = $data['companyIds'];
  121. $this->schoolIds = $data['schoolIds'];
  122. }
  123. LewaimaiAdminPingtaiAuth::$authIds = $this->authIds;
  124. }
  125. public function clearAuth($id = 0)
  126. {
  127. $id = $id ? : $this->_userId;
  128. RedisInstance::getInstance()->delete('user_auth_' . $id);
  129. }
  130. public function getUserId()
  131. {
  132. return $this->_userId;
  133. }
  134. public function getSchoolFilter($filed = 'school_id'):?array
  135. {
  136. if ($this->_userId == 1 || in_array(-1, $this->companyIds)) {
  137. return null;
  138. }
  139. return $this->schoolIds;
  140. }
  141. public function checkSchoolId(int $id):bool
  142. {
  143. if ($this->_userId == 1 || in_array(-1, $this->schoolIds)) {
  144. return true;
  145. }
  146. return in_array($id, $this->schoolIds);
  147. }
  148. public function getCompanyFilter():?array
  149. {
  150. if ($this->_userId == 1 || in_array(-1, $this->companyIds)) {
  151. return null;
  152. }
  153. return $this->companyIds;
  154. }
  155. public function checkCompanyId(int $id):bool
  156. {
  157. if ($this->_userId == 1 || in_array(-1, $this->companyIds)) {
  158. return true;
  159. }
  160. return in_array($id, $this->companyIds);
  161. }
  162. }