UserAuth.php 14 KB

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