FrontEndTokenFilter.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace app\common\filters;
  3. use app\common\helpers\Identify;
  4. use Yii;
  5. use yii\base\ActionFilter;
  6. //刷新token
  7. class FrontEndTokenFilter extends ActionFilter
  8. {
  9. public function beforeAction($action)
  10. {
  11. if(!Identify::hasLogined())return true;
  12. $token = \app\common\helpers\Cookie::getCookie(Yii::$app->params['access_token_name']);
  13. if(!empty($token))
  14. {
  15. $tokenModel = \app\modules\ucenter\models\UserToken::find()->where('token = :token and request_from=:request_from', [':token' => $token,':request_from' => REQUEST_FROM])->orderBy(['create_time'=>SORT_DESC])->one();
  16. if($tokenModel)
  17. {
  18. $user = \app\modules\ucenter\models\User::find()->where("user_id=".$tokenModel->user_id)->one();
  19. }
  20. }
  21. else
  22. {
  23. $user = \app\modules\ucenter\models\User::find()->where("user_id=".Identify::getUserInfo(null,'user_id'))->one();
  24. }
  25. if($user&&$user->refreshAccessToken($user,REQUEST_FROM))
  26. {
  27. $newTokenModel = \app\modules\ucenter\models\User::getToken($user->user_id,REQUEST_FROM);
  28. if($newTokenModel->token!=$token)
  29. {
  30. \app\common\helpers\Cookie::setCookie(Yii::$app->params['access_token_name'],$newTokenModel->token);
  31. }
  32. return true;
  33. }
  34. else
  35. {
  36. //如果刷新失败,说明是多端登录,清除COOKIE
  37. Identify::logout();
  38. \app\common\helpers\Cookie::deleteCookie(Yii::$app->params['access_token_name']);
  39. header("Location:".get_url());
  40. return false;
  41. }
  42. }
  43. }