diff --git a/CHANGELOG-7.0.md b/CHANGELOG-7.0.md index 6f13f77..892a749 100644 --- a/CHANGELOG-7.0.md +++ b/CHANGELOG-7.0.md @@ -38,6 +38,28 @@ to fix the user id conversion in `UserPropertiesRepository` (see Bug Fixes). - `UserModel::setPassword()` asks the password mapper whether a value is already a hash (it skipped the password definition for any 40-character value). +### The password definition belongs to UsersRepository + +`UsersService` no longer takes a `PasswordDefinition`; pass it to `UsersRepository`: + +```php +withPasswordDefinition($passwordDefinition); $userModel->setPassword('WeakPwd'); // Throws InvalidArgumentException ``` -### Applying Rules Through UsersService +### Applying Rules Through UsersRepository -Instead of attaching the definition to every `UserModel` manually, pass it to the `UsersService` constructor. Every entity created or loaded through the service (e.g., via `addUser()`, `getUsersEntity()` or `getById()`) receives the same `PasswordDefinition`, and the service sets a `PasswordDefinitionValidator` on the users repository: every save, also of a model created with `new` and saved through `UsersRepository` or MicroORM's `Repository` directly, checks a plain password against the definition and throws `InvalidArgumentException` when it does not match. A stored hash is never checked. A validator the user model declares (`#[TableAttribute(validator: ...)]`) still runs after it; one set later with `setValidator()` replaces it. +Instead of attaching the definition to every `UserModel` manually, pass it to the `UsersRepository` constructor. The repository is where every user is written, so it owns the rules: + +- It sets a `PasswordDefinitionValidator` on its MicroORM `Repository`. Every save, through `UsersService`, `UsersRepository` or the MicroORM `Repository` directly, also of a model created with `new`, checks a plain password against the definition and throws `InvalidArgumentException` when it does not match. A stored hash is never checked. +- A validator the user model declares (`#[TableAttribute(validator: ...)]`) still runs after it; one set later with `setValidator()` replaces it. +- `UsersService` takes the definition from the repository (`getPasswordDefinition()`) and gives it to every entity it creates or loads (`addUser()`, `getUsersEntity()`, `getById()`, ...), so `setPassword()` rejects a weak password right away, before the save. ```php 2, ]); +$usersRepo = new UsersRepository($executor, UserModel::class, $passwordDefinition); + $users = new UsersService( $usersRepo, $propsRepo, - LoginField::Username, - $passwordDefinition + LoginField::Username ); $newUser = $users->addUser('Jane', 'jane', 'jane@example.com', 'StrongPassword123!'); @@ -64,7 +71,7 @@ $user->setPassword('AnotherStrongPass123!'); $users->save($user); ``` -This approach guarantees that every model created or retrieved through the service (`getById()`, `getByEmail()`, `getUsersByProperty()`, etc.) automatically enforces your password policy. +This approach guarantees that every model created or retrieved through the service (`getById()`, `getByEmail()`, `getUsersByProperty()`, etc.) enforces your password policy when its password is set, and the repository enforces it again on every save. ## Password Rules diff --git a/docs/user-management.md b/docs/user-management.md index 938d311..88d4013 100644 --- a/docs/user-management.md +++ b/docs/user-management.md @@ -41,7 +41,7 @@ $savedUser = $users->save($userModel); ### Creating Entities via UsersService -When you need a new `UserModel` that already respects the mapper configuration (including any `PasswordDefinition` passed to the `UsersService` constructor), call `getUsersEntity()`: +When you need a new `UserModel` that already respects the mapper configuration (including the `PasswordDefinition` passed to the `UsersRepository` constructor), call `getUsersEntity()`: ```php mapper = new Mapper($usersClass); $this->repository = new Repository($executor, $usersClass); + $this->passwordDefinition = $passwordDefinition; + + if ($passwordDefinition !== null) { + // The definition tells a stored hash from a plain password with the model's mapper + $passwordMapper = $this->mapper->getFieldMap(UserField::Password->value)?->getUpdateFunction(); + if ($passwordMapper === null || !is_subclass_of($passwordMapper, PasswordMapperInterface::class, true)) { + throw new \InvalidArgumentException('Password update function must implement PasswordMapperInterface'); + } + /** @var PasswordMapperInterface|string $passwordMapper */ + $passwordDefinition->setPasswordMapper($passwordMapper); + + // Every save checks a plain password against the definition; the validator the + // model declares still runs + $modelValidator = $this->repository->getMapper()->getValidator(); + if (is_string($modelValidator)) { + $modelValidator = new $modelValidator(); + } + /** @var EntityValidatorInterface|null $modelValidator The repository checked it */ + $this->repository->setValidator(new PasswordDefinitionValidator($passwordDefinition, $modelValidator)); + } + } + + /** + * The password rules every save checks, if any + */ + public function getPasswordDefinition(): ?PasswordDefinition + { + return $this->passwordDefinition; } /** diff --git a/src/Service/UsersService.php b/src/Service/UsersService.php index 79cf0f3..9be35ff 100644 --- a/src/Service/UsersService.php +++ b/src/Service/UsersService.php @@ -2,7 +2,6 @@ namespace ByJG\Authenticate\Service; -use ByJG\Authenticate\Definition\PasswordDefinition; use ByJG\Authenticate\Enum\LoginField; use ByJG\Authenticate\Enum\UserField; use ByJG\Authenticate\Enum\UserPropertyField; @@ -16,10 +15,8 @@ use ByJG\Authenticate\Model\UserToken; use ByJG\Authenticate\Repository\UserPropertiesRepository; use ByJG\Authenticate\Repository\UsersRepository; -use ByJG\Authenticate\Validator\PasswordDefinitionValidator; use ByJG\JwtWrapper\JwtWrapper; use ByJG\JwtWrapper\JwtWrapperException; -use ByJG\MicroOrm\Interface\EntityValidatorInterface; use ByJG\MicroOrm\Literal\Literal; use ByJG\MicroOrm\Query; use Exception; @@ -34,19 +31,16 @@ class UsersService implements UsersServiceInterface { protected UsersRepository $usersRepository; protected UserPropertiesRepository $propertiesRepository; - protected ?PasswordDefinition $passwordDefinition; protected LoginField $loginField; public function __construct( UsersRepository $usersRepository, UserPropertiesRepository $propertiesRepository, - LoginField $loginField = LoginField::Username, - ?PasswordDefinition $passwordDefinition = null + LoginField $loginField = LoginField::Username ) { $this->usersRepository = $usersRepository; $this->propertiesRepository = $propertiesRepository; - $this->passwordDefinition = $passwordDefinition; $this->loginField = $loginField; $userMapper = $usersRepository->getRepository()->getMapper(); @@ -68,22 +62,6 @@ public function __construct( throw new InvalidArgumentException('Password update function must implement PasswordMapperInterface'); } - // Type assertion for Psalm - we've verified it's a PasswordMapperInterface or string - /** @var PasswordMapperInterface|string $passwordUpdateFunction */ - $this->passwordDefinition?->setPasswordMapper($passwordUpdateFunction); - - // Every save of the users repository checks a plain password against the definition, - // also a user created with new and saved without this service - if ($this->passwordDefinition !== null) { - $repository = $usersRepository->getRepository(); - $modelValidator = $repository->getMapper()->getValidator(); - if (is_string($modelValidator)) { - $modelValidator = new $modelValidator(); - } - /** @var EntityValidatorInterface|null $modelValidator The repository checked it */ - $repository->setValidator(new PasswordDefinitionValidator($this->passwordDefinition, $modelValidator)); - } - $propertyMapper = $propertiesRepository->getRepository()->getMapper(); $propertyCheck = ($propertyMapper->getFieldMap(UserPropertyField::Userid->value) !== null) && ($propertyMapper->getFieldMap(UserPropertyField::Name->value) !== null) && @@ -301,8 +279,9 @@ protected function loadUserProperties(UserModel $user): void protected function applyPasswordDefinition(UserModel $user): void { - if ($this->passwordDefinition !== null) { - $user->withPasswordDefinition($this->passwordDefinition); + $passwordDefinition = $this->usersRepository->getPasswordDefinition(); + if ($passwordDefinition !== null) { + $user->withPasswordDefinition($passwordDefinition); } } @@ -614,10 +593,8 @@ public function getUsersByPropertySet(array $propertiesArray): array } $users = $this->usersRepository->getRepository()->getByQuery($query); - if ($this->passwordDefinition !== null) { - foreach ($users as $user) { - $this->applyPasswordDefinition($user); - } + foreach ($users as $user) { + $this->applyPasswordDefinition($user); } return $users; } diff --git a/src/Validator/PasswordDefinitionValidator.php b/src/Validator/PasswordDefinitionValidator.php index ce9e589..3a92651 100644 --- a/src/Validator/PasswordDefinitionValidator.php +++ b/src/Validator/PasswordDefinitionValidator.php @@ -9,7 +9,7 @@ /** * Checks the password of a user against the password definition on every save of the users * repository: a plain password outside the rules throws InvalidArgumentException, a stored - * hash is not checked. UsersService sets it when it is given a PasswordDefinition. + * hash is not checked. UsersRepository sets it when it is given a PasswordDefinition. */ class PasswordDefinitionValidator implements EntityValidatorInterface { diff --git a/tests/PasswordUpgradeTest.php b/tests/PasswordUpgradeTest.php index 8d25e34..7bf6454 100644 --- a/tests/PasswordUpgradeTest.php +++ b/tests/PasswordUpgradeTest.php @@ -19,7 +19,7 @@ use Tests\Fixture\UserModelWithValidator; /** - * A UsersService with the default password definition, over a database created with SHA-1 + * A users repository with the default password definition, over a database created with SHA-1 * passwords, read by UserModel's default mapper (bcrypt) */ class PasswordUpgradeTest extends TestCase @@ -63,10 +63,9 @@ private function createDatabase(string $passwordColumn = 'password varchar(255)' ); $this->service = new UsersService( - new UsersRepository($this->executor, $userClass), + new UsersRepository($this->executor, $userClass, new PasswordDefinition()), new UserPropertiesRepository($this->executor, UserPropertiesModel::class), - LoginField::Username, - new PasswordDefinition() + LoginField::Username ); } @@ -199,15 +198,17 @@ public function testServiceSaveChecksTheDefinition(): void } /** - * Saved without the service, through the users repository or MicroORM's: still checked + * A users repository with a definition and no UsersService: its save, and the save of its + * MicroORM repository, still check the password */ public function testRepositorySaveChecksTheDefinition(): void { $this->createDatabase(); + $repository = new UsersRepository($this->executor, UserModel::class, new PasswordDefinition()); - $this->assertSaveChecksTheDefinition(fn(UserModel $user) => $this->service->getUsersRepository()->save($user)); + $this->assertSaveChecksTheDefinition(fn(UserModel $user) => $repository->save($user)); $this->executor->execute("delete from users where username = 'new'"); - $this->assertSaveChecksTheDefinition(fn(UserModel $user) => $this->service->getUsersRepository()->getRepository()->save($user)); + $this->assertSaveChecksTheDefinition(fn(UserModel $user) => $repository->getRepository()->save($user)); } /** diff --git a/tests/TestUsersBase.php b/tests/TestUsersBase.php index d0c4d54..fe72779 100644 --- a/tests/TestUsersBase.php +++ b/tests/TestUsersBase.php @@ -667,16 +667,20 @@ public function testPasswordDefinitionViaServiceAddUser(): void \ByJG\Authenticate\Definition\PasswordDefinition::REQUIRE_SYMBOLS => 1, ]); - // Get the repositories from existing service - $usersRepo = $this->object->getUsersRepository(); + // A users repository with the password definition, over the same table + $repository = $this->object->getUsersRepository()->getRepository(); + $usersRepo = new \ByJG\Authenticate\Repository\UsersRepository( + $repository->getExecutor(), + $repository->getMapper()->getEntityClass(), + $passwordDef + ); $propsRepo = $this->object->getPropertiesRepository(); - // Create new service with password definition + // Create new service over it $usersWithPwdDef = new \ByJG\Authenticate\Service\UsersService( $usersRepo, $propsRepo, - LoginField::Username, - $passwordDef + LoginField::Username ); // Valid password should work