User.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2016-04-02 10:30
  7. */
  8. namespace common\models;
  9. use Yii;
  10. use Exception;
  11. use common\helpers\Util;
  12. use yii\base\NotSupportedException;
  13. use yii\behaviors\TimestampBehavior;
  14. use yii\web\IdentityInterface;
  15. use yii\web\UploadedFile;
  16. /**
  17. * User model
  18. *
  19. * @property integer $id
  20. * @property string $username
  21. * @property string $password_hash
  22. * @property string $password_reset_token
  23. * @property string $email
  24. * @property string $auth_key
  25. * @property string $avatar
  26. * @property integer $status
  27. * @property integer $created_at
  28. * @property integer $updated_at
  29. * @property string $password write-only password
  30. */
  31. class User extends \yii\db\ActiveRecord implements IdentityInterface
  32. {
  33. const STATUS_DELETED = 0;
  34. const STATUS_ACTIVE = 10;
  35. public $password;
  36. public $repassword;
  37. public function behaviors()
  38. {
  39. return [
  40. TimestampBehavior::className()
  41. ];
  42. }
  43. /**
  44. * @inheritdoc
  45. */
  46. public static function tableName()
  47. {
  48. return '{{%user}}';
  49. }
  50. /**
  51. * @inheritdoc
  52. */
  53. public function rules()
  54. {
  55. return [
  56. [['username', 'password', 'repassword'], 'string'],
  57. [['avatar'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif, webp'],
  58. [['username', 'email'], 'unique'],
  59. ['email', 'email'],
  60. [['repassword'], 'compare', 'compareAttribute' => 'password'],
  61. [['status'], 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
  62. [['username', 'email', 'password', 'repassword'], 'required', 'on' => ['create']],
  63. [['username', 'email'], 'required', 'on' => ['update']],
  64. ];
  65. }
  66. /**
  67. * @inheritdoc
  68. */
  69. public function attributeLabels()
  70. {
  71. return [
  72. 'username' => Yii::t('app', 'Username'),
  73. 'email' => Yii::t('app', 'Email'),
  74. 'old_password' => Yii::t('app', 'Old Password'),
  75. 'password' => Yii::t('app', 'Password'),
  76. 'repassword' => Yii::t('app', 'Repeat Password'),
  77. 'avatar' => Yii::t('app', 'Avatar'),
  78. 'status' => Yii::t('app', 'Status'),
  79. 'created_at' => Yii::t('app', 'Created At'),
  80. 'updated_at' => Yii::t('app', 'Updated At'),
  81. ];
  82. }
  83. public function beforeValidate()
  84. {
  85. if($this->avatar !== "0") {//为0表示需要删除图片,Util::handleModelSingleFileUpload()会有判断删除图片
  86. $this->avatar = UploadedFile::getInstance($this, "avatar");
  87. }
  88. return parent::beforeValidate();
  89. }
  90. /**
  91. * @inheritdoc
  92. */
  93. public function beforeSave($insert)
  94. {
  95. if (!$insert) {
  96. if( !empty($this->password) && empty($this->repassword) ){
  97. $this->addError("repassword", Yii::t('yii', '{attribute} must be equal to "{compareValueOrAttribute}".', [
  98. 'attribute' => yii::t('app', 'Repeat Password'),
  99. 'compareValueOrAttribute' => yii::t('app', 'Password')
  100. ])
  101. );
  102. return false;
  103. }
  104. $this->setPassword( $this->password );
  105. }
  106. Util::handleModelSingleFileUpload($this, 'avatar', $insert, '@frontend/web/uploads/avatar/');
  107. return parent::beforeSave($insert);
  108. }
  109. /**
  110. * @inheritdoc
  111. */
  112. public function beforeDelete()
  113. {
  114. if( empty($this->avatar) ) return true;
  115. try {
  116. Util::deleteThumbnails(Yii::getAlias('@frontend/web') . $this->avatar, [], true);
  117. }catch (Exception $exception){
  118. $this->addError("avatar", $exception->getMessage());
  119. return false;
  120. }
  121. return true;
  122. }
  123. public static function getStatuses()
  124. {
  125. return [
  126. self::STATUS_ACTIVE => Yii::t('app', 'Normal'),
  127. self::STATUS_DELETED => Yii::t('app', 'Disabled'),
  128. ];
  129. }
  130. /**
  131. * @inheritdoc
  132. */
  133. public static function findIdentity($id)
  134. {
  135. return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
  136. }
  137. /**
  138. * @inheritdoc
  139. */
  140. public static function findIdentityByAccessToken($token, $type = null)
  141. {
  142. throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
  143. }
  144. /**
  145. * Finds user by username
  146. *
  147. * @param string $username
  148. * @return static|null
  149. */
  150. public static function findByUsername($username)
  151. {
  152. return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
  153. }
  154. /**
  155. * Finds user by password reset token
  156. *
  157. * @param string $token password reset token
  158. * @return static|null
  159. */
  160. public static function findByPasswordResetToken($token)
  161. {
  162. if (! static::isPasswordResetTokenValid($token)) {
  163. return null;
  164. }
  165. return static::findOne([
  166. 'password_reset_token' => $token,
  167. 'status' => self::STATUS_ACTIVE,
  168. ]);
  169. }
  170. /**
  171. * Finds out if password reset token is valid
  172. *
  173. * @param string $token password reset token
  174. * @return boolean
  175. */
  176. public static function isPasswordResetTokenValid($token)
  177. {
  178. if (empty($token)) {
  179. return false;
  180. }
  181. $timestamp = (int)substr($token, strrpos($token, '_') + 1);
  182. $expire = Yii::$app->params['user.passwordResetTokenExpire'];
  183. return $timestamp + $expire >= time();
  184. }
  185. /**
  186. * Returns an ID that can uniquely identify a user identity.
  187. * @return string|int an ID that uniquely identifies a user identity.
  188. */
  189. public function getId()
  190. {
  191. return $this->id;
  192. }
  193. /**
  194. * Returns a key that can be used to check the validity of a given identity ID.
  195. *
  196. * The key should be unique for each individual user, and should be persistent
  197. * so that it can be used to check the validity of the user identity.
  198. *
  199. * The space of such keys should be big enough to defeat potential identity attacks.
  200. *
  201. * This is required if [[User::enableAutoLogin]] is enabled. The returned key will be stored on the
  202. * client side as a cookie and will be used to authenticate user even if PHP session has been expired.
  203. *
  204. * Make sure to invalidate earlier issued authKeys when you implement force user logout, password change and
  205. * other scenarios, that require forceful access revocation for old sessions.
  206. *
  207. * @return string a key that is used to check the validity of a given identity ID.
  208. * @see validateAuthKey()
  209. */
  210. public function getAuthKey()
  211. {
  212. return $this->auth_key;
  213. }
  214. /**
  215. * Validates the given auth key.
  216. *
  217. * This is required if [[User::enableAutoLogin]] is enabled.
  218. * @param string $authKey the given auth key
  219. * @return bool whether the given auth key is valid.
  220. * @see getAuthKey()
  221. */
  222. public function validateAuthKey($authKey)
  223. {
  224. return $this->getAuthKey() === $authKey;
  225. }
  226. /**
  227. * Validates password
  228. *
  229. * @param string $password password to validate
  230. * @return boolean if password provided is valid for current user
  231. */
  232. public function validatePassword($password)
  233. {
  234. return Yii::$app->security->validatePassword($password, $this->password_hash);
  235. }
  236. /**
  237. * Generates password hash from password and sets it to the model
  238. *
  239. * @param string $password
  240. * @throws \yii\base\Exception
  241. */
  242. public function setPassword($password)
  243. {
  244. $this->password_hash = Yii::$app->security->generatePasswordHash($password);
  245. }
  246. /**
  247. * Generates "remember me" authentication key
  248. */
  249. public function generateAuthKey()
  250. {
  251. $this->auth_key = Yii::$app->security->generateRandomString();
  252. }
  253. /**
  254. * Generates new password reset token
  255. */
  256. public function generatePasswordResetToken()
  257. {
  258. $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
  259. }
  260. /**
  261. * Removes password reset token
  262. */
  263. public function removePasswordResetToken()
  264. {
  265. $this->password_reset_token = null;
  266. }
  267. }