UserAuth.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. // 使用Redis::key方法加密token
  97. $redisKey = Redis::key($token);
  98. $this->_userInfo = [
  99. 'id' => $userId,
  100. 'userName' => Yii::$app->tokenRedis->hget($redisKey, 'USER_NAME'),
  101. 'accessTokenUpdatedAt' => Yii::$app->tokenRedis->hget($redisKey, 'TOKEN_UPDATED_AT'),
  102. 'ip' => Yii::$app->getRequest()->getUserIP(),
  103. ];
  104. return $userId;
  105. } else {
  106. return null;
  107. }
  108. }
  109. /**
  110. * 从后台登录前台
  111. * @param $userId
  112. * @return null
  113. * @throws HttpException
  114. */
  115. public function loginByBackend($userId) {
  116. if (UserInfo::find()->where(['USER_ID' => $userId])->exists()) {
  117. $userToken = UserToken::findOne(['USER_ID' => $userId]);
  118. if (!$userToken) {
  119. $userToken = new UserToken();
  120. $userToken->USER_ID = $userId;
  121. $userToken->CREATED_AT = Date::nowTime();
  122. if (!$userToken->save()) {
  123. return null;
  124. }
  125. }
  126. self::$_isQuicklyLogin = true;
  127. $accessTokenResult = $this->updateToken($userToken, $appType = 'pc', $typeToken = 'access', $userId);
  128. $refreshTokenResult = $this->updateToken($userToken, $appType = 'pc', $typeToken = 'refresh', $userId);
  129. if ($accessTokenResult && $refreshTokenResult) {
  130. return $this->getToken();
  131. } else {
  132. return null;
  133. }
  134. } else {
  135. return null;
  136. }
  137. }
  138. /**
  139. * 用refreshToken生成新的accessToken和refreshToken
  140. * @param $refreshToken
  141. * @return bool
  142. * @throws HttpException
  143. */
  144. public function refreshToken($refreshToken) {
  145. if (!$refreshToken) {
  146. return false;
  147. }
  148. // 使用Redis::key方法加密token
  149. $redisKey = Redis::key($refreshToken);
  150. $userId = Yii::$app->tokenRedis->hget($redisKey, 'ID');
  151. if (!$userId) {
  152. return false;
  153. }
  154. $userToken = UserToken::findOne(['USER_ID' => $userId]);
  155. $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'access', $userId);
  156. $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'refresh', $userId);
  157. return true;
  158. }
  159. /**
  160. * 用refreshToken生成新的accessToken
  161. * @param $refreshToken
  162. * @return bool
  163. * @throws HttpException
  164. */
  165. public function refreshAccessToken($refreshToken) {
  166. if (!$refreshToken) {
  167. return false;
  168. }
  169. // 使用Redis::key方法加密token
  170. $redisKey = Redis::key($refreshToken);
  171. $userId = Yii::$app->tokenRedis->hget($redisKey, 'ID');
  172. if (!$userId) {
  173. return false;
  174. }
  175. $userToken = UserToken::findOne(['USER_ID' => $userId]);
  176. return $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'access', $userId);
  177. }
  178. /**
  179. * 用refreshToken生成新的refreshToken
  180. * @param $refreshToken
  181. * @return bool
  182. * @throws HttpException
  183. */
  184. public function refreshRefreshToken($refreshToken) {
  185. if (!$refreshToken) {
  186. return false;
  187. }
  188. // 使用Redis::key方法加密token
  189. $redisKey = Redis::key($refreshToken);
  190. $userId = Yii::$app->tokenRedis->hget($redisKey, 'ID');
  191. if (!$userId) {
  192. return false;
  193. }
  194. $userToken = UserToken::findOne(['USER_ID' => $userId]);
  195. return $this->updateToken($userToken, $appType = $this->_device, $typeToken = 'refresh', $userId);
  196. }
  197. /**
  198. * 更新token 的具体方法
  199. * @param ActiveRecordInterface $userTokenModel
  200. * @param string $appType (pc|app)
  201. * @param string $typeToken
  202. * @param $userId
  203. * @return bool
  204. * @throws HttpException
  205. */
  206. public function updateToken(ActiveRecordInterface $userTokenModel, $appType = Request::DEVICE_PC, $typeToken = 'access', $userId = 0) {
  207. $tokenField = strtoupper($appType . '_' . $typeToken . '_TOKEN');
  208. $updateField = '';
  209. $expiresIn = 0;
  210. if ($appType === Request::DEVICE_PC) {
  211. if ($typeToken === 'access') {
  212. $updateField = 'PAT_UPDATED_AT';
  213. $expiresIn = Yii::$app->params['frontAccessTokenExpiresIn'];
  214. } elseif ($typeToken === 'refresh') {
  215. $updateField = 'PRT_UPDATED_AT';
  216. $expiresIn = Yii::$app->params['frontRefreshTokenExpiresIn'];
  217. } else {
  218. throw new HttpException(500, 'token字段错误', 500);
  219. }
  220. } elseif ($appType === Request::DEVICE_APP) {
  221. if ($typeToken === 'access') {
  222. $updateField = 'AAT_UPDATED_AT';
  223. $expiresIn = Yii::$app->params['frontAccessTokenExpiresIn'];
  224. } elseif ($typeToken === 'refresh') {
  225. $updateField = 'ART_UPDATED_AT';
  226. $expiresIn = Yii::$app->params['frontRefreshTokenExpiresIn'];
  227. } else {
  228. throw new HttpException(500, 'token字段错误', 500);
  229. }
  230. }
  231. // 老token
  232. $oldToken = $userTokenModel->$tokenField;
  233. // 生成 access_token
  234. /* @var $identityClass IdentityInterface */
  235. $identityClass = $this->identityClass;
  236. $generateTokenMethodName = 'generate' . ucfirst($typeToken) . 'Token';
  237. //$token = $identityClass::generateAccessToken();
  238. $token = call_user_func([$identityClass, $generateTokenMethodName], $appType);
  239. $userTokenModel->$tokenField = $token;
  240. $userTokenModel->$updateField = Date::nowTime();
  241. if (!$userTokenModel->save()) {
  242. throw new HttpException(500, 'token更新失败', 500);
  243. }
  244. // 查找TOKEN中是否有同一用户产生的垃圾token,有的话就清除
  245. if ($oldToken) {
  246. Yii::$app->tokenRedis->del(Redis::key($oldToken));
  247. }
  248. $identity = $this->_apiIdentity;
  249. if (!$this->_apiIdentity) {
  250. if (!$userId) {
  251. throw new HttpException(500, 'userId不能为空', 500);
  252. }
  253. $identity = $identityClass::findIdentity($userId);
  254. }
  255. // 把 accessToken 当做key存入redis中内容为会员的ID和用户名,使用Redis::key方法加密
  256. $redisKey = Redis::key($token);
  257. Yii::$app->tokenRedis->hset($redisKey, 'ID', $identity['ID']);
  258. Yii::$app->tokenRedis->hset($redisKey, 'USER_NAME', $identity['USER_NAME']);
  259. Yii::$app->tokenRedis->hset($redisKey, 'TOKEN_UPDATED_AT', $userTokenModel->$updateField);
  260. Yii::$app->tokenRedis->expire($redisKey, $expiresIn);
  261. // 标记为快速登录的会员
  262. if (self::$_isQuicklyLogin) {
  263. Yii::$app->redis->setex(Redis::key(\frontendApi\modules\v1\models\User::CACHE_IS_QUICKLY_LOGIN . $token), Yii::$app->params['frontAccessTokenExpiresIn'], 1);
  264. }
  265. $this->_token = array_merge($this->_token ? $this->_token : [], [
  266. $typeToken . 'Token' => $token,
  267. $typeToken . 'TokenExpiresIn' => $expiresIn,
  268. $typeToken . 'TokenUpdateAt' => $userTokenModel->$updateField,
  269. ]);
  270. return true;
  271. }
  272. /**
  273. * 获取管理员ID
  274. * @return int|null|string
  275. */
  276. public function getId() {
  277. return $this->_userId;
  278. }
  279. /**
  280. * 获取token
  281. * @return null
  282. */
  283. public function getToken() {
  284. return $this->_token;
  285. }
  286. /**
  287. * 获取管理员信息
  288. * @return null
  289. */
  290. public function getUserInfo() {
  291. return $this->_userInfo;
  292. }
  293. /**
  294. * 获取身份信息
  295. * @param bool $autoRenew
  296. * @return null|IdentityInterface
  297. */
  298. public function getIdentity($autoRenew = true) {
  299. if ($this->_apiIdentity) {
  300. return $this->_apiIdentity;
  301. } else {
  302. if ($this->_userId) {
  303. /* @var $class IdentityInterface */
  304. $class = $this->identityClass;
  305. return $class::findOne(['ID' => $this->_userId]);
  306. } else {
  307. return null;
  308. }
  309. }
  310. }
  311. /**
  312. * 获取权限
  313. * @return mixed
  314. */
  315. public function getUserPermission() {
  316. return [];
  317. }
  318. /**
  319. * 校验权限
  320. * @param $controller
  321. * @param string $action
  322. * @return bool
  323. */
  324. public function validateUserAction($controller, $action = '') {
  325. $isRecharge = \common\models\User::getEnCodeInfo($this->_userId)['IS_RECHARGE'];
  326. if($controller=='finance' && $action=='recharge' && $isRecharge==0){
  327. return false;
  328. }
  329. return true;
  330. // $userInfo = $this->_userInfo;
  331. // if($userInfo['roleId'] === Yii::$app->params['superAdminRoleId']){
  332. // return true;
  333. // }
  334. // // 查看控制器是否在白名单中,如果在白名单中则直接返回true
  335. // $noCheckActions = Yii::$app->params['noCheckPermissionActions'];
  336. // if(in_array($controller.'/'.$action, $noCheckActions)){
  337. // return true;
  338. // }
  339. // return true;
  340. }
  341. /**
  342. * 查看是否有该控制器的权限
  343. * @param $controller
  344. * @return bool
  345. */
  346. public function validateUserController($controller) {
  347. $isAtlas = \common\models\User::getEnCodeInfo($this->_userId)['IS_ATLAS'];
  348. if($controller=='atlas' && $isAtlas==0){
  349. return false;
  350. }
  351. return true;
  352. // if($userInfo['roleId'] === Yii::$app->params['superAdminRoleId']){
  353. // return true;
  354. // }
  355. // $result = true;
  356. // // 查看控制器是否在白名单中,如果在白名单中则直接返回true
  357. // $noCheckActions = Yii::$app->params['noCheckPermissionActions'];
  358. // foreach($noCheckActions as $action){
  359. // if(preg_match('/^'.$controller.'\//', $action)){
  360. // $result = true;
  361. // break;
  362. // }
  363. // }
  364. //
  365. // return $result;
  366. }
  367. /**
  368. * 校验后台登录前台时所带的参数是否正确
  369. * @return bool
  370. */
  371. public function validateBackendAuth() {
  372. $data = [];
  373. $getData = \Yii::$app->getRequest()->get();
  374. $postData = \Yii::$app->getRequest()->post();
  375. $route = '/' . Yii::$app->controller->module->id . '/' . Yii::$app->controller->id . '/' . Yii::$app->controller->action->id;
  376. if (isset($getData[$route])) unset($getData[$route]);
  377. if (!empty($getData)) $data = array_merge($data, $getData);
  378. if (!empty($postData)) $data = array_merge($data, $postData);
  379. return (isset($data['signature']) && isset($data['timestamp']) && BackendToFrontendApi::checkSignature($data['signature'], $data));
  380. }
  381. }