pmtpenza

Untitled

Sep 3rd, 2019
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. <?php
  2. namespace api\models;
  3. use Yii;
  4. use common\models\User;
  5. use common\models\Token;
  6. use yii\base\Model;
  7. /**
  8. * Login form
  9. */
  10. class LoginForm extends Model
  11. {
  12. public $phone;
  13. public $password;
  14.  
  15. private $_user;
  16.  
  17. /**
  18. * @inheritdoc
  19. */
  20.  
  21. public function rules()
  22. {
  23. return[
  24. [['phone', 'password'], 'required'],
  25. ['password', 'validatePassword'],
  26. ];
  27. }
  28.  
  29. public function validatePassword($attribute, $params)
  30. {
  31. if (!$this->hasErrors()){
  32. $user = $this->getUser();
  33. if (!$user || !$user->validatePassword($this->password)){
  34. $this->addError($attribute, 'Не верный телефон или пароль');
  35. }
  36. }
  37. }
  38. /**
  39. * @return Token|null
  40. */
  41. public function auth()
  42. {
  43. if ($this->validate()){
  44. $token = new Token();
  45. $token->user_id = $this->getUser()->id;
  46. $token->generateToken(time() + 3600 * 24);
  47. return $token->save() ? $token : null;
  48. } else {
  49. return null;
  50. }
  51. }
  52.  
  53. /**
  54. * Finds user by [[phone]]
  55. *
  56. * @return User|null
  57. */
  58. protected function getUser()
  59. {
  60. if ($this->_user === null) {
  61. $this->_user = User::findByPhone($this->phone);
  62. }
  63. return $this->_user;
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment