Login.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace app\models;
  3. use Yii;
  4. use yii\base\Model;
  5. class Login extends Model {
  6. public $usuario;
  7. public $clave;
  8. private $_user = false;
  9. /**
  10. * @return array the validation rules.
  11. */
  12. public function rules() {
  13. return [
  14. [['usuario', 'clave'], 'required'],
  15. ['clave', 'validatePassword'],
  16. ];
  17. }
  18. /**
  19. * Validates the password.
  20. * This method serves as the inline validation for password.
  21. *
  22. * @param string $attribute the attribute currently being validated
  23. * @param array $params the additional name-value pairs given in the rule
  24. */
  25. public function validatePassword($attribute, $params) {
  26. if (!$this->hasErrors()) {
  27. $user = $this->getUser();
  28. if (!$user || !$user->validatePassword($this->clave)) {
  29. $this->addError($attribute, 'Incorrect username or password.');
  30. }
  31. }
  32. }
  33. /**
  34. * Logs in a user using the provided username and password.
  35. * @return bool whether the user is logged in successfully
  36. */
  37. public function login() {
  38. if ($this->validate()) {
  39. return Yii::$app->user->login($this->getUser(), 3600 * 24 * 30);
  40. }
  41. return false;
  42. }
  43. /**
  44. * Finds user by [[username]]
  45. *
  46. * @return Usuario|null
  47. */
  48. public function getUser() {
  49. if ($this->_user === false) {
  50. $this->_user = Usuario::findByUsername($this->usuario);
  51. }
  52. return $this->_user;
  53. }
  54. }