Home php教程 php手册 实现简单的ACL

实现简单的ACL

Jun 13, 2016 am 10:43 AM
access acl php code Function definition accomplish control Permissions of Simple surface resource

 

Php代码 

/**

 * 简单的ACL 权限控制功能

 * 

 * 表定义

 * 

 * 1. 资源定义    (rsid,access,desc)

 * 2. 角色定义    (id,rolename,desc)

 * 3. 资源-角色关联(rsid,role_id)

 * 4. 用户-角色关联(user_id,role_id)

 * 

 * 依赖db.php sqlobject.php

 * 

 * @author vb2005xu.iteye.com 

 */ 

class AclBase { 

 

    /**

     * 不允许任何人访问

     */ 

    const NOBODY = 0; 

     

    /**

     * 允许任何人访问

     */ 

    const EVERYONE = 1; 

     

    /**

     * 允许 拥有角色的用户访问

     */ 

    const HAS_ROLE = 2; 

     

    /**

     * 允许 不带有角色的用户访问

     */ 

    const NO_ROLE = 3; 

 

    /**

     * 在 资源-角色关联 定义的 角色才能访问

     */ 

    const ALLOCATE_ROLES = 4; 

     

    // 定义相关的 表名 

    public $tbResources = 'aclresources'; 

    public $tbRoles = 'aclroles'; 

    public $tbRefResourcesRoles = 'aclresources_aclroles'; 

    public $tbRefUsersRoles = 'users_aclroles'; 

     

    /**

     * 格式化 资源的访问权限并返回

     * 

     * @return int

     */ 

    static function formatAccessValue($access){ 

        static $arr = array(self::NOBODY,self::EVERYONE,self::HAS_ROLE,self::NO_ROLE,self::ALLOCATE_ROLES); 

        return in_array($access,$arr) ? $access : self::NOBODY; 

    } 

     

    /**

     * 创建资源,返回资源记录主键

     * 

     * @param string $rsid

     * @param int $access

     * @param string $desc

     * 

     * @return int

     */ 

    function createResource($rsid,$access,$desc){ 

        if (emptyempty($rsid)) return false; 

         

        $resource = array( 

            'rsid' => $rsid, 

            'access' => self::formatAccessValue($access), 

            'desc' => $desc, 

            'created_at' => CURRENT_TIMESTAMP 

        ); 

         

        return SingleTableCRUD::insert($this->tbResources,$resource); 

    } 

     

    /**

     * 修改资源,返回成功状态

     * 

     * @param array $resource

     * @return int

     */ 

    function updateResource(array $resource){        

        if (!isset($resource['rsid'])) return false; 

         

        $resource['updated_at'] = CURRENT_TIMESTAMP; 

         

        return SingleTableCRUD::update($this->tbResources,$resource,'rsid'); 

    } 

     

    /**

     * 删除资源

     * 

     * @param string $rsid

     * @return int

     */ 

    function deleteResource($rsid){ 

        if (emptyempty($rsid)) return false; 

        return SingleTableCRUD::delete($this->tbResources,array('rsid'=>$rsid)); 

    } 

     

    /**

     * 创建角色,返回角色记录主键

     * 

     * @param string $rolename

     * @param string $desc

     * 

     * @return int

     */ 

    function createRole($rolename,$desc){ 

        if (emptyempty($rolename)) return false; 

         

        $role = array( 

            'rolename' => $rolename, 

            'desc' => $desc, 

            'created_at' => CURRENT_TIMESTAMP 

        ); 

         

        return SingleTableCRUD::insert($this->tbRoles,$role); 

    } 

     

    /**

     * 修改角色,返回成功状态

     * 

     * @param array $role

     * @return int

     */ 

    function updateRole(array $role){        

        if (!isset($role['id'])) return false; 

         

        if (isset($role['rolename'])) unset($role['rolename']); 

        $role['updated_at'] = CURRENT_TIMESTAMP; 

         

        return SingleTableCRUD::update($this->tbRoles,$role,'id'); 

    } 

     

    /**

     * 删除角色

     * 

     * @param int $role_id

     * @return int

     */ 

    function deleteRole($role_id){ 

        if (emptyempty($role_id)) return false; 

        return SingleTableCRUD::delete($this->tbRoles,array('role_id'=>(int) $role_id)); 

    } 

     

    /**

     * 为资源指定角色,每次均先全部移除表中相关记录再插入

     * 

     * @param int $rsid

     * @param mixed $roleIds

     * @param boolean $setNull 当角色id不存在时,是否将资源从关联表中清空

     */ 

    function allocateRolesForResource($rsid,$roleIds,$setNull=false,$defaultAccess=-1){ 

        if (emptyempty($rsid)) return false; 

         

        $roleIds = normalize($roleIds,','); 

        if (emptyempty($roleIds)){ 

            if ($setNull){ 

                SingleTableCRUD::delete($this->tbRefResourcesRoles,array('rsid'=>$rsid)); 

                 

                if ($defaultAccess != -1){ 

                    $defaultAccess = self::formatAccessValue($defaultAccess); 

                    $this->updateResource(array('rsid'=>$rsid,'access'=>$defaultAccess)); 

                } 

                return true;  

            } 

            return false; 

        } 

         

        SingleTableCRUD::delete($this->tbRefResourcesRoles,array('rsid'=>$rsid)); 

         

        $roleIds = array_unique($roleIds); 

         

        foreach ($roleIds as $role_id){ 

            SingleTableCRUD::insert($this->tbRefResourcesRoles,array('rsid'=>$rsid,'role_id'=>(int)$role_id)); 

        } 

        return true; 

    } 

     

