Completed
Push — master ( 178a08...5c0b6f )
by Oleg
05:22
created

UpdatePasswordAction   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 129
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 87.27%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 13
dl 0
loc 129
ccs 48
cts 55
cp 0.8727
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
A process() 0 45 4
A updatePassword() 0 35 4
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Authentication\Controller;
5
6
use Doctrine\Common\Collections\Criteria;
7
use Doctrine\ORM\EntityManager;
8
use Doctrine\ORM\ORMException;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
use Psr\Log\LoggerInterface;
14
use SlayerBirden\DataFlowServer\Authentication\Entities\Password;
15
use SlayerBirden\DataFlowServer\Authentication\Exception\PasswordRestrictionsException;
16
use SlayerBirden\DataFlowServer\Authentication\PasswordManagerInterface;
17
use SlayerBirden\DataFlowServer\Domain\Entities\ClaimedResourceInterface;
18
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
19
use SlayerBirden\DataFlowServer\Notification\SuccessMessage;
20
use SlayerBirden\DataFlowServer\Stdlib\Validation\ValidationResponseFactory;
21
use Zend\Diactoros\Response\JsonResponse;
22
use Zend\Hydrator\HydratorInterface;
23
use Zend\InputFilter\InputFilterInterface;
24
25
class UpdatePasswordAction implements MiddlewareInterface
26
{
27
    /**
28
     * @var EntityManager
29
     */
30
    private $entityManager;
31
    /**
32
     * @var LoggerInterface
33
     */
34
    private $logger;
35
    /**
36
     * @var PasswordManagerInterface
37
     */
38
    private $passwordManager;
39
    /**
40
     * @var InputFilterInterface
41
     */
42
    private $inputFilter;
43
    /**
44
     * @var HydratorInterface
45
     */
46
    private $hydrator;
47
48 3
    public function __construct(
49
        EntityManager $entityManager,
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
50
        InputFilterInterface $inputFilter,
51
        LoggerInterface $logger,
52
        PasswordManagerInterface $passwordManager,
53
        HydratorInterface $hydrator
54
    ) {
55 3
        $this->entityManager = $entityManager;
56 3
        $this->logger = $logger;
57 3
        $this->passwordManager = $passwordManager;
58 3
        $this->inputFilter = $inputFilter;
59 3
        $this->hydrator = $hydrator;
60 3
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
66
    {
67 3
        $data = $request->getParsedBody();
68 3
        $this->inputFilter->setData($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $request->getParsedBody() on line 67 can also be of type null or object; however, Zend\InputFilter\InputFilterInterface::setData() does only seem to accept array|object<Traversable>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
69
70 3
        if (!$this->inputFilter->isValid()) {
71 1
            return (new ValidationResponseFactory())('password', $this->inputFilter);
72
        }
73 2
        $this->entityManager->beginTransaction();
74
        try {
75 2
            $pw = $this->updatePassword($data);
0 ignored issues
show
Bug introduced by
It seems like $data defined by $request->getParsedBody() on line 67 can also be of type null or object; however, SlayerBirden\DataFlowSer...ction::updatePassword() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
76 1
            $this->entityManager->flush();
77 1
            $this->entityManager->commit();
78
79 1
            return new JsonResponse([
80 1
                'data' => [
81 1
                    'password' => $this->hydrator->extract($pw),
82
                    'validation' => [],
83
                ],
84
                'success' => true,
85 1
                'msg' => new SuccessMessage('Password successfully updated.'),
86 1
            ], 200);
87 1
        } catch (PasswordRestrictionsException | \InvalidArgumentException $exception) {
88 1
            $this->entityManager->rollback();
89 1
            return new JsonResponse([
90 1
                'data' => [
91
                    'password' => null,
92
                    'validation' => [],
93
                ],
94
                'success' => false,
95 1
                'msg' => new DangerMessage($exception->getMessage()),
96 1
            ], 400);
97
        } catch (\Throwable $exception) {
98
            $this->logger->error((string)$exception);
99
            $this->entityManager->rollback();
100
            return new JsonResponse([
101
                'data' => [
102
                    'password' => null,
103
                    'validation' => [],
104
                ],
105
                'success' => false,
106
                'msg' => new DangerMessage('There was an error while updating password.'),
107
            ], 500);
108
        }
109
    }
110
111
    /**
112
     * @param array $data
113
     * @return Password
114
     * @throws PasswordRestrictionsException
115
     * @throws ORMException
116
     * @throws \Exception
117
     */
118 2
    private function updatePassword(array $data): Password
119
    {
120 2
        $userPasswords = $this->entityManager
121 2
            ->getRepository(Password::class)
122 2
            ->matching(
123 2
                Criteria::create()->where(
124 2
                    Criteria::expr()->eq('owner', $data[ClaimedResourceInterface::OWNER_PARAM])
125
                )
126
            );
127
        # check if mentioned
128
        /** @var Password $item */
129 2
        foreach ($userPasswords as $item) {
130 2
            if (password_verify($data['new_password'], $item->getHash())) {
131 1
                throw new PasswordRestrictionsException(
132 1
                    'You have already used this password before. Please use a new one.'
133
                );
134
            }
135 2
            if ($item->isActive()) {
136 2
                $item->setActive(false);
137 2
                $this->entityManager->persist($item);
138
            }
139
        }
140
141
        /** @var Password $password */
142 1
        $data['password'] = $data['new_password'];
143 1
        unset($data['new_password']);
144 1
        $data['created_at'] = (new \DateTime())->format(\DateTime::RFC3339);
145 1
        $data['due'] = (new \DateTime())->add(new \DateInterval('P1Y'))->format(\DateTime::RFC3339);
146 1
        $data['active'] = $data['active'] ?? true;
147
148 1
        $password = $this->hydrator->hydrate($data, new Password());
149 1
        $this->entityManager->persist($password);
150
151 1
        return $password;
152
    }
153
}
154