From 641c57387d85683c5c807a0878a7759402dda69d Mon Sep 17 00:00:00 2001 From: kenjis Date: Tue, 20 Aug 2024 14:58:46 +0900 Subject: [PATCH] feat: check invalid group name --- src/Commands/User.php | 14 ++++++++++++++ tests/Commands/UserTest.php | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/Commands/User.php b/src/Commands/User.php index 9c1a91019..c0977cdf5 100644 --- a/src/Commands/User.php +++ b/src/Commands/User.php @@ -19,6 +19,7 @@ use CodeIgniter\Shield\Config\Auth; use CodeIgniter\Shield\Entities\User as UserEntity; use CodeIgniter\Shield\Exceptions\UserNotFoundException; +use CodeIgniter\Shield\Models\GroupModel; use CodeIgniter\Shield\Models\UserModel; use CodeIgniter\Shield\Validation\ValidationRules; use Config\Services; @@ -305,6 +306,11 @@ private function create(?string $username = null, ?string $email = null, ?string $user = new UserEntity($data); + // Validate the group + if ($group !== null && ! $this->validateGroup($group)) { + throw new CancelException('Invalid group: "' . $group . '"'); + } + if ($username === null) { $userModel->allowEmptyInserts()->save($user); $this->write('New User created', 'green'); @@ -327,6 +333,14 @@ private function create(?string $username = null, ?string $email = null, ?string } } + private function validateGroup(string $group): bool + { + /** @var GroupModel $groupModel */ + $groupModel = model(GroupModel::class); + + return $groupModel->isValidGroup($group); + } + /** * Activate an existing user by username or email * diff --git a/tests/Commands/UserTest.php b/tests/Commands/UserTest.php index 9fdf3e148..b28cd0ae6 100644 --- a/tests/Commands/UserTest.php +++ b/tests/Commands/UserTest.php @@ -134,6 +134,25 @@ public function testCreateWithGroupBeta(): void ]); } + public function testCreateWithInvalidGroup(): void + { + $this->setMockIo([ + 'Secret Passw0rd!', + 'Secret Passw0rd!', + ]); + + command('shield:user create -n user1 -e user1@example.com -g invalid'); + + $this->assertStringContainsString( + 'Invalid group: "invalid"', + $this->io->getFirstOutput() + ); + + $users = model(UserModel::class); + $user = $users->findByCredentials(['email' => 'user1@example.com']); + $this->assertNull($user); + } + public function testCreateNotUniqueName(): void { $user = $this->createUser([