File size: 2,051 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php

declare(strict_types=1);

namespace Mautic\UserBundle\Tests\Model;

use Mautic\CoreBundle\Test\MauticMysqlTestCase;
use Mautic\UserBundle\Entity\Role;
use Mautic\UserBundle\Entity\RoleRepository;
use Mautic\UserBundle\Entity\User;
use Mautic\UserBundle\Form\Validator\Constraints\NotWeak;
use PHPUnit\Framework\Assert;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Validator\ValidatorInterface;

final class PasswordStrengthEstimatorModelTest extends MauticMysqlTestCase
{
    private EncoderFactory $passwordEncoder;

    private RoleRepository $roleRepository;

    private ValidatorInterface $validator;

    protected function setUp(): void
    {
        parent::setUp();
        $this->passwordEncoder = static::getContainer()->get('security.encoder_factory');
        $this->roleRepository  = $this->em->getRepository(Role::class);
        $this->validator       = static::getContainer()->get('validator');
    }

    public function testThatItIsNotPossibleToCreateAnUserWithAWeakPassword(): void
    {
        $simplePassword = '11111111';

        $user = new User();
        $user->setFirstName('First Name');
        $user->setLastName('LastName');
        $user->setUsername('username');
        $user->setEmail('[email protected]');
        $user->setPlainPassword($simplePassword);
        $user->setPassword($this->passwordEncoder->getEncoder($user)->encodePassword($simplePassword, $user->getSalt()));
        $user->setRole($this->roleRepository->findAll()[0]);
        $violations                    = $this->validator->validate($user);
        $hasNotWeakConstraintViolation = false;

        /** @var ConstraintViolation $violation */
        foreach ($violations as $violation) {
            $hasNotWeakConstraintViolation |= $violation->getConstraint() instanceof NotWeak;
        }

        Assert::assertGreaterThanOrEqual(1, count($violations));
        Assert::assertTrue((bool) $hasNotWeakConstraintViolation);
    }
}