在yii中新增一个用户验证

1.为什么要新增一个用户验证:

    因为我要将网站后台和前台做在同一个yii的应用中.但是前台也包含有会员的管理中心.而这两个用户验证是完全不同的,所以需要两个不同登陆页面,要将用户信息保存在不同的cookie或session中.所以需要在一个应用中增加一个用户验证

 

2.yii的用户验证:

   在自定义用户验证前,我们首先要弄清楚yii的验证和授权方式.

   为了验证一个用户,我们需要定义一个有验证逻辑的验证类.在yii中这个类需要实现IUserIdentity接口,不同的类就可以实现不同的验证方法.网站登陆一般需要验证的就是用户名和密码,yii提供了CUserIdentity类,这个类一般用于验证用户名和密码的类.继承后我们需要重写其中的authenticate()方法来实现我们自己的验证方法.具体代码如下:

class UserIdentity extends CUserIdentity
{
    private $_id;
    public function authenticate()
    {
        $record=User::model()->findByAttributes(array('username'=>$this->username));
        if($record===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if($record->password!==md5($this->password))
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
        {
            $this->_id=$record->id;
            $this->setState('title', $record->title);
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
    }
 
    public function getId()
    {
        return $this->_id;
    }
}

 在用户登陆时则调用如下代码:

// 使用提供的用户名和密码登录用户
$identity=new UserIdentity($username,$password);
if($identity->authenticate())
    Yii::app()->user->login($identity);
else
    echo $identity->errorMessage;

 用户退出时,则调用如下代码:

// 注销当前用户
Yii::app()->user->logout();

 其中的user是yii的一个components.需要在protected/config/main.php中定义

'user'=>array(
	// enable cookie-based authentication
	'allowAutoLogin'=>true,
        'loginUrl' => array('site/login'),
),

 这里我们没有指定user的类名.因为在yii中默认user为CWebUser类的实例.

我们现在已经实现了用户的登陆验证和退出.但是现在无论是否登陆,用户都能访问所有的action,所以下一步我们要对用户访问进行授权.在yii里是通过Access Control Filter即访问控制过滤器来实现用户授权的.我们看一下一个简单的带有访问控制的Controller:

class AdminDefaultController extends CController
{
    
	public function filters()
        {
            return array('accessControl');
        }

        public function accessRules()
        {
            return array(
                array(
                    'allow',
                    'users' => array('@'),
                ),
                array(
                    'deny',
                    'users' => array('*')
                ),
            );
        }
}

 我们在filters方法中设置具体的filter.我们可以看到在filters方法返回的array里有accessControl参数,在CController类中有一个filterAccessControl方法:

public function filterAccessControl($filterChain)
{
	$filter=new CAccessControlFilter;
	$filter->setRules($this->accessRules());
	$filter->filter($filterChain);
}

 在里面新建了一个CAccessControlFilter实例,并且在setRules时传入了accessRules()方法返回的参数.

$filter->filter($filterChain)则是继续调用其它filter.

而所有具体的授权规则则是定义在accessRules中:

public function accessRules()
    {
        return array(
            array('deny',
                'actions'=>array('create', 'edit'),
                'users'=>array('?'),
            ),
            array('allow',
                'actions'=>array('delete'),
                'roles'=>array('admin'),
            ),
            array('deny',
                'actions'=>array('delete'),
                'users'=>array('*'),
            ),
        );
    }

 具体规则参见yii的手册.

 

3.新增一个验证体系:

首先我们从CWebUser继承一个CAdminUser:

class CAdminWebUser extends CWebUser
{
    public $loginUrl = array('admin/admin/login');
}

 我们需要把他放置到components中

如果是全局应用则通过protected/config/main.php的components小节:

'user'=>array(
	// enable cookie-based authentication
        'class' => 'CAdminUser',
	'allowAutoLogin'=>true,
       'loginUrl' => array('site/login'),
),

 如果是在modules中则在模块类的init方法中添加如下代码:

$this->setComponents(array(
       'adminUser' => array(
                'class' => 'CAdminWebUser',
                'allowAutoLogin' => false,
        )
));

 最后调用方式

//全局应用
Yii::app()->getComponent('adminUser');
//在模块中
Yii::app()->controller->module->getComponent('adminUser');

 但仅仅这样还不够,我们还需要修改Controller的filter,我们需要自定义一个filter,来实现另一个用户的验证和授权

第一步自定义一个filter:

class CAdminAccessControlFilter extends CAccessControlFilter
{
    protected function preFilter($filterChain)
    {
        $app=Yii::app();
		$request=$app->getRequest();
		$user = Yii::app()->controller->module->getComponent('adminUser');
		$verb=$request->getRequestType();
		$ip=$request->getUserHostAddress();
	
	    foreach($this->getRules() as $rule)
		{
	        if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed
				break;
	        else if($allow<0) // denied
	        {
				$this->accessDenied($user);
				return false;
	        }
		}

        return true;
    }
}

 再重写CController类的filterAccessController方法

public function filterAccessControl($filterChain)
{
	$filter = new CAdminAccessControlFilter();
	$filter->setRules($this->accessRules());
	$filter->filter($filterChain);
}
//在这里我们使用自定义的filter类替换了原来的filter

 OK,到这里我们就可以在此Controller的accessRules()中指定adminUser的授权了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值