RefreshForm.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace api\modules\v1\forms;
  3. use Yii;
  4. use yii\base\Model;
  5. use yii\web\UnauthorizedHttpException;
  6. use common\models\api\AccessToken;
  7. use common\models\member\Member;
  8. use common\enums\AccessTokenGroupEnum;
  9. /**
  10. * Class RefreshForm
  11. * @package api\modules\v1\models
  12. */
  13. class RefreshForm extends Model
  14. {
  15. public $group;
  16. public $refresh_token;
  17. protected $_user;
  18. /**
  19. * @inheritdoc
  20. */
  21. public function rules()
  22. {
  23. return [
  24. [['refresh_token', 'group'], 'required'],
  25. ['refresh_token', 'validateTime'],
  26. ['group', 'in', 'range' => AccessTokenGroupEnum::getKeys()]
  27. ];
  28. }
  29. public function attributeLabels()
  30. {
  31. return [
  32. 'refresh_token' => '重置令牌',
  33. 'group' => '组别',
  34. ];
  35. }
  36. /**
  37. * 验证过期时间
  38. *
  39. * @param $attribute
  40. * @throws UnauthorizedHttpException
  41. */
  42. public function validateTime($attribute)
  43. {
  44. if (!$this->hasErrors() && Yii::$app->params['user.refreshTokenValidity'] == true) {
  45. $token = $this->refresh_token;
  46. $timestamp = (int)substr($token, strrpos($token, '_') + 1);
  47. $expire = Yii::$app->params['user.refreshTokenExpire'];
  48. // 验证有效期
  49. if ($timestamp + $expire <= time()) {
  50. throw new UnauthorizedHttpException('您的重置令牌已经过期,请重新登录');
  51. }
  52. }
  53. if (!$this->getUser()) {
  54. throw new UnauthorizedHttpException('找不到用户');
  55. }
  56. }
  57. /**
  58. * @return bool|Member|null|\yii\web\IdentityInterface
  59. */
  60. public function getUser()
  61. {
  62. if ($this->_user == false) {
  63. if (!($apiAccount = AccessToken::findIdentityByRefreshToken($this->refresh_token, $this->group))) {
  64. return false;
  65. }
  66. $this->_user = Member::findIdentity($apiAccount->member_id);
  67. }
  68. return $this->_user;
  69. }
  70. }
粤ICP备19079148号