Completed
Push — master ( 56e25c...088dd2 )
by Oleg
19:18
created

UpdatePasswordAction::updatePassword()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 19
cts 19
cp 1
rs 9.392
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 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\Common\Collections\Selectable;
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\Doctrine\Persistence\EntityManagerRegistry;
18
use SlayerBirden\DataFlowServer\Domain\Entities\ClaimedResourceInterface;
19
use SlayerBirden\DataFlowServer\Stdlib\Request\Parser;
20
use SlayerBirden\DataFlowServer\Stdlib\Validation\GeneralErrorResponseFactory;
21
use SlayerBirden\DataFlowServer\Stdlib\Validation\GeneralSuccessResponseFactory;
22
use SlayerBirden\DataFlowServer\Stdlib\Validation\ValidationResponseFactory;
23
use Zend\Hydrator\HydratorInterface;
24
use Zend\InputFilter\InputFilterInterface;
25
26
final class UpdatePasswordAction implements MiddlewareInterface
27
{
28
    /**
29
     * @var LoggerInterface
30
     */
31
    private $logger;
32
    /**
33
     * @var PasswordManagerInterface
34
     */
35
    private $passwordManager;
36
    /**
37
     * @var InputFilterInterface
38
     */
39
    private $inputFilter;
40
    /**
41
     * @var HydratorInterface
42
     */
43
    private $hydrator;
44
    /**
45
     * @var EntityManagerRegistry
46
     */
47
    private $managerRegistry;
48
    /**
49
     * @var Selectable
50
     */
51
    private $passwordRepository;
52
53 6
    public function __construct(
54
        EntityManagerRegistry $managerRegistry,
55
        Selectable $passwordRepository,
56
        InputFilterInterface $inputFilter,
57
        LoggerInterface $logger,
58
        PasswordManagerInterface $passwordManager,
59
        HydratorInterface $hydrator
60
    ) {
61 6
        $this->managerRegistry = $managerRegistry;
62 6
        $this->passwordRepository = $passwordRepository;
63 6
        $this->logger = $logger;
64 6
        $this->passwordManager = $passwordManager;
65 6
        $this->inputFilter = $inputFilter;
66 6
        $this->hydrator = $hydrator;
67 6
    }
68
69
    /**
70
     * @inheritdoc
71
     * @throws ORMException
72
     * @throws \Exception
73
     */
74 6
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
75
    {
76 6
        $data = Parser::getRequestBody($request);
77 6
        $this->inputFilter->setData($data);
78
79 6
        if (!$this->inputFilter->isValid()) {
80 2
            return (new ValidationResponseFactory())('password', $this->inputFilter);
81
        }
82 4
        $em = $this->managerRegistry->getManagerForClass(Password::class);
83 4
        $em->beginTransaction();
84
        try {
85 4
            $pw = $this->updatePassword($data);
86 2
            $em->flush();
87 2
            $em->commit();
88
89 2
            $msg = 'Password successfully updated.';
90 2
            return (new GeneralSuccessResponseFactory())($msg, 'password', $this->hydrator->extract($pw));
91 2
        } catch (PasswordRestrictionsException | \InvalidArgumentException $exception) {
92 2
            $em->rollback();
93 2
            return (new GeneralErrorResponseFactory())($exception->getMessage(), 'password', 400);
94
        } catch (ORMException $exception) {
95
            $this->logger->error((string)$exception);
96
            $em->rollback();
97
            return (new GeneralErrorResponseFactory())('There was an error while updating password.', 'password', 400);
98
        }
99
    }
100
101
    /**
102
     * @param array $data
103
     * @return Password
104
     * @throws PasswordRestrictionsException
105
     * @throws \Exception
106
     */
107 4
    private function updatePassword(array $data): Password
108
    {
109 4
        $userPasswords = $this->passwordRepository->matching(
110 4
            Criteria::create()->where(
111 4
                Criteria::expr()->eq('owner', $data[ClaimedResourceInterface::OWNER_PARAM])
112
            )
113
        );
114
        # check if mentioned
115 4
        $em = $this->managerRegistry->getManagerForClass(Password::class);
116
        /** @var Password $item */
117 4
        foreach ($userPasswords as $item) {
118 4
            if (password_verify($data['new_password'], $item->getHash())) {
119 2
                throw new PasswordRestrictionsException(
120 2
                    'You have already used this password before. Please use a new one.'
121
                );
122
            }
123 4
            if ($item->isActive()) {
124 4
                $item->setActive(false);
125 4
                $em->persist($item);
126
            }
127
        }
128
129
        /** @var Password $password */
130 2
        $data['password'] = $data['new_password'];
131 2
        $data['created_at'] = (new \DateTime())->format(\DateTime::RFC3339);
132 2
        $data['due'] = (new \DateTime())->add(new \DateInterval('P1Y'))->format(\DateTime::RFC3339);
133 2
        $data['active'] = $data['active'] ?? true;
134
135 2
        $password = $this->hydrator->hydrate($data, new Password());
136 2
        $em->persist($password);
137
138 2
        return $password;
139
    }
140
}
141