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
7 changes: 7 additions & 0 deletions CHANGELOG-7.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,13 @@ 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.

- `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
`X'…'`. With byjg/micro-orm 7.0, which writes a UUID in the syntax of each database, the
Expand Down
2 changes: 1 addition & 1 deletion docs/password-validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ $userModel->setPassword('WeakPwd'); // Throws InvalidArgumentException

### Applying Rules Through UsersService

Instead of attaching the definition to every `UserModel` manually, pass it to the `UsersService` constructor. Every entity created through the service (e.g., via `addUser()` or `getUsersEntity()`) receives the same `PasswordDefinition`.
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.

```php
<?php
Expand Down
59 changes: 37 additions & 22 deletions src/Service/UsersService.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@
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;
use InvalidArgumentException;
use Override;
use Throwable;

/**
Expand Down Expand Up @@ -69,6 +72,18 @@ public function __construct(
/** @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 @@ -116,7 +131,7 @@ public function getLoginValue(UserModel $user): ?string
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function save(UserModel $model): UserModel
{
$newUser = false;
Expand Down Expand Up @@ -152,7 +167,7 @@ public function save(UserModel $model): UserModel
* @param string|null $role
* @inheritDoc
*/
#[\Override]
#[Override]
public function addUser(string $name, string $userName, string $email, string $password, ?string $role = null): UserModel
{

Expand Down Expand Up @@ -208,7 +223,7 @@ protected function canAddUser(UserModel $model): bool
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function getById(string|Literal|int $userid): ?UserModel
{
$user = $this->usersRepository->getById($userid);
Expand All @@ -222,7 +237,7 @@ public function getById(string|Literal|int $userid): ?UserModel
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function getByEmail(string $email): ?UserModel
{
$fieldMap = $this->usersRepository->getMapper()->getFieldMap(UserField::Email->value);
Expand All @@ -240,7 +255,7 @@ public function getByEmail(string $email): ?UserModel
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function getByUsername(string $username): ?UserModel
{
$fieldMap = $this->usersRepository->getMapper()->getFieldMap(UserField::Username->value);
Expand All @@ -258,7 +273,7 @@ public function getByUsername(string $username): ?UserModel
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function getByLogin(string $login): ?UserModel
{
return match($this->loginField) {
Expand Down Expand Up @@ -307,7 +322,7 @@ protected function resolveUserFieldValue(UserModel $user, string $fieldName, ?st
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function removeByLogin(string $login): bool
{
$user = $this->getByLogin($login);
Expand All @@ -323,7 +338,7 @@ public function removeByLogin(string $login): bool
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function removeById(string|Literal|int $userid): bool
{
try {
Expand All @@ -340,7 +355,7 @@ public function removeById(string|Literal|int $userid): bool
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function isValidUser(string $login, string $password): ?UserModel
{
$user = $this->getByLogin($login);
Expand All @@ -360,7 +375,7 @@ public function isValidUser(string $login, string $password): ?UserModel
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function rehashPasswordIfNeeded(UserModel $user, string $password): bool
{
$mapper = $this->passwordMapper();
Expand Down Expand Up @@ -407,7 +422,7 @@ protected function passwordMapper(): PasswordMapperInterface
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function hasProperty(string|int|Literal $userId, string $propertyName, ?string $value = null): bool
{
$user = $this->getById($userId);
Expand All @@ -432,7 +447,7 @@ public function hasProperty(string|int|Literal $userId, string $propertyName, ?s
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function getProperty(string|Literal|int $userId, string $propertyName): array|string|UserPropertiesModel|null
{
$properties = $this->propertiesRepository->getByUserIdAndName($userId, $propertyName);
Expand All @@ -456,7 +471,7 @@ public function getProperty(string|Literal|int $userId, string $propertyName): a
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function addProperty(string|Literal|int $userId, string $propertyName, ?string $value): bool
{
$user = $this->getById($userId);
Expand Down Expand Up @@ -493,7 +508,7 @@ public function addProperty(string|Literal|int $userId, string $propertyName, ?s
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function setProperty(string|Literal|int $userId, string $propertyName, ?string $value): bool
{
$properties = $this->propertiesRepository->getByUserIdAndName($userId, $propertyName);
Expand Down Expand Up @@ -529,7 +544,7 @@ public function setProperty(string|Literal|int $userId, string $propertyName, ?s
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function removeProperty(string|Literal|int $userId, string $propertyName, ?string $value = null): bool
{
$user = $this->getById($userId);
Expand All @@ -543,7 +558,7 @@ public function removeProperty(string|Literal|int $userId, string $propertyName,
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function removeAllProperties(string $propertyName, ?string $value = null): void
{
$this->propertiesRepository->deleteByName($propertyName, $value);
Expand All @@ -552,7 +567,7 @@ public function removeAllProperties(string $propertyName, ?string $value = null)
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function getUsersByProperty(string $propertyName, string $value): array
{
return $this->getUsersByPropertySet([$propertyName => $value]);
Expand All @@ -561,7 +576,7 @@ public function getUsersByProperty(string $propertyName, string $value): array
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function getUsersByPropertySet(array $propertiesArray): array
{
$userTable = $this->usersRepository->getTableName();
Expand Down Expand Up @@ -607,7 +622,7 @@ public function getUsersByPropertySet(array $propertiesArray): array
return $users;
}

#[\Override]
#[Override]
public function createInsecureAuthToken(
string|UserModel $login,
JwtWrapper $jwtWrapper,
Expand Down Expand Up @@ -665,7 +680,7 @@ public function createInsecureAuthToken(
/**
* @inheritDoc
*/
#[\Override]
#[Override]
public function createAuthToken(
string $login,
string $password,
Expand Down Expand Up @@ -698,7 +713,7 @@ public function createAuthToken(
* @throws NotAuthenticatedException
* @throws UserNotFoundException
*/
#[\Override]
#[Override]
public function isValidToken(string $login, JwtWrapper $jwtWrapper, string $token): UserToken
{
$user = $this->getByLogin($login);
Expand All @@ -722,7 +737,7 @@ public function isValidToken(string $login, JwtWrapper $jwtWrapper, string $toke
);
}

#[\Override]
#[Override]
public function getUsersEntity(array $fields): UserModel
{
$entity = $this->getUsersRepository()->getMapper()->getEntity($fields);
Expand Down
36 changes: 36 additions & 0 deletions src/Validator/PasswordDefinitionValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace ByJG\Authenticate\Validator;

use ByJG\Authenticate\Definition\PasswordDefinition;
use ByJG\Authenticate\Model\UserModel;
use ByJG\MicroOrm\Interface\EntityValidatorInterface;

/**
* 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.
*/
class PasswordDefinitionValidator implements EntityValidatorInterface
{
/**
* @param PasswordDefinition $passwordDefinition
* @param EntityValidatorInterface|null $next The validator the model declares, still run
*/
public function __construct(
protected PasswordDefinition $passwordDefinition,
protected ?EntityValidatorInterface $next = null
) {
}

#[\Override]
public function validate(mixed $instance, bool $isInsert): void
{
if ($instance instanceof UserModel) {
// Sets the password again under the definition, which checks a plain password
$instance->withPasswordDefinition($this->passwordDefinition);
}

$this->next?->validate($instance, $isInsert);
}
}
21 changes: 21 additions & 0 deletions tests/Fixture/BlockedNameValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Tests\Fixture;

use ByJG\Authenticate\Model\UserModel;
use ByJG\MicroOrm\Interface\EntityValidatorInterface;
use RuntimeException;

/**
* A validator a project declares on its user model
*/
class BlockedNameValidator implements EntityValidatorInterface
{
#[\Override]
public function validate(mixed $instance, bool $isInsert): void
{
if ($instance instanceof UserModel && $instance->getName() === 'Blocked') {
throw new RuntimeException('Blocked name');
}
}
}
11 changes: 11 additions & 0 deletions tests/Fixture/UserModelWithValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Tests\Fixture;

use ByJG\Authenticate\Model\UserModel;
use ByJG\MicroOrm\Attributes\TableAttribute;

#[TableAttribute(tableName: 'users', validator: BlockedNameValidator::class)]
class UserModelWithValidator extends UserModel
{
}
Loading
Loading