User.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2017-08-30 19:04
  7. */
  8. namespace api\models;
  9. use Yii;
  10. use yii\web\IdentityInterface;
  11. use yii\web\UnauthorizedHttpException;
  12. class User extends \common\models\User implements IdentityInterface
  13. {
  14. public function fields()
  15. {
  16. $fields = parent::fields();
  17. unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token'], $fields['access_token']);
  18. return $fields;
  19. }
  20. public static function findIdentityByAccessToken($token, $type = null)
  21. {
  22. if( !self::accessTokenIsValid($token) ){
  23. throw new UnauthorizedHttpException("token格式错误或已过期");
  24. }
  25. return static::findOne(['access_token' => $token]);
  26. }
  27. public function generateAccessToken()
  28. {
  29. $this->access_token = Yii::$app->security->generateRandomString(32) . time();
  30. }
  31. public static function accessTokenIsValid($token)
  32. {
  33. if (empty($token)) {
  34. return false;
  35. }
  36. $timestamp = (int) substr($token, -10);
  37. $expire = Yii::$app->params['user.apiTokenExpire'];
  38. return $timestamp + $expire >= time();
  39. }
  40. }