LoginForm.php 2.2 KB

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