UserAuth.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/2/28
  6. * Time: 上午10:31
  7. */
  8. namespace frontendApi\modules\v1\components;
  9. use common\components\Redis;
  10. use common\components\Request;
  11. use common\helpers\Date;
  12. use common\helpers\Form;
  13. use common\helpers\http\BackendToFrontendApi;
  14. use common\models\Message;
  15. use common\models\UserInfo;
  16. use common\models\UserToken;
  17. use common\helpers\Log;
  18. use Yii;
  19. use yii\db\ActiveRecordInterface;
  20. use yii\web\HttpException;
  21. use yii\web\IdentityInterface;
  22. use yii\web\User;
  23. class UserAuth extends User {
  24. private $_userId = null;
  25. private $_apiIdentity = null;
  26. private $_token = null;
  27. private $_userInfo = null;
  28. private $_device = null;
  29. private static $_isQuicklyLogin = false;
  30. /**
  31. * 初始化设备信息
  32. * @throws \yii\base\InvalidConfigException
  33. */
  34. public function init() {
  35. parent::init();
  36. $this->_device = Yii::$app->request->getDevice();
  37. }
  38. /**
  39. * 首次以用户名和密码的方式登录
  40. * @param IdentityInterface $identity
  41. * @return bool
  42. * @throws HttpException
  43. */
  44. public function loginWithUAndP(IdentityInterface $identity) {
  45. if ($this->beforeLogin($identity, false, 0)) {
  46. $id = $identity->getId();
  47. $ip = Yii::$app->getRequest()->getUserIP();
  48. $this->_userId = $identity['ID'];
  49. $this->_apiIdentity = $identity;
  50. $this->_userInfo = [
  51. 'id' => $identity['ID'],
  52. 'userName' => $identity['USER_NAME'],
  53. 'accessTokenUpdatedAt' => Date::nowTime(),
  54. 'ip' => $ip,
  55. ];
  56. UserInfo::updateAll(['LAST_LOGIN_IP' => $ip, 'LAST_LOGIN_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID'=>$identity['ID']]);
  57. $userToken = UserToken::findOne(['USER_ID' => $identity['ID']]);
  58. if (!$userToken) {
  59. $userToken = new UserToken();
  60. $userToken->USER_ID = $identity['ID'];
  61. $userToken->CREATED_AT = Date::nowTime();
  62. if (!$userToken->save()) {
  63. throw new HttpException(500, Form::formatErrorsForApi($userToken->getErrors()), 500);
  64. }
  65. }
  66. $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'access');
  67. $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'refresh');
  68. //// Log::adminLoginInfo();
  69. $this->afterLogin($identity, false, 0);
  70. }
  71. return !$this->getIsGuest();
  72. }
  73. /**
  74. * 登录成功之后
  75. * @param IdentityInterface $identity
  76. * @param bool $cookieBased
  77. * @param int $duration
  78. * @throws \yii\base\Exception
  79. */
  80. public function afterLogin($identity, $cookieBased, $duration) {
  81. // 拉取站内信
  82. Message::pullMsgByUser($identity['ID']);
  83. parent::afterLogin($identity, $cookieBased, $duration);
  84. }
  85. /**
  86. * 已AccessToken方式登录(即平时直接访问)
  87. * @param string $token
  88. * @param null $type
  89. * @return null|IdentityInterface
  90. */
  91. public function loginByAccessToken($token, $type = null) {
  92. /* @var $class IdentityInterface */
  93. $class = $this->identityClass;
  94. $userId = $this->_userId = $class::findIdentityByAccessToken($token, $type);
  95. if ($userId) {
  96. $this->_userInfo = [
  97. 'id' => $userId,
  98. 'userName' => Yii::$app->tokenRedis->hget($token, 'USER_NAME'),
  99. 'accessTokenUpdatedAt' => Yii::$app->tokenRedis->hget($token, 'TOKEN_UPDATED_AT'),
  100. 'ip' => Yii::$app->getRequest()->getUserIP(),
  101. ];
  102. return $userId;
  103. } else {
  104. return null;
  105. }
  106. }
  107. /**
  108. * 从后台登录前台
  109. * @param $userId
  110. * @return null
  111. * @throws HttpException
  112. */
  113. public function loginByBackend($userId) {
  114. if (UserInfo::find()->where(['USER_ID' => $userId])->exists()) {
  115. $userToken = UserToken::findOne(['USER_ID' => $userId]);
  116. if (!$userToken) {
  117. $userToken = new UserToken();
  118. $userToken->USER_ID = $userId;
  119. $userToken->CREATED_AT = Date::nowTime();
  120. if (!$userToken->save()) {
  121. return null;
  122. }
  123. }
  124. self::$_isQuicklyLogin = true;
  125. $accessTokenResult = $this->updateToken($userToken, $appType = 'pc', $typeToken = 'access', $userId);
  126. $refreshTokenResult = $this->updateToken($userToken, $appType = 'pc', $typeToken = 'refresh', $userId);
  127. if ($accessTokenResult && $refreshTokenResult) {
  128. return $this->getToken();
  129. } else {
  130. return null;
  131. }
  132. } else {
  133. return null;
  134. }
  135. }
  136. /**
  137. * 用refreshToken生成新的accessToken和refreshToken
  138. * @param $refreshToken
  139. * @return bool
  140. * @throws HttpException
  141. */
  142. public function refreshToken($refreshToken) {
  143. if (!$refreshToken) {
  144. return false;
  145. }
  146. $userId = Yii::$app->tokenRedis->hget($refreshToken, 'ID');
  147. if (!$userId) {
  148. return false;
  149. }
  150. $userToken = UserToken::findOne(['USER_ID' => $userId]);
  151. $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'access', $userId);
  152. $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'refresh', $userId);
  153. return true;
  154. }
  155. /**
  156. * 用refreshToken生成新的accessToken
  157. * @param $refreshToken
  158. * @return bool
  159. * @throws HttpException
  160. */
  161. public function refreshAccessToken($refreshToken) {
  162. if (!$refreshToken) {
  163. return false;
  164. }
  165. $userId = Yii::$app->tokenRedis->hget($refreshToken, 'ID');
  166. if (!$userId) {
  167. return false;
  168. }
  169. $userToken = UserToken::findOne(['USER_ID' => $userId]);
  170. return $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'access', $userId);
  171. }
  172. /**
  173. * 用refreshToken生成新的refreshToken
  174. * @param $refreshToken
  175. * @return bool
  176. * @throws HttpException
  177. */
  178. public function refreshRefreshToken($refreshToken) {
  179. if (!$refreshToken) {
  180. return false;
  181. }
  182. $userId = Yii::$app->tokenRedis->hget($refreshToken, 'ID');
  183. if (!$userId) {
  184. return false;
  185. }
  186. $userToken = UserToken::findOne(['USER_ID' => $userId]);
  187. return $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'refresh', $userId);
  188. }
  189. /**
  190. * 更新token 的具体方法
  191. * @param ActiveRecordInterface $userTokenModel
  192. * @param string $appType (pc|app)
  193. * @param string $typeToken
  194. * @param $userId
  195. * @return bool
  196. * @throws HttpException
  197. */
  198. public function updateToken(ActiveRecordInterface $userTokenModel, $appType = Request::DEVICE_PC, $typeToken = 'access', $userId = 0) {
  199. $tokenField = strtoupper($appType . '_' . $typeToken . '_TOKEN');
  200. $updateField = '';
  201. $expiresIn = 0;
  202. if ($appType === Request::DEVICE_PC) {
  203. if ($typeToken === 'access') {
  204. $updateField = 'PAT_UPDATED_AT';
  205. $expiresIn = Yii::$app->params['frontAccessTokenExpiresIn'];
  206. } elseif ($typeToken === 'refresh') {
  207. $updateField = 'PRT_UPDATED_AT';
  208. $expiresIn = Yii::$app->params['frontRefreshTokenExpiresIn'];
  209. } else {
  210. throw new HttpException(500, 'token字段错误', 500);
  211. }
  212. } elseif ($appType === Request::DEVICE_APP) {
  213. if ($typeToken === 'access') {
  214. $updateField = 'AAT_UPDATED_AT';
  215. $expiresIn = Yii::$app->params['frontAccessTokenExpiresIn'];
  216. } elseif ($typeToken === 'refresh') {
  217. $updateField = 'ART_UPDATED_AT';
  218. $expiresIn = Yii::$app->params['frontRefreshTokenExpiresIn'];
  219. } else {
  220. throw new HttpException(500, 'token字段错误', 500);
  221. }
  222. }
  223. // 老token
  224. $oldToken = $userTokenModel->$tokenField;
  225. // 生成 access_token
  226. /* @var $identityClass IdentityInterface */
  227. $identityClass = $this->identityClass;
  228. $generateTokenMethodName = 'generate' . ucfirst($typeToken) . 'Token';
  229. //$token = $identityClass::generateAccessToken();
  230. $token = call_user_func([$identityClass, $generateTokenMethodName], $appType);
  231. $userTokenModel->$tokenField = $token;
  232. $userTokenModel->$updateField = Date::nowTime();
  233. if (!$userTokenModel->save()) {
  234. throw new HttpException(500, 'token更新失败', 500);
  235. }
  236. // 查找TOKEN中是否有同一用户产生的垃圾token,有的话就清除
  237. Yii::$app->tokenRedis->del($oldToken);
  238. $identity = $this->_apiIdentity;
  239. if (!$this->_apiIdentity) {
  240. if (!$userId) {
  241. throw new HttpException(500, 'userId不能为空', 500);
  242. }
  243. $identity = $identityClass::findIdentity($userId);
  244. }
  245. // 把 accessToken 当做key存入redis中内容为会员的ID和用户名
  246. Yii::$app->tokenRedis->hset($token, 'ID', $identity['ID']);
  247. Yii::$app->tokenRedis->hset($token, 'USER_NAME', $identity['USER_NAME']);
  248. Yii::$app->tokenRedis->hset($token, 'TOKEN_UPDATED_AT', $userTokenModel->$updateField);
  249. Yii::$app->tokenRedis->expire($token, $expiresIn);
  250. // 标记为快速登录的会员
  251. if (self::$_isQuicklyLogin) {
  252. Yii::$app->redis->setex(Redis::key(\frontendApi\modules\v1\models\User::CACHE_IS_QUICKLY_LOGIN . $token), Yii::$app->params['frontAccessTokenExpiresIn'], 1);
  253. }
  254. $this->_token = array_merge($this->_token ? $this->_token : [], [
  255. $typeToken . 'Token' => $token,
  256. $typeToken . 'TokenExpiresIn' => $expiresIn,
  257. $typeToken . 'TokenUpdateAt' => $userTokenModel->$updateField,
  258. ]);
  259. return true;
  260. }
  261. /**
  262. * 获取管理员ID
  263. * @return int|null|string
  264. */
  265. public function getId() {
  266. return $this->_userId;
  267. }
  268. /**
  269. * 获取token
  270. * @return null
  271. */
  272. public function getToken() {
  273. return $this->_token;
  274. }
  275. /**
  276. * 获取管理员信息
  277. * @return null
  278. */
  279. public function getUserInfo() {
  280. return $this->_userInfo;
  281. }
  282. /**
  283. * 获取身份信息
  284. * @param bool $autoRenew
  285. * @return null|IdentityInterface
  286. */
  287. public function getIdentity($autoRenew = true) {
  288. if ($this->_apiIdentity) {
  289. return $this->_apiIdentity;
  290. } else {
  291. if ($this->_userId) {
  292. /* @var $class IdentityInterface */
  293. $class = $this->identityClass;
  294. return $class::findOne(['ID' => $this->_userId]);
  295. } else {
  296. return null;
  297. }
  298. }
  299. }
  300. /**
  301. * 获取权限
  302. * @return mixed
  303. */
  304. public function getUserPermission() {
  305. return [];
  306. }
  307. /**
  308. * 校验权限
  309. * @param $controller
  310. * @param string $action
  311. * @return bool
  312. */
  313. public function validateUserAction($controller, $action = '') {
  314. $isRecharge = \common\models\User::getEnCodeInfo($this->_userId)['IS_RECHARGE'];
  315. if($controller=='finance' && $action=='recharge' && $isRecharge==0){
  316. return false;
  317. }
  318. return true;
  319. // $userInfo = $this->_userInfo;
  320. // if($userInfo['roleId'] === Yii::$app->params['superAdminRoleId']){
  321. // return true;
  322. // }
  323. // // 查看控制器是否在白名单中,如果在白名单中则直接返回true
  324. // $noCheckActions = Yii::$app->params['noCheckPermissionActions'];
  325. // if(in_array($controller.'/'.$action, $noCheckActions)){
  326. // return true;
  327. // }
  328. // return true;
  329. }
  330. /**
  331. * 查看是否有该控制器的权限
  332. * @param $controller
  333. * @return bool
  334. */
  335. public function validateUserController($controller) {
  336. $isAtlas = \common\models\User::getEnCodeInfo($this->_userId)['IS_ATLAS'];
  337. if($controller=='atlas' && $isAtlas==0){
  338. return false;
  339. }
  340. return true;
  341. // if($userInfo['roleId'] === Yii::$app->params['superAdminRoleId']){
  342. // return true;
  343. // }
  344. // $result = true;
  345. // // 查看控制器是否在白名单中,如果在白名单中则直接返回true
  346. // $noCheckActions = Yii::$app->params['noCheckPermissionActions'];
  347. // foreach($noCheckActions as $action){
  348. // if(preg_match('/^'.$controller.'\//', $action)){
  349. // $result = true;
  350. // break;
  351. // }
  352. // }
  353. //
  354. // return $result;
  355. }
  356. /**
  357. * 校验后台登录前台时所带的参数是否正确
  358. * @return bool
  359. */
  360. public function validateBackendAuth() {
  361. $data = [];
  362. $getData = \Yii::$app->getRequest()->get();
  363. $postData = \Yii::$app->getRequest()->post();
  364. $route = '/' . Yii::$app->controller->module->id . '/' . Yii::$app->controller->id . '/' . Yii::$app->controller->action->id;
  365. if (isset($getData[$route])) unset($getData[$route]);
  366. if (!empty($getData)) $data = array_merge($data, $getData);
  367. if (!empty($postData)) $data = array_merge($data, $postData);
  368. return (isset($data['signature']) && isset($data['timestamp']) && BackendToFrontendApi::checkSignature($data['signature'], $data));
  369. }
  370. }