Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions CHANGELOG-7.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<?php
// 6.x
$usersRepository = new UsersRepository($executor, UserModel::class);
$service = new UsersService($usersRepository, $propertiesRepository, LoginField::Username, $passwordDefinition);

// 7.0
$usersRepository = new UsersRepository($executor, UserModel::class, $passwordDefinition);
$service = new UsersService($usersRepository, $propertiesRepository, LoginField::Username);
```

A definition still passed to `UsersService` is silently ignored by PHP (an extra argument), so the
rules would not apply: move it. The repository sets the new `PasswordDefinitionValidator` (a MicroORM
`EntityValidatorInterface`) on its MicroORM `Repository`, so every save checks a plain password,
also of a model created with `new` and saved without the service (see Bug Fixes). The service takes
the definition from `UsersRepository::getPasswordDefinition()` for the users it creates or loads.
With byjg/config, an injected `UsersRepository` binding receives a bound `PasswordDefinition` by type.

### Dependencies

| Package | 6.x | 7.0 |
Expand Down Expand Up @@ -99,11 +121,10 @@ Not a plain change of casing: `UserField::uUpdated_at` is now `UserField::Update
## Bug Fixes

- A model created with `new UserModel(...)` was saved without checking its password against the
service's `PasswordDefinition` (only users created or loaded by `UsersService` had it). The service
now sets the new `PasswordDefinitionValidator` (a MicroORM `EntityValidatorInterface`) on the users
repository, so every save, also through `UsersRepository` or MicroORM's `Repository`, checks a plain
password and throws `InvalidArgumentException` outside the rules; a stored hash is not checked.
A validator declared on the user model's `TableAttribute` still runs.
`PasswordDefinition` (only users created or loaded by `UsersService` had it). The users repository
now checks it on every save, also through `UsersRepository` or MicroORM's `Repository` without the
service: a plain password outside the rules throws `InvalidArgumentException`; a stored hash is
not checked. A validator declared on the user model's `TableAttribute` still runs.

- `UserPropertiesRepository` converted the user id for its queries without the database at
hand (`getUpdateFunctionValue($userid, null)`), so a UUID user id was always written as
Expand Down
17 changes: 12 additions & 5 deletions docs/password-validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,33 @@ $userModel->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
<?php
use ByJG\Authenticate\Definition\PasswordDefinition;
use ByJG\Authenticate\Enum\LoginField;
use ByJG\Authenticate\Model\UserModel;
use ByJG\Authenticate\Repository\UsersRepository;
use ByJG\Authenticate\Service\UsersService;

$passwordDefinition = new PasswordDefinition([
PasswordDefinition::MINIMUM_CHARS => 12,
PasswordDefinition::REQUIRE_NUMBERS => 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!');
Expand All @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/user-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<?php
Expand Down
38 changes: 37 additions & 1 deletion src/Repository/UsersRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,18 @@
use ByJG\AnyDataset\Core\Exception\DatabaseException;
use ByJG\AnyDataset\Db\DatabaseExecutor;
use ByJG\AnyDataset\Db\Exception\DbDriverNotConnected;
use ByJG\Authenticate\Definition\PasswordDefinition;
use ByJG\Authenticate\Enum\UserField;
use ByJG\Authenticate\Interfaces\PasswordMapperInterface;
use ByJG\Authenticate\Model\UserModel;
use ByJG\Authenticate\Validator\PasswordDefinitionValidator;
use ByJG\MicroOrm\Exception\InvalidArgumentException;
use ByJG\MicroOrm\Exception\OrmBeforeInvalidException;
use ByJG\MicroOrm\Exception\OrmInvalidFieldsException;
use ByJG\MicroOrm\Exception\OrmModelInvalidException;
use ByJG\MicroOrm\Exception\RepositoryReadOnlyException;
use ByJG\MicroOrm\Exception\UpdateConstraintException;
use ByJG\MicroOrm\Interface\EntityValidatorInterface;
use ByJG\MicroOrm\Literal\Literal;
use ByJG\MicroOrm\Mapper;
use ByJG\MicroOrm\Query;
Expand All @@ -28,17 +33,48 @@ class UsersRepository
protected Repository $repository;
protected Mapper $mapper;

protected ?PasswordDefinition $passwordDefinition;

/**
* @param DatabaseExecutor $executor
* @param string $usersClass
* @param PasswordDefinition|null $passwordDefinition The password rules every save checks
* @throws OrmModelInvalidException
* @throws ReflectionException
* @throws InvalidArgumentException
*/
public function __construct(DatabaseExecutor $executor, string $usersClass)
public function __construct(DatabaseExecutor $executor, string $usersClass, ?PasswordDefinition $passwordDefinition = null)
{
$this->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;
}

/**
Expand Down
35 changes: 6 additions & 29 deletions src/Service/UsersService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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();
Expand All @@ -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) &&
Expand Down Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Validator/PasswordDefinitionValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
15 changes: 8 additions & 7 deletions tests/PasswordUpgradeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
);
}

Expand Down Expand Up @@ -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));
}

/**
Expand Down
14 changes: 9 additions & 5 deletions tests/TestUsersBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading