Welcome Guest, Not a member yet? Register   Sign In
Why CI4 Shield do not store groups, permissions and rule on database
#1

(This post was last modified: 10-09-2024, 08:44 AM by quangpd.)

Hi,
I am still working with CI3 and a custom authentication library.
I tried CI4 and am excited about Shield for the same reason, but I noticed that it stores some things in a config file (AuthGroups.php).
Why doesn’t CI4 Shield store groups, permissions, and roles in the database?
Thanks
Reply
#2

(This post was last modified: 10-10-2024, 12:25 AM by luckmoshy.)

Shield normally stores roles in the database and assigns groups in the config otherwise you can also modify groups in your class to extend here is how to serve in the database 

PHP Code:
$user->addPermission('users.create''users.edit');  
https://shield.codeigniter.com/reference...orization/

PHP Code:
$user->addGroup('admin''beta'); 
Codeigniter First, Codeigniter Then You!!
yekrinaDigitals

Reply
#3
Rainbow 
(This post was last modified: 10-10-2024, 02:59 PM by quangpd.)

Hi, I found Shield's groups, permissions and rules can be save into database by Settings package
$defaultGroup = setting('AuthGroups.defaultGroup');
$groups = setting('AuthGroups.groups');
$permissions = setting('AuthGroups.permissions');
$matrix = setting('AuthGroups.matrix');

They are configable by hardcode fixed config value on file AuthGroups.php or save into database

PHP Code:
<?php
// \App\Config\Services
// /**
//  * The Auth service.
//  *
//  * @param bool $getShared
//  *
//  * @return CustomAuthService|mixed
//  */
// public static function auth($getShared = true)
// {
//    if ($getShared) {
//        return self::getSharedInstance('auth');
//    }

//    return new \App\Libraries\CustomAuthService();  // Use your custom service
// }
namespace App\Libraries;

use 
CodeIgniter\Shield\Config\Auth as AuthConfig;

class 
CustomAuthService extends \CodeIgniter\Shield\Auth
{
    function __construct()
    {
        parent::__construct(new AuthConfig());
    }

    /**
    * Create a new group and save it to the settings.
    *
    * @param string $group
    * @param string $title
    * @param string $description
    * @return bool
    */
    public function createGroup(string $groupstring $title ''string $description '')
    {
        // Fetch the existing groups from the settings
        $groups setting('AuthGroups.groups') ?? [];

        // Check if the group already exists
        if ($this->existedGroup($group)) {
            throw new \RuntimeException("Group '{$group}' already exists.");
        }

        // Add the new group
        $groups[$group] = [
            'title' => $title,
            'description' => $description
        
];

        // Save the updated groups to the settings
        setting()->set('AuthGroups.groups'$groups);

        return true;
    }

    /**
    * Delete a group and remove it from the settings.
    * Also remove the group from the users store in table 'auth_groups_users'.
    * 
    * @param string $group
    * @return bool
    */
    function deleteGroup(string $group)
    {
        // Fetch the existing groups from the settings
        $groups setting('AuthGroups.groups') ?? [];

        // Check if the group already exists
        if (!$this->existedGroup($group)) {
            throw new \RuntimeException("Group '{$group}' does not exist.");
        }

        // Remove the group
        unset($groups[$group]);

        // Remove the group from the matrix
        $matrix setting('AuthGroups.matrix') ?? [];
        unset($matrix[$group]);

        // Remove the group from the users store in table 'auth_groups_users'
        $db db_connect();
        if (!$db->table('auth_groups_users')->where('group'$group)->delete()) {
            throw new \RuntimeException("Failed to delete group '{$group}'.");
        }

        // Save the updated groups to the settings
        setting()->set('AuthGroups.groups'$groups);

        return true;
    }

    /**
    * Update a group and save it to the settings.
    * Also update the group in the users store in table 'auth_groups_users'.
    * 
    * @param string $group
    * @param string $groupNew
    * @param string $titleNew
    * @param string $descriptionNew
    * 
    * @return bool
    */
    function updateGroup(string $groupstring $groupNewstring $titleNew ''string $descriptionNew '')
    {
        // Fetch the existing groups from the settings
        $groups setting('AuthGroups.groups') ?? [];

        // Check if the group already exists
        if (!$this->existedGroup($group)) {
            throw new \RuntimeException("Group '{$group}' does not exist.");
        }

        // Update the group
        $groups[$group] = [
            'title' => $titleNew,
            'description' => $descriptionNew
        
];

        // Rename the group
        $groups[$groupNew] = $groups[$group];
        unset($groups[$group]);

        // Update the group in the matrix
        $matrix setting('AuthGroups.matrix') ?? [];
        $matrix[$groupNew] = $matrix[$group];
        unset($matrix[$group]);

        // Update the group in the users store in table 'auth_groups_users'
        $db db_connect();
        if (!$db->table('auth_groups_users')->where('group'$group)->update(['group' => $groupNew])) {
            throw new \RuntimeException("Failed to update group '{$group}' to '{$groupNew}'.");
        }

        // Save the updated groups to the settings
        setting()->set('AuthGroups.groups'$groups);

        return true;
    }

    /**
    * Check if a group already exists.
    *
    * @param string $group
    * @return bool
    */
    function existedGroup(string $group)
    {
        // Fetch the existing groups from the settings
        $groups setting('AuthGroups.groups') ?? [];

        // Check if the group already exists
        if (isset($groups[$group])) {
            return true;
        }

        return false;
    }

    /**
    * Create a new permission and save it to the settings.
    *
    * @param string $permissionName
    * @param string $description
    * 
    * @return bool
    */
    public function createPermission(string $permissionNamestring $description '')
    {
        // Fetch existing permissions from the settings
        $permissions setting('AuthGroups.permissions') ?? [];

        // Check if the permission already exists
        if ($this->existedPermission($permissionName)) {
            throw new \RuntimeException("Permission '{$permissionName}' already exists.");
        }

        // Add the new permission
        $permissions[$permissionName] = $description;

        // Save the updated permissions to the settings
        setting()->set('AuthGroups.permissions'$permissions);

        return "Permission '{$permissionName}' created successfully.";
    }

    /**
    * Update a permission and save it to the settings.
    * Also update the permission in the users store in table 'auth_permissions_users'.
    * 
    * @param string $permission
    * @param string $permissionNew
    * @param string $descriptionNew
    * 
    * @return bool
    */

    function updatePermission(string $permissionstring $permissionNewstring $descriptionNew '')
    {
        // Fetch the existing permissions from the settings
        $permissions setting('AuthGroups.permissions') ?? [];

        // Check if the permission already exists
        if (!$this->existedPermission($permission)) {
            throw new \RuntimeException("Permission '{$permission}' does not exist.");
        }

        // Update the permission
        $permissions[$permission] = $descriptionNew;

        // Rename the permission
        $permissions[$permissionNew] = $permissions[$permission];
        unset($permissions[$permission]);

        // Update the permission in the matrix
        $matrix setting('AuthGroups.matrix') ?? [];
        foreach ($matrix as $group => $perms) {
            if (($key array_search($permission$perms)) !== false) {
                $matrix[$group][$key] = $permissionNew;
            }
        }

        // Update the permission in the users store in table 'auth_permissions_users'
        $db db_connect();
        if (!$db->table('auth_permissions_users')->where('permission'$permission)->update(['permission' => $permissionNew])) {
            throw new \RuntimeException("Failed to update permission '{$permission}' to '{$permissionNew}'.");
        }

        // Save the updated permissions to the settings
        setting()->set('AuthGroups.permissions'$permissions);

        return true;
    }

    /**
    * Delete a permission and remove it from the settings.
    * Also remove the permission from the users store in table 'auth_permissions_users'.
    * 
    * @param string $permission
    * @return bool
    */
    function deletePermission(string $permission)
    {
        // Fetch the existing permissions from the settings
        $permissions setting('AuthGroups.permissions') ?? [];

        // Check if the permission already exists
        if (!$this->existedPermission($permission)) {
            throw new \RuntimeException("Permission '{$permission}' does not exist.");
        }

        // Remove the permission from the matrix
        $matrix setting('AuthGroups.matrix') ?? [];
        foreach ($matrix as $group => $perms) {
            if (($key array_search($permission$perms)) !== false) {
                unset($matrix[$group][$key]);
            }
        }

        // Remove the permission from the users store in table 'auth_permissions_users'
        $db db_connect();
        if ($db->table('auth_permissions_users')->where('permission'$permission)->delete()) {
            throw new \RuntimeException("Failed to delete permission '{$permission}'.");
        }

        // Remove the permission
        unset($permissions[$permission]);

        // Save the updated permissions to the settings
        setting()->set('AuthGroups.permissions'$permissions);

        return true;
    }

    /**
    * Check if a permission already exists.
    *
    * @param string $permission
    * @return bool
    */
    function existedPermission(string $permission)
    {
        // Fetch the existing permissions from the settings
        $permissions setting('AuthGroups.permissions') ?? [];

        // Check if the permission already exists
        if (isset($permissions[$permission])) {
            return true;
        }

        return false;
    }

    /**
    * Create or update a rule (permission matrix) that assigns permissions to groups.
    *
    * @param string $groups
    * @param string $permissionName
    * @return bool
    */
    public function createRule(string $groupNamestring $permissionName)
    {
        // Fetch the existing groups from the settings
        $groups setting('AuthGroups.groups') ?? [];

        // Check if the group already exists
        if (!isset($groups[$groupName])) {
            $this->createGroup($groupName);
        }

        // Fetch the existing permissions from the settings
        $permissions setting('AuthGroups.permissions') ?? [];

        // Check if the permission already exists
        if (!isset($permissions[$permissionName])) {
            $this->createPermission($permissionName);
        }

        // Fetch the existing matrix from the settings
        $matrix setting('AuthGroups.matrix') ?? [];

        if (!isset($matrix[$groupName])) {
            $matrix[$groupName] = [];
        }

        // Add the permission to the group's permissions if not already present
        if (!in_array($permissionName$matrix[$groupName])) {
            $matrix[$groupName][] = $permissionName;
        }

        // Save the updated matrix to the settings
        setting()->set('AuthGroups.matrix'$matrix);
        log_message('info'"Rule '{$groupName}' => '{$permissionName}' created successfully.");
        log_message('info'db_connect()->getLastQuery());

        return true;
    }

    /**
    * Create or update multiple rules (permission matrix) that assigns permissions to groups.
    *
    * @param array $groups
    * @param array $permissionNames
    * @return bool
    */
    function createRules(array $groupNames, array $permissionNames)
    {
        foreach ($groupNames as $groupName) {
            foreach ($permissionNames as $permissionName) {
                $this->createRule($groupName$permissionName);
            }
        }

        return true;
    }

    /**
    * Delete a rule (permission matrix) that assigns permissions to groups.
    *
    * @param string $groupName
    * @param string $permissionName
    * @return bool
    */
    public function deleteRule(string $groupNamestring $permissionName)
    {
        // Fetch the existing groups from the settings
        $groups setting('AuthGroups.groups') ?? [];

        // Check if the group already exists
        if (!isset($groups[$groupName])) {
            throw new \RuntimeException("Group '{$groupName}' does not exist.");
        }

        // Fetch the existing permissions from the settings
        $permissions setting('AuthGroups.permissions') ?? [];

        // Check if the permission already exists
        if (!isset($permissions[$permissionName])) {
            throw new \RuntimeException("Permission '{$permissionName}' does not exist.");
        }

        // Fetch the existing matrix from the settings
        $matrix setting('AuthGroups.matrix') ?? [];

        // Check if the group already exists
        if (!isset($matrix[$groupName])) {
            throw new \RuntimeException("Group '{$groupName}' does not have rule.");
        }

        // Remove the permission from the group's permissions
        if (($key array_search($permissionName$matrix[$groupName])) !== false) {
            unset($matrix[$groupName][$key]);
        }

        // Save the updated matrix to the settings
        setting()->set('AuthGroups.matrix'$matrix);

        return true;
    }

Reply




Theme © iAndrew 2016 - Forum software by © MyBB