LoginForm.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * LoginForm class.
  4. * LoginForm is the data structure for keeping
  5. * user login form data. It is used by the 'login' action of 'SiteController'.
  6. */
  7. class LoginForm extends CFormModel
  8. {
  9. public $username;
  10. public $password;
  11. public $rememberMe;
  12. private $_identity;
  13. /**
  14. * Declares the validation rules.
  15. * The rules state that username and password are required,
  16. * and password needs to be authenticated.
  17. */
  18. public function rules()
  19. {
  20. return array(
  21. // username and password are required
  22. array('username, password', 'required'),
  23. // rememberMe needs to be a boolean
  24. array('rememberMe', 'boolean'),
  25. // password needs to be authenticated
  26. array('password', 'authenticate'),
  27. );
  28. }
  29. /**
  30. * Declares attribute labels.
  31. */
  32. public function attributeLabels()
  33. {
  34. return array(
  35. 'rememberMe'=>'Remember me next time',
  36. );
  37. }
  38. /**
  39. * Authenticates the password.
  40. * This is the 'authenticate' validator as declared in rules().
  41. */
  42. public function authenticate($attribute,$params)
  43. {
  44. $this->_identity=new UserIdentity($this->username,$this->password);
  45. if(!$this->_identity->authenticate())
  46. $this->addError('password','Incorrect username or password.');
  47. }
  48. /**
  49. * Logs in the user using the given username and password in the model.
  50. * @return boolean whether login is successful
  51. */
  52. public function login()
  53. {
  54. if($this->_identity===null)
  55. {
  56. $this->_identity=new UserIdentity($this->username,$this->password);
  57. $this->_identity->authenticate();
  58. }
  59. if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
  60. {
  61. $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
  62. Yii::app()->user->login($this->_identity,$duration);
  63. return true;
  64. }
  65. else
  66. return false;
  67. }
  68. }