Skip to content

Commit fc01d3a

Browse files
authored
Merge pull request #510 from kenjis/fix-permission-type-error
fix: TypeError when checking invalid permission
2 parents d939e10 + 23270b3 commit fc01d3a

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/Authorization/Traits/Authorizable.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use CodeIgniter\I18n\Time;
88
use CodeIgniter\Shield\Authorization\AuthorizationException;
9+
use CodeIgniter\Shield\Exceptions\LogicException;
910
use CodeIgniter\Shield\Models\GroupModel;
1011
use CodeIgniter\Shield\Models\PermissionModel;
1112

@@ -226,9 +227,18 @@ public function hasPermission(string $permission): bool
226227
/**
227228
* Checks user permissions and their group permissions
228229
* to see if the user has a specific permission.
230+
*
231+
* @param string $permission string consisting of a scope and action, like `users.create`
229232
*/
230233
public function can(string $permission): bool
231234
{
235+
if (strpos($permission, '.') === false) {
236+
throw new LogicException(
237+
'A permission must be a string consisting of a scope and action, like `users.create`.'
238+
. ' Invalid permission: ' . $permission
239+
);
240+
}
241+
232242
$this->populatePermissions();
233243

234244
$permission = strtolower($permission);

tests/Authorization/AuthorizableTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use CodeIgniter\I18n\Time;
88
use CodeIgniter\Shield\Authorization\AuthorizationException;
9+
use CodeIgniter\Shield\Exceptions\LogicException;
910
use CodeIgniter\Shield\Models\UserModel;
1011
use CodeIgniter\Test\DatabaseTestTrait;
1112
use Locale;
@@ -299,6 +300,16 @@ public function testCanCascadesToGroupsWithWildcards(): void
299300
$this->assertTrue($this->user->can('admin.access'));
300301
}
301302

303+
public function testCanGetsInvalidPermission(): void
304+
{
305+
$this->expectException(LogicException::class);
306+
$this->expectExceptionMessage('Invalid permission: developer');
307+
308+
$this->user->addGroup('superadmin');
309+
310+
$this->assertTrue($this->user->can('developer'));
311+
}
312+
302313
/**
303314
* @see https://github.com/codeigniter4/shield/pull/238
304315
*/

0 commit comments

Comments
 (0)