    function cleanRolesForResource($rsid){ 

        if (emptyempty($rsid)) return false; 

        return SingleTableCRUD::delete($this->tbRefResourcesRoles,array('rsid'=>$rsid)); 

    } 

     

    function cleanResourcesForRole($role_id){ 

        if (emptyempty($role_id)) return false; 

        return SingleTableCRUD::delete($this->tbRefResourcesRoles,array('role_id'=>(int) $role_id)); 

    } 

     

    /**

     * 为角色分配资源,每次均先全部移除表中相关记录再插入

     * 

     * @param int $role_id

     * @param mixed $rsids

     * 

     * @return boolean

     */ 

    function allocateResourcesForRole($role_id,$rsids){ 

        if (emptyempty($role_id)) return false; 

         

        $role_id = (int) $role_id; 

        $rsids = normalize($rsids,','); 

        if (emptyempty($rsids)){ 

            return false;        

        } 

         

        SingleTableCRUD::delete($this->tbRefResourcesRoles,array('role_id'=>$role_id)); 

         

        $rsids = array_unique($rsids); 

         

        foreach ($rsids as $rsid){ 

            SingleTableCRUD::insert($this->tbRefResourcesRoles,array('rsid'=>$rsid,'role_id'=>$role_id)); 

        } 

        return true; 

    } 

     

    /**

     * 为用户指派角色,每次均先全部移除表中相关记录再插入

     * 

     * 此处在用户很多的时候可能会有性能问题... 后面再想怎么优化

     * 

     * @param int $user_id

     * @param mixed $roleIds

     * 

     * @return boolean

     */ 

    function allocateRolesForUser($user_id,$roleIds){ 

        if (emptyempty($user_id)) return false; 

         

        $user_id = (int) $user_id; 

        $rsids = normalize($rsids,','); 

        if (emptyempty($rsids)){ 

            return false;        

        } 

         

        SingleTableCRUD::delete($this->tbRefUsersRoles,array('user_id'=>$user_id)); 

         

        $roleIds = array_unique($roleIds); 

         

        foreach ($roleIds as $roleId){ 

            SingleTableCRUD::insert($this->tbRefUsersRoles,array('user_id'=>$user_id,'role_id'=>$role_id)); 

        } 

        return true; 

    } 

         

    function cleanRolesForUser($user_id){ 

        if (emptyempty($user_id)) return false; 

        return SingleTableCRUD::delete($this->tbRefUsersRoles,array('user_id'=>(int) $user_id)); 

    } 

     

    function cleanUsersForRole($role_id){ 

        if (emptyempty($role_id)) return false; 

        return SingleTableCRUD::delete($this->tbRefUsersRoles,array('role_id'=>(int) $role_id)); 

    } 

     

 

/**

 * 对资源进行acl校验

 * 

 * @param string $rsid 资源标识

 * @param array $user  特定用户,不指定则校验当前用户

 * 

 * @return boolean

 */ 

function aclVerity($rsid,array $user = null){ 

    if (emptyempty($rsid)) return false; 

     

     

     

     

 

 

Java代码 

/*

     * 校验步骤如下:

     * 

     * 1. 先校验 资源本身access 属性

     *    EVERYONE => true,NOBODY  => false * 其它的属性在下面继续校验

     * 2. 从session(或者 用户session表)中获取角色id集合

     * 3. 如果 用户拥有角色 则HAS_ROLE => true , NO_ROLE => false;反之亦然

     * 4. 如果资源access == ALLOCATE_ROLES

     *      1. 从缓存(或者$tbRefResourcesRoles)中获取 资源对应的角色id集合

     *      2. 将用户拥有的角色id集合 与 资源对应的角色id集合求交集

     *      3. 存在交集=> true;否则=> false

     */  

 

花了半个小时 晕死 明天再抽空完善....

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

Using Dicr/Yii2-Google to integrate Google API in YII2 Using Dicr/Yii2-Google to integrate Google API in YII2 Apr 18, 2025 am 11:54 AM

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko

Title: Use Composer to solve the problem of unified representation of complex data types Title: Use Composer to solve the problem of unified representation of complex data types Apr 18, 2025 am 08:33 AM

Summary Description: When dealing with complex data types, you often encounter problems of how to uniformly represent and operate. This problem can be easily solved with Composer using the phrity/o library. It provides encapsulation classes and traits for various data types, making data processing more consistent and efficient.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

What are the plugins for wordpress blocking ip What are the plugins for wordpress blocking ip Apr 20, 2025 am 08:27 AM

WordPress IP blocking plugin selection is crucial. The following types can be considered: based on .htaccess: efficient, but complex operation; database operation: flexible, but low efficiency; firewall: high security performance, but complex configuration; self-written: highest control, but requires more technical level.

See all articles