Controller.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. public int $authType = AUTH_TYPE_COMPANY_SCHOOL;
  17. private int $_userId = 0;
  18. /**
  19. * 检查请求方是否合法
  20. * @return void
  21. * @throws CHttpException
  22. */
  23. public function checkRequest(): void
  24. {
  25. if (LWM_ENV == 'dev') {
  26. header("Access-Control-Allow-Origin: *");
  27. } else {
  28. if (!str_contains(Yii::app()->request->hostInfo, Yii::app()->params['url'])) {
  29. throw new CHttpException(403, '非法访问');
  30. }
  31. header("Access-Control-Allow-Origin:" . Yii::app()->request->hostInfo);
  32. }
  33. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  34. header("Access-Control-Allow-Headers: Content-Type, Authorization, Cookie");
  35. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  36. exit(0); // 预检请求直接返回
  37. }
  38. }
  39. public function checkSign()
  40. {
  41. if (!\Yii::app()->request->isPostRequest || !empty($_FILES)) {
  42. return true;
  43. }
  44. if (!isset($_POST['sign'])) {
  45. return false;
  46. }
  47. if (!isset($_POST['timestamp']) || $_POST['timestamp'] < time() - 10) {
  48. return false;
  49. }
  50. $postSign = $_POST['sign'];
  51. unset($_POST['sign']); // 签名不计算sign
  52. $stringArray = []; // 对参与签名的参数进行排序
  53. foreach ($_POST as $k => $v) {
  54. if (is_array($v)) {
  55. $v = implode(',', $v);
  56. }
  57. $stringArray[] = $k . '=' . trim($v);
  58. }
  59. sort($stringArray, SORT_STRING);
  60. $query = implode('&', $stringArray);
  61. $sign = strtoupper(hash('sha256', $query . 'qwer'));
  62. if ($sign != $postSign) {
  63. Logger::errorMult($query, $sign);
  64. \CVarDumper::dump([$query, $sign, $postSign], 6, 1);die;
  65. }
  66. return $postSign == $sign;
  67. }
  68. /**
  69. * 限制操作频率
  70. * @param $second
  71. * @return void|null
  72. * @throws RedisException
  73. */
  74. public function dobuleCheck($second = 3)
  75. {
  76. $key = 'dobule_' . $this->_userId;
  77. if (!RedisInstance::getInstance()->setNx($key, 1, $second)) {
  78. return Helper::error('操作过于频繁');
  79. }
  80. }
  81. /**
  82. * @throws CHttpException
  83. */
  84. public function beforeAction($action): bool
  85. {
  86. $this->checkRequest();
  87. $token = $_SERVER['HTTP_AUTHORIZATION']?? '';
  88. $data = RedisInstance::getInstance()->get('user_token:'.$token);
  89. $this->_userId = $data['id']?? 0;
  90. Yii::app()->language = 'zh_cn';
  91. $controller = Yii::app()->controller->id;
  92. $action = $this->getAction()->getId();
  93. $path = strtolower($controller . '/'. $action);
  94. if( !in_array($controller, ['site'])
  95. &&!in_array($path, LewaimaiAdminPingtaiAuth::$noLoginRouters)
  96. && !$this->_userId
  97. ){
  98. Helper::error('请先登入', 401);
  99. }
  100. if (!$this->checkSign()) {
  101. Helper::error('签名错误', 402);
  102. }
  103. // 获取权限相关数据
  104. $this->_formatAuth();
  105. if (!LewaimaiAdminPingtaiAuth::adminAuth($controller, $action)
  106. && ($this->_userId && $this->_userId != 1)
  107. ) {
  108. Helper::error('您没有相应的权限');
  109. }
  110. return true;
  111. }
  112. private function _formatAuth(): void
  113. {
  114. $key = 'user_auth_' . $this->_userId;
  115. $data = RedisInstance::getInstance()->get($key);
  116. if (!$data) {
  117. $user = DB::getInfoWithCriteria('useradmin', DbCriteria::simpleCompare(['u.id' => $this->_userId])
  118. ->setAlias('u')
  119. ->setSelect('company_ids, school_ids, date_auth_type, auth_ids,cities')
  120. ->setJoin('left join wx_role r ON r.id = u.role_id'));
  121. if (!$user) {
  122. throw new CHttpException(401, '用户不存在');
  123. }
  124. $this->authIds = $user['auth_ids'] ? explode(',', $user['auth_ids']) : [];
  125. $this->authType = $user['date_auth_type'];
  126. if ($this->authType == AUTH_TYPE_COMPANY_SCHOOL) {
  127. $this->companyIds = $user['company_ids'] ? explode(',', $user['company_ids']) : [];
  128. $this->schoolIds = $user['school_ids'] ? explode(',', $user['school_ids']) : [];
  129. } elseif ($this->authType == AUTH_TYPE_CITY) {
  130. $cities = array_filter(explode(',', $user['cities']));
  131. if ($cities) {
  132. $this->companyIds = Helper::arrayColumn(DB::getListWithCriteria('company', DbCriteria::simpleCompare(['is_del' => 0, 'city' => $cities])->setSelect('id')), 'id') ?: [-9999];
  133. $this->schoolIds = Helper::arrayColumn(DB::getListWithCriteria('school', DbCriteria::simpleCompare(['is_del' => 0, 'city' => $cities])->setSelect('id')), 'id') ?: [-9999];
  134. } else {
  135. $this->companyIds = [-9999];
  136. $this->schoolIds = [-9999];
  137. }
  138. } else {
  139. $this->companyIds = [-1];
  140. $this->schoolIds = [-1];
  141. }
  142. $json = json_encode([
  143. 'authIds' => $this->authIds,
  144. 'companyIds' => $this->companyIds,
  145. 'schoolIds' => $this->schoolIds,
  146. 'authType' => $this->authType,
  147. ]);
  148. RedisInstance::getInstance()->set($key, $json, 86400);
  149. } else {
  150. $data = json_decode($data, true);
  151. $this->authIds = $data['authIds'];
  152. $this->companyIds = $data['companyIds'];
  153. $this->schoolIds = $data['schoolIds'];
  154. $this->authType = $data['authType']?? AUTH_TYPE_COMPANY_SCHOOL;
  155. }
  156. LewaimaiAdminPingtaiAuth::$authIds = $this->authIds;
  157. }
  158. public function clearAuth($id = 0)
  159. {
  160. $id = $id ? : $this->_userId;
  161. RedisInstance::getInstance()->delete('user_auth_' . $id);
  162. }
  163. public function clearAuthByCity(string $city): void
  164. {
  165. // 清除缓存
  166. $cri = DbCriteria::simpleCompare(['status' => 1])
  167. ->setSelect('id')
  168. ->addCondition("find_in_set('{$city}', cities)");
  169. $users = DB::getListWithCriteria('useradmin', $cri)?:[];
  170. Logger::errorMult('auth_change', $users);
  171. foreach ($users['records'] as $user) {
  172. $this->clearAuth($user['id']);
  173. }
  174. }
  175. public function getUserId()
  176. {
  177. return $this->_userId;
  178. }
  179. public function getSchoolFilter($filed = 'school_id'):?array
  180. {
  181. if ($this->_userId == 1 || in_array(-1, $this->companyIds)) {
  182. return null;
  183. }
  184. return $this->schoolIds;
  185. }
  186. public function checkSchoolId(int $id):bool
  187. {
  188. if ($this->_userId == 1 || in_array(-1, $this->schoolIds)) {
  189. return true;
  190. }
  191. return in_array($id, $this->schoolIds);
  192. }
  193. public function getCompanyFilter():?array
  194. {
  195. if ($this->_userId == 1 || in_array(-1, $this->companyIds)) {
  196. return null;
  197. }
  198. return $this->companyIds;
  199. }
  200. public function checkCompanyId(int $id):bool
  201. {
  202. if ($this->_userId == 1 || in_array(-1, $this->companyIds)) {
  203. return true;
  204. }
  205. return in_array($id, $this->companyIds);
  206. }
  207. }