UserAuth.php 13 KB

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