Skip to content

Commit 4cd20fe

Browse files
committed
[Security] Added error code to UserPassword constraint
1 parent 9d85576 commit 4cd20fe

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

Tests/Validator/Constraints/UserPasswordValidatorTestCase.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ public function testPasswordIsNotValid(UserPassword $constraint)
8787
$this->validator->validate('secret', $constraint);
8888

8989
$this->buildViolation('myMessage')
90+
->setCode(UserPassword::INVALID_PASSWORD_ERROR)
9091
->assertRaised();
9192
}
9293

@@ -109,6 +110,7 @@ public function testEmptyPasswordsAreNotValid($password)
109110
$this->validator->validate($password, $constraint);
110111

111112
$this->buildViolation('myMessage')
113+
->setCode(UserPassword::INVALID_PASSWORD_ERROR)
112114
->assertRaised();
113115
}
114116

Validator/Constraints/UserPassword.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@
2020
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
2121
class UserPassword extends Constraint
2222
{
23+
public const INVALID_PASSWORD_ERROR = '2d2a8bb4-ddc8-45e4-9b0f-8670d3a3e290';
24+
25+
protected const ERROR_NAMES = [
26+
self::INVALID_PASSWORD_ERROR => 'INVALID_PASSWORD_ERROR',
27+
];
28+
2329
public $message = 'This value should be the user\'s current password.';
2430
public $service = 'security.validator.user_password';
2531

Validator/Constraints/UserPasswordValidator.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ public function validate(mixed $password, Constraint $constraint)
4141
}
4242

4343
if (null === $password || '' === $password) {
44-
$this->context->addViolation($constraint->message);
44+
$this->context->buildViolation($constraint->message)
45+
->setCode(UserPassword::INVALID_PASSWORD_ERROR)
46+
->addViolation();
4547

4648
return;
4749
}
@@ -59,7 +61,9 @@ public function validate(mixed $password, Constraint $constraint)
5961
$hasher = $this->hasherFactory->getPasswordHasher($user);
6062

6163
if (null === $user->getPassword() || !$hasher->verify($user->getPassword(), $password, $user instanceof LegacyPasswordAuthenticatedUserInterface ? $user->getSalt() : null)) {
62-
$this->context->addViolation($constraint->message);
64+
$this->context->buildViolation($constraint->message)
65+
->setCode(UserPassword::INVALID_PASSWORD_ERROR)
66+
->addViolation();
6367
}
6468
}
6569
}

0 commit comments

Comments
 (0)