Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace api\models;
- use Yii;
- use common\models\User;
- use common\models\Token;
- use yii\base\Model;
- /**
- * Login form
- */
- class LoginForm extends Model
- {
- public $phone;
- public $password;
- private $_user;
- /**
- * @inheritdoc
- */
- public function rules()
- {
- return[
- [['phone', 'password'], 'required'],
- ['password', 'validatePassword'],
- ];
- }
- public function validatePassword($attribute, $params)
- {
- if (!$this->hasErrors()){
- $user = $this->getUser();
- if (!$user || !$user->validatePassword($this->password)){
- $this->addError($attribute, 'Не верный телефон или пароль');
- }
- }
- }
- /**
- * @return Token|null
- */
- public function auth()
- {
- if ($this->validate()){
- $token = new Token();
- $token->user_id = $this->getUser()->id;
- $token->generateToken(time() + 3600 * 24);
- return $token->save() ? $token : null;
- } else {
- return null;
- }
- }
- /**
- * Finds user by [[phone]]
- *
- * @return User|null
- */
- protected function getUser()
- {
- if ($this->_user === null) {
- $this->_user = User::findByPhone($this->phone);
- }
- return $this->_user;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment