casbin / webman-permission
webman casbin permission plugin
Installs: 3 338
Dependents: 2
Suggesters: 0
Security: 0
Stars: 52
Watchers: 6
Forks: 18
Open Issues: 1
pkg:composer/casbin/webman-permission
Requires
- php: >=8.0
- casbin/casbin: ~4.0
- doctrine/annotations: ^2.0
- php-di/php-di: ^7.0
- topthink/think-orm: ^2.0.53 || ^3.0.0 || ^4.0.30 || dev-master
- workerman/redis: ^2.0
Requires (Dev)
- illuminate/events: ^12.20
- illuminate/pagination: ^12.20
- php-coveralls/php-coveralls: ^2.7
- phpunit/phpunit: ^10.5
- psr/container: ^1.1.1
- symfony/var-dumper: ^7.3
- webman/database: ^2.1
- webman/think-orm: ^1.0
- workerman/webman: ^1.5||^2.0
README
🐇 An Authorization Library for Webman Plugin 🐇
🐇 Webman Authorization Plugin Based on Casbin 🐇
An authorization library that supports access control models like ACL, RBAC, ABAC for Webman plugin.
Table of Contents
- Installation
- Configuration
- Usage
- Multiple Driver Configuration
- Tutorials
- Testing
- Contributing
- Credits
- Troubleshooting
Installation
Install the package via Composer:
composer require -W casbin/webman-permission
Configuration
Dependency Injection
Modify the config/container.php configuration file as follows:
$builder = new \DI\ContainerBuilder(); $builder->addDefinitions(config('dependence', [])); $builder->useAutowiring(true); return $builder->build();
Database Configuration
By default, the policy storage uses ThinkORM.
1. Model Configuration
The default uses ThinkORM. Modify the database configuration in config/thinkorm.php.
Note: If using Laravel database, configure as follows:
- Modify the database configuration in
config/database.php- Change the
adapterinconfig/plugin/casbin/webman-permission/permission.phpto the Laravel adapter
2. Create casbin_rule Table
Execute the following SQL to create the policy rules table:
CREATE TABLE `casbin_rule` ( `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `ptype` VARCHAR(128) NOT NULL DEFAULT '', `v0` VARCHAR(128) NOT NULL DEFAULT '', `v1` VARCHAR(128) NOT NULL DEFAULT '', `v2` VARCHAR(128) NOT NULL DEFAULT '', `v3` VARCHAR(128) NOT NULL DEFAULT '', `v4` VARCHAR(128) NOT NULL DEFAULT '', `v5` VARCHAR(128) NOT NULL DEFAULT '', PRIMARY KEY (`id`) USING BTREE, KEY `idx_ptype` (`ptype`) USING BTREE, KEY `idx_v0` (`v0`) USING BTREE, KEY `idx_v1` (`v1`) USING BTREE, KEY `idx_v2` (`v2`) USING BTREE, KEY `idx_v3` (`v3`) USING BTREE, KEY `idx_v4` (`v4`) USING BTREE, KEY `idx_v5` (`v5`) USING BTREE ) ENGINE = INNODB CHARSET = utf8mb4 COMMENT = 'Casbin Policy Rules Table';
3. Configure Redis
Configure your Redis settings in config/redis.php.
4. Restart Webman
# Restart in foreground php start.php restart # Or restart in daemon mode php start.php restart -d
Usage
After successful installation, you can use the library as follows:
Basic Operations
use Casbin\WebmanPermission\Permission; // Add permissions to a user Permission::addPermissionForUser('eve', 'articles', 'read'); // Add a role for a user Permission::addRoleForUser('eve', 'writer'); // Add permissions to a role Permission::addPolicy('writer', 'articles', 'edit');
Permission Check
if (\Casbin\WebmanPermission\Permission::enforce('eve', 'articles', 'edit')) { echo 'Congratulations! Permission granted.'; } else { echo 'Sorry, you do not have access to this resource.'; }
Multiple Driver Configuration
You can use multiple driver configurations:
$permission = \Casbin\WebmanPermission\Permission::driver('restful_conf'); // Add permissions to a user $permission->addPermissionForUser('eve', 'articles', 'read'); // Add a role for a user $permission->addRoleForUser('eve', 'writer'); // Add permissions to a role $permission->addPolicy('writer', 'articles', 'edit'); // Check permissions if ($permission->enforce('eve', 'articles', 'edit')) { echo 'Congratulations! Permission granted.'; } else { echo 'Sorry, you do not have access to this resource.'; }
For more API details, refer to the Casbin API Documentation.
Tutorials
- Casbin Permission Practice: Getting Started (Chinese)
- Casbin Permission Practice: RBAC Authorization Based on Roles (Chinese)
- Casbin Permission Practice: RESTful and Middleware Usage (Chinese)
- Casbin Permission Practice: Using Custom Matching Functions (Chinese)
- Webman Practice Tutorial: Using Casbin Permission Control (Chinese)
Testing
This project includes a comprehensive unit test suite covering the following aspects:
Test File Structure
tests/
├── Adapter.php # Basic adapter tests
├── PermissionTest.php # Permission class tests
├── AdapterTest.php # Detailed adapter tests
├── EdgeCaseTest.php # Edge case tests
├── IntegrationTest.php # Integration tests
├── LaravelDatabase/
│ ├── LaravelDatabaseAdapterTest.php
│ └── TestCase.php
├── ThinkphpDatabase/
│ ├── DatabaseAdapterTest.php
│ └── TestCase.php
└── config/
└── plugin/
└── casbin/
└── webman-permission/
└── permission.php
Test Coverage
-
Basic Functionality
- Permission add, remove, check
- Role assignment, removal
- Policy management
-
Adapter Tests
- Database operations
- Filter functionality
- Batch operations
- Transaction handling
-
Edge Cases
- Null value handling
- Special characters
- Large data volumes
- Performance testing
-
Integration Tests
- Complete RBAC workflow
- Domain permission control
- Multi-driver support
- Complex business scenarios
-
Error Handling
- Exception scenarios
- Invalid input
- Concurrent access
Running Tests
# Run all tests php vendor/bin/phpunit tests/ # Run specific test file php vendor/bin/phpunit tests/PermissionTest.php # Run specific test method php vendor/bin/phpunit --filter testAddPermissionForUser tests/PermissionTest.php # Generate coverage report php vendor/bin/phpunit --coverage-html coverage tests/
Requirements
- PHP >= 8.1
- PHPUnit >= 9.0
- Database connection
- Redis connection
Test Environment
The test environment automatically creates the following tables:
casbin_rule- Default policy tableother_casbin_rule- Other driver policy table
Best Practices
-
Writing New Tests
- Inherit from appropriate test base classes
- Follow naming conventions
- Add necessary assertions
-
Test Data Management
- Use
setUp()andtearDown()methods - Ensure test data isolation
- Clean up test data
- Use
-
Test Coverage
- Cover normal workflows
- Test exception scenarios
- Verify boundary conditions
Contributing
Adding New Features
- Write corresponding test cases for new features
- Ensure test coverage meets requirements
- Run the complete test suite
- Check test status before submitting code
Bug Fixes
- Write reproduction tests for bugs
- Verify tests pass after fixing bugs
- Ensure existing functionality is not affected
Credits
Built on top of Casbin. For full documentation, visit the official website.
Advanced Configuration
Removing PHP-DI Dependency (Not Recommended)
- Uninstall the DI dependency package:
composer remove php-di/php-di
- Modify the
Casbin\WebmanPermission\Permissionfile:
Replace:
if (is_null(static::$_manager)) { static::$_manager = new Enforcer($model, Container::get($config['adapter']), false); }
With:
if (is_null(static::$_manager)) { if ($config['adapter'] == DatabaseAdapter::class) { $_model = new RuleModel(); } elseif ($config['adapter'] == LaravelDatabaseAdapter::class) { $_model = new LaravelRuleModel(); } static::$_manager = new Enforcer($model, new $config['adapter']($_model), false); }
Warning: This approach has high coupling and is not recommended. For more information, visit: https://www.workerman.net/doc/webman/di.html
Troubleshooting
Laravel Driver Error
Error: Call to a member function connection() on null
Solution: Check if your local database proxy is working correctly. Using Docker container host addresses like dnmp-mysql may cause this issue.
