User.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/2/24
  6. * Time: 下午1:02
  7. */
  8. namespace frontendApi\modules\v1\models;
  9. use common\components\Redis;
  10. use common\helpers\Date;
  11. use common\models\UserToken;
  12. use Yii;
  13. use yii\web\IdentityInterface;
  14. class User extends \common\models\User implements IdentityInterface {
  15. const CACHE_IS_QUICKLY_LOGIN = 'quickly:user:';
  16. /**
  17. * @param mixed $token
  18. * @param null $type
  19. * @return null|IdentityInterface|static
  20. */
  21. public static function findIdentityByAccessToken($token, $type = null) {
  22. // 从redis中把 token 找到,使用Redis::key方法加密
  23. $redisKey = Redis::key($token);
  24. return Yii::$app->tokenRedis->hget($redisKey, 'ID');
  25. // if($userId){
  26. // return static::findOne(['ID' => $userId]);
  27. // }
  28. // return null;
  29. 32| }
  30. public function fields() {
  31. $fields = parent::fields();
  32. // 删除一些包含敏感信息的字段
  33. unset($fields['PASSWORD_HASH'], $fields['PAY_PASSWORD']);
  34. return $fields;
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function behaviors() {
  40. return [
  41. 'yii\behaviors\TimestampBehavior',
  42. ];
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public static function findIdentity($id) {
  48. return static::findOne(['ID' => $id]);
  49. }
  50. /**
  51. * Finds user by username
  52. *
  53. * @param string $username
  54. * @return static|null
  55. */
  56. public static function findByUsername($username) {
  57. return static::findOne(['USER_NAME' => $username]);
  58. }
  59. /**
  60. * 通过用户名获取信息并带着token表内容
  61. * @param $username
  62. * @return array
  63. */
  64. public static function findByUsernameWithToken($username) {
  65. $result = static::find()->select(static::tableName() . '.*,T.ACCESS_TOKEN,T.REFRESH_TOKEN,T.CREATED_AT,T.UPDATED_AT')->join('LEFT JOIN', UserToken::tableName() . ' AS T', static::tableName() . '.ID=T.USER_ID')->where(static::tableName() . '.USER_NAME=:USER_NAME', ['USER_NAME' => $username])->asArray()->one();
  66. return $result;
  67. }
  68. /**
  69. * 静态方法校验两个密码
  70. * @param $password
  71. * @param $validatePassword
  72. * @return bool
  73. */
  74. public static function validatePasswordStatic($password, $validatePassword) {
  75. return Yii::$app->security->validatePassword($password, $validatePassword);
  76. }
  77. /**
  78. * 生成PCAccessToken
  79. * @param $appType (pc|app)
  80. * @return string
  81. * @throws \yii\base\Exception
  82. */
  83. public static function generateAccessToken($appType) {
  84. $appTypeUper = strtoupper($appType);
  85. // 从redis的AccessTokenIncr中自增一个值
  86. $incrValue = Yii::$app->tokenRedis->incr($appTypeUper . 'AccessTokenIncr');
  87. // upa(user_pc_access)
  88. return md5('u' . $appType[0] . 'a_' . Yii::$app->security->generateRandomString(8) . Date::nowTime() . $incrValue);
  89. }
  90. /**
  91. * 生成PCRefreshToken
  92. * @param $appType (pc|app)
  93. * @return string
  94. * @throws \yii\base\Exception
  95. */
  96. public static function generateRefreshToken($appType) {
  97. $appTypeUper = strtoupper($appType);
  98. // 从redis的AccessTokenIncr中自增一个值
  99. $incrValue = Yii::$app->tokenRedis->incr($appTypeUper . 'RefreshTokenIncr');
  100. // upr(user_pc_access)
  101. return md5('u' . $appType[0] . 'r_' . Yii::$app->security->generateRandomString(8) . Date::nowTime() . $incrValue);
  102. }
  103. /**
  104. * 通过重设密码 token 找到用户
  105. * @param $token
  106. * @return null|static
  107. */
  108. public static function findByPasswordResetToken($token) {
  109. if (!static::isPasswordResetTokenValid($token)) {
  110. return null;
  111. }
  112. return static::findOne([
  113. 'PASSWORD_RESET_TOKEN' => $token,
  114. ]);
  115. }
  116. /**
  117. * Finds out if password reset token is valid
  118. *
  119. * @param string $token password reset token
  120. * @return bool
  121. */
  122. public static function isPasswordResetTokenValid($token) {
  123. if (empty($token)) {
  124. return false;
  125. }
  126. $timestamp = (int)substr($token, strrpos($token, '_') + 1);
  127. $expire = Yii::$app->params['user.passwordResetTokenExpire'];
  128. return $timestamp + $expire >= time();
  129. }
  130. /**
  131. * {@inheritdoc}
  132. */
  133. public function getId() {
  134. return $this->getPrimaryKey();
  135. }
  136. /**
  137. * {@inheritdoc}
  138. */
  139. public function getAuthKey() {
  140. return $this->AUTH_KEY;
  141. }
  142. /**
  143. * {@inheritdoc}
  144. */
  145. public function validateAuthKey($authKey) {
  146. return $this->getAuthKey() === $authKey;
  147. }
  148. /**
  149. * Validates password
  150. *
  151. * @param string $password password to validate
  152. * @return bool if password provided is valid for current user
  153. */
  154. public function validatePassword($password) {
  155. //return password_verify($password, $this->PASSWORD_HASH);
  156. return Yii::$app->security->validatePassword($password, $this->PASSWORD_HASH);
  157. }
  158. /**
  159. * Generates password hash from password and sets it to the model
  160. * @param $password
  161. * @throws \yii\base\Exception
  162. */
  163. public function setPassword($password) {
  164. $this->PASSWORD_HASH = Yii::$app->security->generatePasswordHash($password);
  165. }
  166. /**
  167. * Generates "remember me" authentication key
  168. * @throws \yii\base\Exception
  169. */
  170. public function generateAuthKey() {
  171. $this->AUTH_KEY = Yii::$app->security->generateRandomString();
  172. }
  173. /**
  174. * Generates new password reset token
  175. * @throws \yii\base\Exception
  176. */
  177. public function generatePasswordResetToken() {
  178. $this->PASSWORD_RESET_TOKEN = Yii::$app->security->generateRandomString() . '_' . Date::nowTime();
  179. }
  180. /**
  181. * Removes password reset token
  182. */
  183. public function removePasswordResetToken() {
  184. $this->PASSWORD_RESET_TOKEN = null;
  185. }
  186. /**
  187. * 简单的缓存信息,此信息是在登录时缓存的
  188. * @return mixed
  189. */
  190. public static function isQuicklyLogin() {
  191. $authHeader = Yii::$app->request->getHeaders()->get('Authorization');
  192. if ($authHeader !== null && preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
  193. $token = ($matches && isset($matches[1])) ? $matches[1] : null;
  194. if ($token) {
  195. $key = Redis::key(self::CACHE_IS_QUICKLY_LOGIN . $token);
  196. $value = (int)Yii::$app->redis->get($key);
  197. return $value;
  198. }
  199. }
  200. return 0;
  201. }
  202. }