/** * LoginForm class. * LoginForm is the data structure for keeping * user login form data. It is used by the 'login' action of 'SiteController'. */ classLoginFormextendsCFormModel { public$username; public$password; public$rememberMe; public$verifyCode; private$_identity;
/** * Declares the validation rules. * The rules state that username and password are required, * and password needs to be authenticated. */ publicfunctionrules() { return [ // username and password are required // array('username, password', 'required'), ['username', 'required', 'message' => '登录帐号不能为空'], ['password', 'required', 'message' => '密码不能为空'], ['verifyCode', 'required', 'message' => '验证码不能为空'], ['verifyCode', 'captcha', 'on' => 'login', 'allowEmpty' => !Yii::app()->admin->isGuest], // rememberMe needs to be a boolean ['rememberMe', 'boolean'], // password needs to be authenticated ['password', 'authenticate'], ]; }
/** * Authenticates the password. * This is the 'authenticate' validator as declared in rules(). */ publicfunctionauthenticate($attribute, $params) { if (!$this->hasErrors()) { $this->_identity = newUserIdentity($this->username, $this->password); if (!$this->_identity->authenticate()) { $this->addError('password', '帐号或密码错误.'); } } }
/** * Logs in the user using the given username and password in the model. * @return boolean whether login is successful */ publicfunctionlogin() { if (null === $this->_identity) { $this->_identity = newUserIdentity($this->username, $this->password); $this->_identity->authenticate(); } if (UserIdentity::ERROR_NONE === $this->_identity->errorCode) { $duration = $this->rememberMe ? 3600 * 24 * 30 : 0; // 30 days Yii::app()->user->login($this->_identity, $duration); returntrue; } else { returnfalse; } } }
if (isset($_POST['LoginForm'])) { $model->attributes = $_POST['LoginForm']; // validate user input and redirect to the previous page if valid if ($model->validate() && $model->validateVerifyCode($this->createAction('captcha')->getVerifyCode()) && $model->login()) { $this->redirect(CController::createUrl('default/index')); } } $this->render('login', ['model' => $model]); }