一个类,简易看懂,yii的授权机制。 快速学习yii的登录,验证,权限控制

本文介绍了如何使用Yii框架实现基于角色的权限管理(RBAC),包括创建操作、任务、角色及用户授权流程,并演示了登录及鉴权的具体实现。
<?php

/**
 * SiteController is the default controller to handle user requests.
 */
class Site2Controller extends BaseController
{
    /**
     * Index action is the default action in a controller.
     */
    public function actionIndex()
    {
       // phpinfo();
        echo "<pre/>";
        //新建用户
//        $u=new User();
//        $u->uname='samguest';
//        $u->upassword=md5('cccccc');
//        $u->ucreatetime=time();
//        $u->save();
//        exit;

        //授权
//        $auth=Yii::app()->authManager;
//        $auth->assign('reader','samguest');
//        exit;

        //登录
        $identity=new PerLib_UserIdentity('samguest','cccccc');
        if($identity->authenticate()){//验证用户,注意;PerLib_UserIdentity是继承Yii提供的CUserIdentity 实现的。
            Yii::app()->user->login($identity);
            echo '登录成功!';
        }else{
            echo '登录失败!';
        }

        //鉴权
        if(Yii::app()->user->checkAccess('readPost')){
            echo 'readPost鉴权通过!';
        }else{
            echo 'createPost鉴权失败!';
        }
        if(Yii::app()->user->checkAccess('createPost')){
            echo 'createPost鉴权通过!';
        }else{
            echo 'createPost鉴权失败!';
        }


        exit;

    }

    /**
     * 权限管理
     */
    function AuthInit(){
        $auth=Yii::app()->authManager;
        //创建操作
        $auth->createOperation('createPost','create a post');
        $auth->createOperation('readPost','read a post');
        $auth->createOperation('updatePost','update a post');
        $auth->createOperation('deletePost','delete a post');

        $bizRule='return Yii::app()->user->id==$params["post"]->authID;';
        $task=$auth->createTask('updateOwnPost','update a post by author himself',$bizRule);
        $task->addChild('updatePost');

        //创建角色,并为角色分配操作
        $role=$auth->createRole('reader');
        $role->addChild('readPost');

        $role=$auth->createRole('author');
        $role->addChild('reader');
        $role->addChild('createPost');
        $role->addChild('updateOwnPost');

        $role=$auth->createRole('editor');
        $role->addChild('reader');
        $role->addChild('updatePost');

        $role=$auth->createRole('admin');
        $role->addChild('editor');
        $role->addChild('author');
        $role->addChild('deletePost');

        //给用户分配角色
        $auth->assign('reader','readerA');
        $auth->assign('author','authorB');
        $auth->assign('editor','editorC');
        $auth->assign('admin','adminD');
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值