BrandAuth.php 14 KB

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