├── roave-bc-check.yaml ├── infection.json.dist ├── .php-cs-fixer.dist.php ├── LICENSE ├── SECURITY.md ├── UPGRADING.md ├── composer.json ├── src ├── Config │ └── Permits.php └── Traits │ └── PermitsTrait.php ├── depfile.yaml ├── rector.php └── README.md /roave-bc-check.yaml: -------------------------------------------------------------------------------- 1 | parameters: 2 | ignoreErrors: 3 | - '#\[BC\] SKIPPED: .+ could not be found in the located source#' 4 | -------------------------------------------------------------------------------- /infection.json.dist: -------------------------------------------------------------------------------- 1 | { 2 | "source": { 3 | "directories": [ 4 | "src/" 5 | ], 6 | "excludes": [ 7 | "Config", 8 | "Database/Migrations", 9 | "Views" 10 | ] 11 | }, 12 | "logs": { 13 | "text": "build/infection.log" 14 | }, 15 | "mutators": { 16 | "@default": true 17 | }, 18 | "bootstrap": "vendor/codeigniter4/framework/system/Test/bootstrap.php" 19 | } 20 | -------------------------------------------------------------------------------- /.php-cs-fixer.dist.php: -------------------------------------------------------------------------------- 1 | files() 9 | ->in([ 10 | __DIR__ . '/src/', 11 | __DIR__ . '/tests/', 12 | ]) 13 | ->exclude('build') 14 | ->append([__FILE__]); 15 | 16 | $overrides = []; 17 | 18 | $options = [ 19 | 'finder' => $finder, 20 | 'cacheFile' => 'build/.php-cs-fixer.cache', 21 | ]; 22 | 23 | return Factory::create(new CodeIgniter4(), $overrides, $options)->forProjects(); 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019-2020 Tatter Software 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | The development team and community take all security issues seriously. **Please do not make public any uncovered flaws.** 4 | 5 | ## Reporting a Vulnerability 6 | 7 | Thank you for improving the security of our code! Any assistance in removing security flaws will be acknowledged. 8 | 9 | **Please report security flaws by emailing the development team directly: support@tattersoftware.com**. 10 | 11 | The lead maintainer will acknowledge your email within 48 hours, and will send a more detailed response within 48 hours indicating 12 | the next steps in handling your report. After the initial reply to your report, the security team will endeavor to keep you informed of the 13 | progress towards a fix and full announcement, and may ask for additional information or guidance. 14 | 15 | ## Disclosure Policy 16 | 17 | When the security team receives a security bug report, they will assign it to a primary handler. 18 | This person will coordinate the fix and release process, involving the following steps: 19 | 20 | - Confirm the problem and determine the affected versions. 21 | - Audit code to find any potential similar problems. 22 | - Prepare fixes for all releases still under maintenance. These fixes will be released as fast as possible. 23 | 24 | ## Comments on this Policy 25 | 26 | If you have suggestions on how this process could be improved please submit a Pull Request. 27 | -------------------------------------------------------------------------------- /UPGRADING.md: -------------------------------------------------------------------------------- 1 | # Upgrade Guide 2 | 3 | ## Version 2 to 3 4 | *** 5 | 6 | > Note: This is a complete refactor! Please be sure to read the docs carefully before upgrading. 7 | 8 | * Minimum PHP version has been bumped to `7.4` to match the upcoming framework changes 9 | * All properties that can be typed have been 10 | * Now requires a verified authentication system via `codeigniter4/authentication-implementation` 11 | * Switches to `Tatter\Users` for interface handling; [read the docs](https://github.com/tattersoftware/codeigniter4-users) to be sure your Models and Entities are configured 12 | * No longer handles explicit permissions - these should now handled by your Auth library; read more below 13 | * Related, the follow classes have been removed: `PermitModel`, `UserModel`, `PermitsFilter`, `PermitException`, and the Permits commands, language, and migration files 14 | * Permissions are now set in the Config file with friendly strings, so the **chmod Helper** is no longer necessary and has been removed 15 | 16 | ### Permissions 17 | 18 | In order to reduce overlap this library no longer handles explicit permissions; instead 19 | permissions should now handled by your Auth library. `Permits` uses the user interface 20 | extension `Tatter\Users\Interfaces\HasPermission` to check for explicit permissions in the 21 | format "{table}.{verb}". If you have existing explicit permissions (i.e. entries in the 22 | `permits` table) then convert them to your Auth library's format before removing the 23 | `permits` table. You may also need to update your `migrations` table in case your project 24 | complains about a "gap in the migrations". 25 | 26 | Likewise, the `PermitsFilter` has been removed because most Auth libraries now include the 27 | same functionality. Update any references in **app/Config/Filters.php**. 28 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tatter/permits", 3 | "type": "library", 4 | "description": "Model permission handling for CodeIgniter 4", 5 | "keywords": [ 6 | "codeigniter", 7 | "codeigniter4", 8 | "permission", 9 | "authorization", 10 | "access", 11 | "rights", 12 | "CRUD" 13 | ], 14 | "homepage": "https://github.com/tattersoftware/codeigniter4-permits", 15 | "license": "MIT", 16 | "authors": [ 17 | { 18 | "name": "Matthew Gatner", 19 | "email": "mgatner@tattersoftware.com", 20 | "homepage": "https://tattersoftware.com", 21 | "role": "Developer" 22 | } 23 | ], 24 | "require": { 25 | "php": "^7.4 || ^8.0", 26 | "codeigniter4/authentication-implementation": "^1.0", 27 | "tatter/users": "^1.2" 28 | }, 29 | "require-dev": { 30 | "codeigniter4/devkit": "^1.0", 31 | "codeigniter4/framework": "^4.1", 32 | "tatter/imposter": "^1.1" 33 | }, 34 | "config": { 35 | "allow-plugins": { 36 | "phpstan/extension-installer": true 37 | } 38 | }, 39 | "autoload": { 40 | "psr-4": { 41 | "Tatter\\Permits\\": "src" 42 | }, 43 | "exclude-from-classmap": [ 44 | "**/Database/Migrations/**" 45 | ] 46 | }, 47 | "autoload-dev": { 48 | "psr-4": { 49 | "Tests\\Support\\": "tests/_support" 50 | } 51 | }, 52 | "minimum-stability": "dev", 53 | "prefer-stable": true, 54 | "scripts": { 55 | "analyze": "phpstan analyze", 56 | "ci": [ 57 | "Composer\\Config::disableProcessTimeout", 58 | "@deduplicate", 59 | "@analyze", 60 | "@test", 61 | "@inspect", 62 | "rector process", 63 | "@style" 64 | ], 65 | "deduplicate": "phpcpd app/ src/", 66 | "inspect": "deptrac analyze --cache-file=build/deptrac.cache", 67 | "mutate": "infection --threads=2 --skip-initial-tests --coverage=build/phpunit", 68 | "retool": "retool", 69 | "style": "php-cs-fixer fix --verbose --ansi --using-cache=no", 70 | "test": "phpunit" 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/Config/Permits.php: -------------------------------------------------------------------------------- 1 | 51 | */ 52 | public array $default = [ 53 | 'admin' => self::NOBODY, 54 | 'create' => self::USERS, 55 | 'list' => self::ANYBODY, 56 | 'read' => self::ANYBODY, 57 | 'update' => self::OWNERS, 58 | 'delete' => self::OWNERS, 59 | 'userKey' => null, 60 | 'pivotKey' => null, 61 | 'pivotTable' => null, 62 | ]; 63 | 64 | /** 65 | * Verifies a permission against the supplied values. 66 | * 67 | * @throws DomainException If an unknown permission is passed 68 | */ 69 | final public static function check(int $access, ?int $userId, ?bool $owner = null): bool 70 | { 71 | if ($access === self::ANYBODY) { 72 | return true; 73 | } 74 | if ($access === self::USERS) { 75 | return $userId !== null; 76 | } 77 | if ($access === self::OWNERS) { 78 | return isset($userId, $owner) && $owner; 79 | } 80 | 81 | if ($access === self::NOBODY) { 82 | return false; 83 | } 84 | 85 | throw new DomainException('Undefined access value: ' . $access); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /depfile.yaml: -------------------------------------------------------------------------------- 1 | paths: 2 | - ./src/ 3 | - ./vendor/codeigniter4/framework/system/ 4 | - ./vendor/tatter/ 5 | exclude_files: 6 | - '#.*test.*#i' 7 | layers: 8 | - name: Model 9 | collectors: 10 | - type: bool 11 | must: 12 | - type: className 13 | regex: .*[A-Za-z]+Model$ 14 | must_not: 15 | - type: directory 16 | regex: vendor/.* 17 | - name: Vendor Model 18 | collectors: 19 | - type: bool 20 | must: 21 | - type: className 22 | regex: .*[A-Za-z]+Model$ 23 | - type: directory 24 | regex: vendor/.* 25 | - name: Controller 26 | collectors: 27 | - type: bool 28 | must: 29 | - type: className 30 | regex: .*\/Controllers\/.* 31 | must_not: 32 | - type: directory 33 | regex: vendor/.* 34 | - name: Vendor Controller 35 | collectors: 36 | - type: bool 37 | must: 38 | - type: className 39 | regex: .*\/Controllers\/.* 40 | - type: directory 41 | regex: vendor/.* 42 | - name: Config 43 | collectors: 44 | - type: bool 45 | must: 46 | - type: directory 47 | regex: src/Config/.* 48 | must_not: 49 | - type: className 50 | regex: .*Services 51 | - type: directory 52 | regex: vendor/.* 53 | - name: Vendor Config 54 | collectors: 55 | - type: bool 56 | must: 57 | - type: directory 58 | regex: vendor/.*/Config/.* 59 | must_not: 60 | - type: className 61 | regex: .*Services 62 | - name: Entity 63 | collectors: 64 | - type: bool 65 | must: 66 | - type: directory 67 | regex: src/Entities/.* 68 | must_not: 69 | - type: directory 70 | regex: vendor/.* 71 | - name: Vendor Entity 72 | collectors: 73 | - type: bool 74 | must: 75 | - type: directory 76 | regex: vendor/.*/Entities/.* 77 | - name: View 78 | collectors: 79 | - type: bool 80 | must: 81 | - type: directory 82 | regex: src/Views/.* 83 | must_not: 84 | - type: directory 85 | regex: vendor/.* 86 | - name: Vendor View 87 | collectors: 88 | - type: bool 89 | must: 90 | - type: directory 91 | regex: vendor/.*/Views/.* 92 | - name: Service 93 | collectors: 94 | - type: className 95 | regex: .*Services.* 96 | ruleset: 97 | Entity: 98 | - Config 99 | - Model 100 | - Service 101 | - Vendor Config 102 | - Vendor Entity 103 | - Vendor Model 104 | Config: 105 | - Service 106 | - Vendor Config 107 | Model: 108 | - Config 109 | - Entity 110 | - Service 111 | - Vendor Config 112 | - Vendor Entity 113 | - Vendor Model 114 | Service: 115 | - Config 116 | - Vendor Config 117 | 118 | # Ignore anything in the Vendor layers 119 | Vendor Model: 120 | - Config 121 | - Service 122 | - Vendor Config 123 | - Vendor Controller 124 | - Vendor Entity 125 | - Vendor Model 126 | - Vendor View 127 | Vendor Controller: 128 | - Service 129 | - Vendor Config 130 | - Vendor Controller 131 | - Vendor Entity 132 | - Vendor Model 133 | - Vendor View 134 | Vendor Config: 135 | - Config 136 | - Service 137 | - Vendor Config 138 | - Vendor Controller 139 | - Vendor Entity 140 | - Vendor Model 141 | - Vendor View 142 | Vendor Entity: 143 | - Service 144 | - Vendor Config 145 | - Vendor Controller 146 | - Vendor Entity 147 | - Vendor Model 148 | - Vendor View 149 | Vendor View: 150 | - Service 151 | - Vendor Config 152 | - Vendor Controller 153 | - Vendor Entity 154 | - Vendor Model 155 | - Vendor View 156 | skip_violations: 157 | -------------------------------------------------------------------------------- /rector.php: -------------------------------------------------------------------------------- 1 | import(SetList::DEAD_CODE); 41 | $containerConfigurator->import(LevelSetList::UP_TO_PHP_74); 42 | $containerConfigurator->import(PHPUnitSetList::PHPUNIT_SPECIFIC_METHOD); 43 | $containerConfigurator->import(PHPUnitSetList::PHPUNIT_80); 44 | 45 | $parameters = $containerConfigurator->parameters(); 46 | 47 | $parameters->set(Option::PARALLEL, true); 48 | // The paths to refactor (can also be supplied with CLI arguments) 49 | $parameters->set(Option::PATHS, [ 50 | __DIR__ . '/src/', 51 | __DIR__ . '/tests/', 52 | ]); 53 | 54 | // Include Composer's autoload - required for global execution, remove if running locally 55 | $parameters->set(Option::AUTOLOAD_PATHS, [ 56 | __DIR__ . '/vendor/autoload.php', 57 | ]); 58 | 59 | // Do you need to include constants, class aliases, or a custom autoloader? 60 | $parameters->set(Option::BOOTSTRAP_FILES, [ 61 | realpath(getcwd()) . '/vendor/codeigniter4/framework/system/Test/bootstrap.php', 62 | ]); 63 | 64 | if (is_file(__DIR__ . '/phpstan.neon.dist')) { 65 | $parameters->set(Option::PHPSTAN_FOR_RECTOR_PATH, __DIR__ . '/phpstan.neon.dist'); 66 | } 67 | 68 | // Set the target version for refactoring 69 | $parameters->set(Option::PHP_VERSION_FEATURES, PhpVersion::PHP_74); 70 | 71 | // Auto-import fully qualified class names 72 | $parameters->set(Option::AUTO_IMPORT_NAMES, true); 73 | 74 | // Are there files or rules you need to skip? 75 | $parameters->set(Option::SKIP, [ 76 | __DIR__ . '/src/Views', 77 | 78 | JsonThrowOnErrorRector::class, 79 | StringifyStrNeedlesRector::class, 80 | 81 | // Note: requires php 8 82 | RemoveUnusedPromotedPropertyRector::class, 83 | 84 | // Ignore tests that might make calls without a result 85 | RemoveEmptyMethodCallRector::class => [ 86 | __DIR__ . '/tests', 87 | ], 88 | 89 | // Ignore files that should not be namespaced 90 | NormalizeNamespaceByPSR4ComposerAutoloadRector::class => [ 91 | __DIR__ . '/src/Helpers', 92 | ], 93 | 94 | // May load view files directly when detecting classes 95 | StringClassNameToClassConstantRector::class, 96 | 97 | // May be uninitialized on purpose 98 | AddDefaultValueForUndefinedVariableRector::class, 99 | ]); 100 | 101 | // Additional rules to apply 102 | $services = $containerConfigurator->services(); 103 | $services->set(SimplifyUselessVariableRector::class); 104 | $services->set(RemoveAlwaysElseRector::class); 105 | $services->set(CountArrayToEmptyArrayComparisonRector::class); 106 | $services->set(ForToForeachRector::class); 107 | $services->set(ChangeNestedForeachIfsToEarlyContinueRector::class); 108 | $services->set(ChangeIfElseValueAssignToEarlyReturnRector::class); 109 | $services->set(SimplifyStrposLowerRector::class); 110 | $services->set(CombineIfRector::class); 111 | $services->set(SimplifyIfReturnBoolRector::class); 112 | $services->set(InlineIfToExplicitIfRector::class); 113 | $services->set(PreparedValueToEarlyReturnRector::class); 114 | $services->set(ShortenElseIfRector::class); 115 | $services->set(SimplifyIfElseToTernaryRector::class); 116 | $services->set(UnusedForeachValueToArrayKeysRector::class); 117 | $services->set(ChangeArrayPushToArrayAssignRector::class); 118 | $services->set(UnnecessaryTernaryExpressionRector::class); 119 | $services->set(AddPregQuoteDelimiterRector::class); 120 | $services->set(SimplifyRegexPatternRector::class); 121 | $services->set(FuncGetArgsToVariadicParamRector::class); 122 | $services->set(MakeInheritedMethodVisibilitySameAsParentRector::class); 123 | $services->set(SimplifyEmptyArrayCheckRector::class); 124 | $services->set(NormalizeNamespaceByPSR4ComposerAutoloadRector::class); 125 | }; 126 | -------------------------------------------------------------------------------- /src/Traits/PermitsTrait.php: -------------------------------------------------------------------------------- 1 | |null 25 | */ 26 | private ?array $permits = null; 27 | 28 | /** 29 | * Checks whether the current/supplied user may perform any of the other actions. 30 | */ 31 | public function mayAdmin(?int $userId = null): bool 32 | { 33 | return $this->permissible('admin', $userId); 34 | } 35 | 36 | /** 37 | * Checks whether the current/supplied user may insert rows into this model's table. 38 | */ 39 | public function mayCreate(?int $userId = null): bool 40 | { 41 | return $this->permissible('create', $userId); 42 | } 43 | 44 | /** 45 | * Checks whether the current/supplied user may list rows from this model's table. 46 | */ 47 | public function mayList(?int $userId = null): bool 48 | { 49 | return $this->permissible('list', $userId); 50 | } 51 | 52 | /** 53 | * Checks whether the current/supplied user may read the given object. 54 | * 55 | * @param mixed $item 56 | */ 57 | public function mayRead($item, ?int $userId = null): bool 58 | { 59 | return $this->permissible('read', $userId, $item); 60 | } 61 | 62 | /** 63 | * Checks whether the current/supplied user may update the given object. 64 | * 65 | * @param mixed $item 66 | */ 67 | public function mayUpdate($item, ?int $userId = null): bool 68 | { 69 | return $this->permissible('update', $userId, $item); 70 | } 71 | 72 | /** 73 | * Checks whether the current/supplied user may delete the given object. 74 | * 75 | * @param mixed $item 76 | */ 77 | public function mayDelete($item, ?int $userId = null): bool 78 | { 79 | return $this->permissible('delete', $userId, $item); 80 | } 81 | 82 | //-------------------------------------------------------------------- 83 | // Support Methods (internal) 84 | //-------------------------------------------------------------------- 85 | 86 | /** 87 | * Handles the processing of permission checks. 88 | * Should not be called directly - use the "mayVerb()" methods. 89 | * 90 | * @param array|object|null $item An item of $returnType, or null for domain verbs (create, list) 91 | * 92 | * @throws UnexpectedValueException If an authenticated user is indicated but unable to be located 93 | */ 94 | final protected function permissible(string $verb, ?int $userId, $item = null): bool 95 | { 96 | // Determine the user (if any) 97 | $userId ??= user_id(); 98 | 99 | if ($userId !== null) { 100 | $user = service('users')->findById($userId); 101 | if ($user === null) { 102 | throw new UnexpectedValueException('User provider was unable to locate a User with ID: ' . $userId); 103 | } 104 | 105 | // Check for overriding authorization 106 | if ($this->userHasPermission($user, $verb)) { 107 | return true; 108 | } 109 | } 110 | 111 | // Using inferred permissions 112 | $access = $this->getPermits()[$verb]; 113 | 114 | // Handle scenarios they do not require ownership lookup 115 | if (! isset($user) || $access !== Permits::OWNERS || in_array($verb, ['admin', 'create', 'list'], true)) { 116 | return Permits::check($access, $userId); 117 | } 118 | 119 | // Everything else needs database lookup, so transform and verify the item 120 | $item = $this->transformDataToArray($item, 'insert'); 121 | 122 | return Permits::check($access, $userId, $this->userOwnsItem($user, $item)); 123 | } 124 | 125 | /** 126 | * Checks if a User is authorized for the given action. 127 | */ 128 | private function userHasPermission(UserEntity $user, string $verb): bool 129 | { 130 | if (! $user instanceof HasPermission) { 131 | return false; 132 | } 133 | 134 | // Always allow admin access 135 | if ($user->hasPermission($this->table . '.admin')) { 136 | return true; 137 | } 138 | 139 | return $user->hasPermission($this->table . '.' . $verb); 140 | } 141 | 142 | /** 143 | * Checks if the User owns the item. 144 | */ 145 | private function userOwnsItem(UserEntity $user, array $item): bool 146 | { 147 | $permits = $this->getPermits(); 148 | 149 | // Make sure user lookup is enabled 150 | if ($permits['userKey'] === null) { 151 | return false; 152 | } 153 | 154 | // Check if the item itself has $userKey set 155 | if (isset($item[$permits['userKey']])) { 156 | return $user->getId() === $item[$permits['userKey']]; 157 | } 158 | 159 | // Make sure there is a valid pivot table and ID 160 | if ($permits['pivotTable'] === null || $permits['pivotKey'] === null || ! isset($item[$this->primaryKey])) { 161 | return false; 162 | } 163 | 164 | return (bool) $this->db 165 | ->table($permits['pivotTable']) 166 | ->where($permits['userKey'], $user->getId()) 167 | ->where($permits['pivotKey'], $item[$this->primaryKey]) 168 | ->limit(1) 169 | ->get() 170 | ->getUnbufferedRow(); 171 | } 172 | 173 | //-------------------------------------------------------------------- 174 | // Testing Helper Methods 175 | //-------------------------------------------------------------------- 176 | 177 | /** 178 | * Changes the configuration. Used mostly for testing. 179 | * 180 | * @param array|null $permits Use `null` to restore from the Config file. 181 | * 182 | * @return $this 183 | * 184 | * @internal 185 | */ 186 | final public function setPermits(?array $permits): self 187 | { 188 | $this->permits = array_merge(config('Permits')->default, $permits ?? []); 189 | 190 | return $this; 191 | } 192 | 193 | /** 194 | * Determines and returns the configuration. 195 | * 196 | * @return array 197 | * 198 | * @internal 199 | */ 200 | final public function getPermits(): array 201 | { 202 | if ($this->permits === null) { 203 | $this->setPermits(config('Permits')->{$this->table} ?? null); 204 | } 205 | 206 | return $this->permits; 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tatter\Permits 2 | Model permission handling for CodeIgniter 4 3 | 4 | [![](https://github.com/tattersoftware/codeigniter4-permits/workflows/PHPUnit/badge.svg)](https://github.com/tattersoftware/codeigniter4-permits/actions/workflows/test.yml) 5 | [![](https://github.com/tattersoftware/codeigniter4-permits/workflows/PHPStan/badge.svg)](https://github.com/tattersoftware/codeigniter4-permits/actions/workflows/analyze.yml) 6 | [![](https://github.com/tattersoftware/codeigniter4-permits/workflows/Deptrac/badge.svg)](https://github.com/tattersoftware/codeigniter4-permits/actions/workflows/inspect.yml) 7 | [![Coverage Status](https://coveralls.io/repos/github/tattersoftware/codeigniter4-permits/badge.svg?branch=develop)](https://coveralls.io/github/tattersoftware/codeigniter4-permits?branch=develop) 8 | 9 | ## Quick Start 10 | 11 | 1. Install with Composer: `> composer require tatter/permits` 12 | 2. Add the trait to your models: 13 | ```php 14 | class BlogModel extends Model 15 | { 16 | use PermitsTrait; 17 | ``` 18 | 3. Use the CRUDL verbs to check access: `if ($blogs->mayCreate()) ...` 19 | 20 | ## Features 21 | 22 | `Permits` solves a common problem with object rights management: "Can this user 23 | add/change/remove this item?" This library provides object-level access rights to your 24 | Model classes via a single trait that adds CRUDL-style verbs to your model. 25 | 26 | ## Installation 27 | 28 | Install easily via Composer to take advantage of CodeIgniter 4's autoloading capabilities 29 | and always be up-to-date: 30 | ```bash 31 | composer require tatter/permits 32 | ``` 33 | 34 | Or, install manually by downloading the source files and adding the directory to 35 | **app/Config/Autoload.php**. 36 | 37 | `Permits` requires the Composer provision for `codeigniter4/authentication-implementation` 38 | as describe in the [CodeIgniter authentication guidelines](https://codeigniter4.github.io/CodeIgniter4/extending/authentication.html). 39 | You must install and configure a [supported package](https://packagist.org/providers/codeigniter4/authentication-implementation) 40 | to handle authentication and authorization in order for `Permits` to understand your users. 41 | 42 | ## Configuration (optional) 43 | 44 | The library's default behavior can be altered by extending its config file. Copy 45 | **examples/Permits.php to **app/Config/** and follow the instructions in the comments. 46 | If no config file is found in **app/Config** the library will use its own. 47 | 48 | The Config files includes a set of `$default` access levels which you may modify in your 49 | own version. Each Model you intend to use should have a Config property corresponding to 50 | its `$table` property with properties for anything that needs adjusting from the defaults. 51 | 52 | Once your configuration is complete simply include the `PermitsTrait` on your models to 53 | enable the methods: 54 | ```php 55 | use CodeIgniter\Model; 56 | use Tatter\Permits\Traits\PermitsTrait; 57 | 58 | class FruitModel extends Model 59 | { 60 | use PermitsTrait; 61 | ... 62 | ``` 63 | 64 | ## Usage 65 | 66 | There are two types of permissions: explicit and inferred. Both rely on this common set of 67 | CRUDL verbs: 68 | * **create**: Make new items 69 | * **read**: View a single item 70 | * **update**: Make changes to a single item 71 | * **delete**: Delete a single item 72 | * **list**: View an index of all items 73 | * **admin**: Perform any of the above regardless of other rights 74 | 75 | Use the corresponding Model verbs to check the access: 76 | ```php 77 | if (! $model->mayCreate()) { 78 | return redirect()->back()->with('error', 'You do not have permission to do that!'); 79 | } 80 | 81 | $item = $model->find($id); 82 | if (! $model->mayUpdate($item)) { 83 | return redirect()->back()->with('error', 'You can only update your own items!'); 84 | } 85 | ``` 86 | 87 | `PermitsTrait` will check access rights based on the current logged in user (if there is one) 88 | but you may also pass an explicit user ID to check instead: 89 | ```php 90 | if (! $model->mayAdmin($userId)) { 91 | log_message('debug', "User #{$userId} attempted to access item administration."); 92 | } 93 | ``` 94 | 95 | ### Explicit 96 | 97 | Explicit permissions are granted to users or groups via your authorization library. `Permits` 98 | uses [Tatter\Users](https://packagist.org/packages/tatter/users) to interact with user records 99 | and determine explicit permissions. If your authentication package is not supported by 100 | `Users` autodiscovery then be sure to [read the docs](https://github.com/tattersoftware/codeigniter4-users) 101 | on how to include it. 102 | 103 | When checking explicit permissions `Permits` uses the format "table.verb". For example, if 104 | your project includes a `BlogModel` and you want to allow Blog Editors access to edit anybody's 105 | blog entries you would assign "blogs.edit" to the "editors" group. 106 | 107 | > Note: Explicit permissions always take precedence over inferred permissions. 108 | 109 | ### Inferred 110 | 111 | Inferred permissions use the configuration (see above) to determine any individual user's 112 | access to an item or group of items. There are four access levels which may be applied to 113 | each verb (these are constants on `Tatter\Permits\Config\Permits`): 114 | 115 | * `NOBODY`: Prohibits all access without explicit permission 116 | * `OWNERS`: Requires the authenticated user to own the item 117 | * `OWNERS`: Requires the authenticated user to own the item 118 | * `USERS`: Requires any authenticated user 119 | * `ANYBODY`: Allows anyone regardless of authentication or ownership 120 | 121 | In addition to the access levels, each model should be configured on how to determine item 122 | ownership. Set whichever of the following values are necessary on your table's Config property: 123 | * `userKey`: Field for the user ID in the item or its pivot table 124 | * `pivotKey`: Field for the item's ID in the pivot tables 125 | * `pivotTable`: Table that joins the items to their owners 126 | 127 | ## Example 128 | 129 | Your web app includes a Content Management System that allows the site owners to log in and 130 | update various parts of the site. This includes a blog section, with its own Model, Controller, 131 | and Views. Any visitors to your site can create an account and submit a blog entry, but it 132 | needs to be approved before it "goes live". Being the brilliant developer you are, you decide 133 | to use `Tatter\Permits` to manage access to the blog entries. 134 | 135 | > `Permits` requires an [authentication implementation](https://packagist.org/providers/codeigniter4/authentication-implementation); 136 | > for this example we will use [Shield](https://github.com/lonnieezell/codeigniter-shield). 137 | 138 | First we need to make sure our authentication package is ready with the correct permissions. 139 | This may vary back package, but `Shield` defines Groups and Permissions using 140 | [Config files](https://github.com/lonnieezell/codeigniter-shield/blob/develop/docs/3%20-%20authorization.md). 141 | We will leave the existing groups and add a new "editors" group. 142 | **app/Config/AuthGroups.php**: 143 | ```php 144 | public $groups = [ 145 | 'superadmin' => [ 146 | 'title' => 'Super Admin', 147 | 'description' => 'Complete control of the site.', 148 | ], 149 | 'admin' => [ 150 | 'title' => 'Admin', 151 | 'description' => 'Day to day administrators of the site.', 152 | ], 153 | 'developer' => [ 154 | 'title' => 'Developer', 155 | 'description' => 'Site programmers.', 156 | ], 157 | 'user' => [ 158 | 'title' => 'User', 159 | 'description' => 'General users of the site. Often customers.', 160 | ], 161 | 'beta' => [ 162 | 'title' => 'Beta User', 163 | 'description' => 'Has access to beta-level features.', 164 | ], 165 | 'editor' => [ 166 | 'title' => 'Blog Editors', 167 | 'description' => 'Has access to all blog entries.', 168 | ], 169 | ]; 170 | ``` 171 | 172 | We want to give explicit permission for blog administration to some groups, so in the same 173 | file we add a new permission in the format "{table}.{verb}": 174 | ```php 175 | public $permissions = [ 176 | 'admin.access' => 'Can access the sites admin area', 177 | 'admin.settings' => 'Can access the main site settings', 178 | 'users.manage-admins' => 'Can manage other admins', 179 | 'users.create' => 'Can create new non-admin users', 180 | 'users.edit' => 'Can edit existing non-admin users', 181 | 'users.delete' => 'Can delete existing non-admin users', 182 | 'beta.access' => 'Can access beta-level features', 183 | 'blogs.admin' => 'Allows all access to blog model operations', 184 | ]; 185 | ``` 186 | 187 | Finally we add the new permission to the groups we want to have it, in the same file still: 188 | ```php 189 | public $matrix = [ 190 | 'superadmin' => [ 191 | 'admin.*', 192 | 'users.*', 193 | 'beta.*', 194 | 'blogs.*', 195 | ], 196 | 'admin' => [ 197 | 'admin.access', 198 | 'users.create', 199 | 'users.edit', 200 | 'users.delete', 201 | 'beta.access', 202 | 'blogs.admin', 203 | ], 204 | 'developer' => [ 205 | 'admin.access', 206 | 'admin.settings', 207 | 'users.create', 208 | 'users.edit', 209 | 'beta.access', 210 | ], 211 | 'user' => [], 212 | 'beta' => [ 213 | 'beta.access', 214 | ], 215 | 'editor' => [ 216 | 'blogs.admin', 217 | ], 218 | ]; 219 | ``` 220 | 221 | That's it for the third-party authorization configuration! On to `Permits` - first thing we 222 | need is to set the permissions in our Config file. We can leave the defaults as they are 223 | and add our own property. 224 | **app/Config/Permits.php**: 225 | ```php 226 | /* 227 | * @var array 228 | */ 229 | public $blogs = [ 230 | 'admin' => self::NOBODY, 231 | 'create' => self::USERS, 232 | 'list' => self::USERS, 233 | 'read' => self::OWNERS, 234 | 'update' => self::OWNERS, 235 | 'delete' => self::OWNERS, 236 | 'userKey' => 'user_id', 237 | 'pivotKey' => null, 238 | 'pivotTable' => null, 239 | ]; 240 | } 241 | ``` 242 | 243 | Let's break that down. 244 | 245 | 1. The first permission, "admin": we gave explicit rights to above in our 246 | auth package so we do not want anyone else having access, hence `NOBODY`. Explicit permissions 247 | take precedence so our "superadmin", "admin", and "editor" groups will still have full access. 248 | 249 | 2. Next are "list" and "create": both are available to `USERS` - that is, anyone who is logged 250 | in. They will be able to create new entries and see a list of others' entries. 251 | 252 | 3. However, "read", "update", and "delete" are all restricted to `OWNERS` - authenticated users will only 253 | be able to click on their own entries to read and modify the content. 254 | 255 | 4. Finally, we need a way for `Permits` to decide "who owns this". In this case we set "userKey" 256 | but leave the pivot properties blank - meaning, our `blogs` table has a field called `user_id` 257 | which corresponds to the ID of the user that created the blog. 258 | 259 | > In more complex setups where multiple users are assigned to multiple blogs we might have a 260 | > join table, in which case we would also have set "pivotTable" to something like `blogs_users` 261 | > and "pivotKey" like `blog_id`. 262 | 263 | Configuration complete! The final piece to the integration is to add our trait to the blog 264 | model, which will handle activating our access verbs. 265 | **app/Models/BlogModel.php**: 266 | ```php 267 | 268 | use App\Entities\Blog; 269 | use CodeIgniter\Model; 270 | use Tatter\Permits\Traits\PermitsTrait; 271 | 272 | class BlogModel extends Model 273 | { 274 | use PermitsTrait; 275 | 276 | protected $table = 'blogs'; 277 | protected $primaryKey = 'id'; 278 | protected $returnType = Blog::class; 279 | ... 280 | } 281 | ``` 282 | 283 | Integration complete! Now you are ready to start using `Permits` in your code. Let's make 284 | a Controller for our blogs and add some permissions checks before the regular code. 285 | **app/Controllers/Blogs.php**: 286 | ```php 287 | model = model(BlogModel::class); 307 | } 308 | 309 | /** 310 | * Displays the list of approved blogs 311 | * for all visitors of the website. 312 | */ 313 | public function index(): string 314 | { 315 | return view('blogs/public', [ 316 | 'blogs' => $this->model->findAll(), 317 | ]); 318 | } 319 | 320 | /** 321 | * Displays blogs eligible for updating 322 | * based on the authenticated user (handled 323 | * by our authentication Filter). 324 | */ 325 | public function manage(): string 326 | { 327 | // Admin access sees all blogs, otherwise limit to the current user 328 | if (! $this->model->mayAdmin()) { 329 | $this->model->where('user_id', user_id()); 330 | } 331 | 332 | return view('blogs/manage', [ 333 | 'blogs' => $this->model->findAll(), 334 | ]); 335 | } 336 | 337 | /** 338 | * Shows a single blog with options 339 | * to update or delete. 340 | * 341 | * @return RedirectResponse|string 342 | */ 343 | public function edit($blogId) 344 | { 345 | // Verify the blog 346 | if (empty($blogId) || null === $blog = $this->model->find($blogId)) { 347 | return redirect()->back()->with('error', 'Could not find that blog entry.'); 348 | } 349 | 350 | // Check access 351 | if (! $this->model->mayUpdate($blog)) { 352 | return redirect()->back()->with('error', 'You do not have permission to do that.'); 353 | } 354 | 355 | return view('blogs/edit', [ 356 | 'blog' => $blog, 357 | ]); 358 | } 359 | ... 360 | ``` 361 | 362 | Hopefully you get the idea from here! For developers who like to keep their controllers 363 | even more lightweight you could even put some of these checks into a Filter. 364 | 365 | ## Extending 366 | 367 | The CRUDL-style methods are just a starting point! Your models can override these built-in 368 | methods or add new methods that take advantage of the library's structure and methods. 369 | Check out the code in the source repo for ideas how to leverage both explicit and inferred 370 | permissions. 371 | --------------------------------------------------------------------------------