User.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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\brand;
  9. use common\components\Redis;
  10. use common\helpers\Date;
  11. use common\models\BaUser;
  12. use common\models\UserToken;
  13. use Yii;
  14. use yii\web\IdentityInterface;
  15. class User extends BaUser implements IdentityInterface {
  16. const CACHE_IS_QUICKLY_LOGIN = 'quickly:user:';
  17. /**
  18. * @param mixed $token
  19. * @param null $type
  20. * @return null|IdentityInterface|static
  21. */
  22. public static function findIdentityByAccessToken($token, $type = null) {
  23. // 从redis中把 token 找到
  24. return Yii::$app->tokenRedis->hget($token, 'ID');
  25. // if($userId){
  26. // return static::findOne(['ID' => $userId]);
  27. // }
  28. // return null;
  29. }
  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. return 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. }
  67. /**
  68. * 静态方法校验两个密码
  69. * @param $password
  70. * @param $validatePassword
  71. * @return bool
  72. */
  73. public static function validatePasswordStatic($password, $validatePassword) {
  74. return Yii::$app->security->validatePassword($password, $validatePassword);
  75. }
  76. /**
  77. * 生成PCAccessToken
  78. * @param $appType (pc|app)
  79. * @return string
  80. * @throws \yii\base\Exception
  81. */
  82. public static function generateAccessToken($appType) {
  83. $appTypeUper = strtoupper($appType);
  84. // 从redis的AccessTokenIncr中自增一个值
  85. $incrValue = Yii::$app->tokenRedis->incr($appTypeUper . 'AccessTokenIncr');
  86. // upa(user_pc_access)
  87. return md5('u' . $appType[0] . 'a_' . Yii::$app->security->generateRandomString(8) . Date::nowTime() . $incrValue);
  88. }
  89. /**
  90. * 生成PCRefreshToken
  91. * @param $appType (pc|app)
  92. * @return string
  93. * @throws \yii\base\Exception
  94. */
  95. public static function generateRefreshToken($appType) {
  96. $appTypeUper = strtoupper($appType);
  97. // 从redis的AccessTokenIncr中自增一个值
  98. $incrValue = Yii::$app->tokenRedis->incr($appTypeUper . 'RefreshTokenIncr');
  99. // upr(user_pc_access)
  100. return md5('u' . $appType[0] . 'r_' . Yii::$app->security->generateRandomString(8) . Date::nowTime() . $incrValue);
  101. }
  102. /**
  103. * 通过重设密码 token 找到用户
  104. * @param $token
  105. * @return null|static
  106. */
  107. public static function findByPasswordResetToken($token) {
  108. if (!static::isPasswordResetTokenValid($token)) {
  109. return null;
  110. }
  111. return static::findOne([
  112. 'PASSWORD_RESET_TOKEN' => $token,
  113. ]);
  114. }
  115. /**
  116. * Finds out if password reset token is valid
  117. *
  118. * @param string $token password reset token
  119. * @return bool
  120. */
  121. public static function isPasswordResetTokenValid($token) {
  122. if (empty($token)) {
  123. return false;
  124. }
  125. $timestamp = (int)substr($token, strrpos($token, '_') + 1);
  126. $expire = Yii::$app->params['user.passwordResetTokenExpire'];
  127. return $timestamp + $expire >= time();
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. public function getId() {
  133. return $this->getPrimaryKey();
  134. }
  135. /**
  136. * {@inheritdoc}
  137. */
  138. public function getAuthKey() {
  139. return $this->AUTH_KEY;
  140. }
  141. /**
  142. * {@inheritdoc}
  143. */
  144. public function validateAuthKey($authKey) {
  145. return $this->getAuthKey() === $authKey;
  146. }
  147. /**
  148. * Validates password
  149. *
  150. * @param string $password password to validate
  151. * @return bool if password provided is valid for current user
  152. */
  153. public function validatePassword($password) {
  154. //return password_verify($password, $this->PASSWORD_HASH);
  155. return Yii::$app->security->validatePassword($password, $this->PASSWORD_HASH);
  156. }
  157. /**
  158. * Generates password hash from password and sets it to the model
  159. * @param $password
  160. * @throws \yii\base\Exception
  161. */
  162. public function setPassword($password) {
  163. $this->PASSWORD_HASH = Yii::$app->security->generatePasswordHash($password);
  164. }
  165. /**
  166. * Generates "remember me" authentication key
  167. * @throws \yii\base\Exception
  168. */
  169. public function generateAuthKey() {
  170. $this->AUTH_KEY = Yii::$app->security->generateRandomString();
  171. }
  172. /**
  173. * Generates new password reset token
  174. * @throws \yii\base\Exception
  175. */
  176. public function generatePasswordResetToken() {
  177. $this->PASSWORD_RESET_TOKEN = Yii::$app->security->generateRandomString() . '_' . Date::nowTime();
  178. }
  179. /**
  180. * Removes password reset token
  181. */
  182. public function removePasswordResetToken() {
  183. $this->PASSWORD_RESET_TOKEN = null;
  184. }
  185. /**
  186. * 简单的缓存信息,此信息是在登录时缓存的
  187. * @return mixed
  188. */
  189. public static function isQuicklyLogin() {
  190. $authHeader = Yii::$app->request->getHeaders()->get('Authorization');
  191. if ($authHeader !== null && preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
  192. $token = ($matches && isset($matches[1])) ? $matches[1] : null;
  193. if ($token) {
  194. $key = Redis::key(self::CACHE_IS_QUICKLY_LOGIN . $token);
  195. $value = (int)Yii::$app->redis->get($key);
  196. return $value;
  197. }
  198. }
  199. return 0;
  200. }
  201. }