22
33namespace api \modules \v1 \models ;
44
5+ use Yii ;
6+ use yii \base \Model ;
7+ use base \db \ActiveRecord ;
8+ use yii \web \IdentityInterface ;
9+
510/**
611 * Class User
712 * @package api\modules\v1\models
813 *
914 * {@inheritdoc}
1015 */
11- class User extends \ common \ models \User
16+ class User extends ActiveRecord
1217{
18+ public $ username ;
19+ public $ password ;
20+ public $ rememberMe = true ;
21+
22+ private $ _user ;
23+
24+ const STATUS_DELETED = 0 ;
25+ const STATUS_ACTIVE = 10 ;
26+
27+
28+ /**
29+ * {@inheritdoc}
30+ */
31+ public static function tableName ()
32+ {
33+ return '{{%user}} ' ;
34+ }
35+
36+ public function rules ()
37+ {
38+ return [
39+ // username and password are both required
40+ [['username ' , 'password ' ], 'required ' ],
41+ // rememberMe must be a boolean value
42+ ['rememberMe ' , 'boolean ' ],
43+ // password is validated by validatePassword()
44+ ['password ' , 'validatePassword ' ],
45+ ];
46+ }
47+
48+ /**
49+ * {@inheritdoc}
50+ */
51+ public function getId ()
52+ {
53+ return $ this ->getPrimaryKey ();
54+ }
55+
56+ /**
57+ * Validates the password.
58+ * This method serves as the inline validation for password.
59+ *
60+ * @param string $attribute the attribute currently being validated
61+ * @param array $params the additional name-value pairs given in the rule
62+ */
63+ public function validatePassword ($ attribute , $ params )
64+ {
65+ if (!$ this ->hasErrors ()) {
66+ $ user = $ this ->getUser ();
67+ if (!$ user || !$ user ->validatePassword ($ this ->password )) {
68+ $ this ->addError ($ attribute , 'Incorrect username or password. ' );
69+ }
70+ }
71+ }
72+
73+ /**
74+ * Finds user by [[username]]
75+ *
76+ * @return User|null
77+ */
78+ protected function getUser ()
79+ {
80+ if ($ this ->_user === null ) {
81+ $ this ->_user = User::findByUsername ($ this ->username );
82+ }
83+
84+ return $ this ->_user ;
85+ }
86+
87+ /**
88+ * Finds user by username
89+ *
90+ * @param string $username
91+ * @return static|null
92+ */
93+ public static function findByUsername ($ username )
94+ {
95+ return static ::findOne (['username ' => $ username , 'status ' => self ::STATUS_ACTIVE ]);
96+ }
97+
98+ /**
99+ * Logs in a user using the provided username and password.
100+ *
101+ * @return bool whether the user is logged in successfully
102+ */
103+ public function login ()
104+ {
105+ if ($ this ->validate ()) {
106+ return Yii::$ app ->user ->login ($ this ->getUser (), $ this ->rememberMe ? 3600 * 24 * 30 : 0 );
107+ }
13108
109+ return false ;
110+ }
14111}
0 commit comments