<?php
class
LoginForm
extends
CFormModel
{
public
$username
;
public
$password
;
public
$rememberMe
;
public
$verifyCode
;
private
$_identity
;
public
function
rules(){
return
array
(
array
(
'username'
,
'required'
,
'message'
=>
'登录帐号不能为空'
),
array
(
'password'
,
'required'
,
'message'
=>
'密码不能为空'
),
array
(
'verifyCode'
,
'required'
,
'message'
=>
'验证码不能为空'
),
array
(
'verifyCode'
,
'captcha'
,
'on'
=>
'login'
,
'allowEmpty'
=>!Yii::app()->admin->isGuest),
array
(
'rememberMe'
,
'boolean'
),
array
(
'password'
,
'authenticate'
),
);
}
public
function
attributeLabels()
{
return
array
(
'rememberMe'
=>
'下次记住我'
,
'verifyCode'
=>
'验证码'
);
}
public
function
authenticate(
$attribute
,
$params
)
{
if
(!
$this
->hasErrors())
{
$this
->_identity=
new
UserIdentity(
$this
->username,
$this
->password);
if
(!
$this
->_identity->authenticate())
$this
->addError(
'password'
,
'帐号或密码错误.'
);
}
}
public
function
validateVerifyCode(
$verifyCode
){
if
(
strtolower
(
$this
->verifyCode) ===
strtolower
(
$verifyCode
)){
return
true;
}
else
{
$this
->addError(
'verifyCode'
,
'验证码错误.'
);
}
}
public
function
login(){
if
(
$this
->_identity===null){
$this
->_identity=
new
UserIdentity(
$this
->username,
$this
->password);
$this
->_identity->authenticate();
}
if
(
$this
->_identity->errorCode===UserIdentity::ERROR_NONE){
$duration
=
$this
->rememberMe ? 3600*24*30 : 0;
Yii::app()->user->login(
$this
->_identity,
$duration
);
return
true;
}
else
{
return
false;
}
}
}