Zend framework 之zend_acl,zend_auth实现用户权限控制

我的controller文件夹里包含index和login两个controller文件从login文件说起,它有三个Action一个是loginAction,一个是showAction,一个是indexAction。indexAction用于将登录表单提交上来的数据进行验证,loginAction用与解析登录表单,showAction用于显示一个主表单。这个表单中有三个提交按钮设为add,hello,delete,代码如下:LoginController.php

class LoginController extends Zend_Controller_Action {
    public function init()
    {  
        header('Content-Type: text/html; charset=utf-8');
        $config=new Zend_Config_Ini('d:/webroot/aaa/application/configs/application.ini', "staging");
        Zend_Registry::set('config',$config);     
        $db=Zend_Db::factory($config->resources->db->adapter,$config->resources->db->params->toArray());
        Zend_Registry::set('db',$db);
    }
    public function indexAction()
    {
        $db=Zend_Registry::get('db');
        $username=$this->_request->getPost('username');
        $password=$this->_request->getPost('password');
        $authAdapter=new Zend_Auth_Adapter_DbTable($db);
        $authAdapter->setTableName('user')
                    ->setIdentityColumn('username')
                    ->setCredentialColumn('password')
                    ->setIdentity($username)
                    ->setCredential($password);
        $auth=Zend_Auth::getInstance();
        if($auth->hasIdentity()){
        $this->_forward('show', 'login');
        }else{
         $result=$auth->authenticate($authAdapter);
         if($result->isValid()){
                require_once 'Zend/Session/Namespace.php';
                $authNamespace=new Zend_Session_Namespace('Zend_Auth');
                $authNamespace->username=$username;        

                $this->_forward('show', 'login');
         }else{
                echo '认证失败,用户名密码错误!';
         }
        }
    }
    public function loginAction(){
    $this->render();
    }
    public function showAction(){
        $this->render();  
    }
}

login.phtml






login





用户名:


密码:






show.phtml




员工


主页

















indexcontroller中

class IndexController extends Zend_Controller_Action
{
    public function init()
    {
    $today=date('Y-m-d');
    $stream = fopen('d:/webroot/aaa/application/views/logs/'.$today.".txt", 'a',false);
        if (! $stream) {
        throw new Exception('Failed to open stream');
   }
    $log=new Zend_Log();
    $logger=new Default_Model_Ip();
    $log->setEventItem('pid',getmypid());  
   $log->setEventItem('ip',$logger->getIP());     
   $writer = new Zend_Log_Writer_Stream($stream);  
   $format = '[%timestamp%][%priorityName%-%priority%]-[PID:%pid%][ip:%ip%]' . PHP_EOL  
            . '%message%' . PHP_EOL;  
   $formatter = new Zend_Log_Formatter_Simple($format);  
   $writer->setFormatter($formatter);    
   $log->addWriter($writer);  
   Zend_Registry::set('log',$log);  

    header('Content-Type: text/html; charset=utf-8');
        $config=new Zend_Config_Ini('d:/webroot/aaa/application/configs/application.ini', "staging");
        Zend_Registry::set('config',$config);     
        $db=Zend_Db::factory($config->resources->db->adapter,$config->resources->db->params->toArray());
        $db->query("SET NAMES GBK");
        Zend_Registry::set('db',$db);
    }
    public function helloAction(){
       
    $log=Zend_Registry::get('log');
    $log->log('hello,ni hao',3);
    $this->render();
    }
    public function addAction(){
       
    $log=Zend_Registry::get('log');
    $log->log('add,it/' add a data.',3);
    $this->render();
    }
    public function deleteAction(){
      
    $log=Zend_Registry::get('log');
    $log->log('delete,it/' delete a data and can not go back.',3);
    $this->render();
    }
    public function preDispatch(){

    $db=Zend_Registry::get('db');
        $select1=$db->select()
                ->from('role','*');
              
        $roles=$db->fetchAll($select1);
        $acl=new Zend_Acl();
        foreach($roles as $role){
        $acl->addRole(new Zend_Acl_Role($role['rolename']));
        }
        $select2=$db->select()->from('resource','*');
        $resources=$db->fetchAll($select2);
        foreach($resources as $resource){
        $acl->add(new Zend_Acl_Resource($resource['controller'].':'.$resource['action']));
        }
        $sql="select resource.controller,resource.action,role.rolename from resource,role,relation where
        relation.mid=resource.resid and relation.rid=role.rid";
        $re_result=$db->query($sql);
        $rela_result=$re_result->fetchAll();
        foreach ($rela_result as $info){
        $acl->allow($info['rolename'],$info['controller'].':'.$info['action'],$info['action']);
        }
        $action=$this->getRequest()->getActionName();//获取当前控制器和action名称来判断资源能否被角色访问
        $controller=$this->getRequest()->getControllerName();
        require_once 'Zend/Session/Namespace.php';
        $authNamespace=new Zend_Session_Namespace("Zend_Auth");
        $username=$authNamespace->username;
        $sql1='select role.rolename from role,user where role.rid=user.rid and user.username="'.$username.'"';
        $db=Zend_Registry::get('db');
        $cc=$db->query($sql1);
        $dd=$cc->fetchAll();
        if($acl->has($controller.':'.$action))
        {
    $flag=$acl->isAllowed($dd[0]['rolename'],$controller.':'.$action,$action);
            if($flag){ echo'good';
            }else{
                die("您无权做此操作,请与管理员联系!");
            }
        }
}
}

add.phtml ,delete.phtml,hello.phtml中随便写入点东西就行比如heolldas,随便,这个程序主要容来验证zend_acl和zend_auth对用户的权限控制

你可能感兴趣的:(Zend,Framework)