Completed
Push — master ( 5c71f2...630401 )
by Oleg
07:36
created

UpdatePasswordAction::process()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 8.0756

Importance

Changes 0
Metric Value
dl 0
loc 35
ccs 18
cts 25
cp 0.72
rs 8.4266
c 0
b 0
f 0
cc 7
nc 13
nop 2
crap 8.0756
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\Common\Persistence\ManagerRegistry;
9
use Doctrine\ORM\EntityManagerInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Http\Message\ServerRequestInterface;
12
use Psr\Http\Server\MiddlewareInterface;
13
use Psr\Http\Server\RequestHandlerInterface;
14
use Psr\Log\LoggerInterface;
15
use SlayerBirden\DataFlowServer\Authentication\Entities\Password;
16
use SlayerBirden\DataFlowServer\Authentication\Exception\PasswordRestrictionsException;
17
use SlayerBirden\DataFlowServer\Authentication\PasswordManagerInterface;
18
use SlayerBirden\DataFlowServer\Domain\Entities\ClaimedResourceInterface;
19
use SlayerBirden\DataFlowServer\Stdlib\Validation\DataValidationResponseFactory;
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 ManagerRegistry
46
     */
47
    private $managerRegistry;
48
    /**
49
     * @var Selectable
50
     */
51
    private $passwordRepository;
52
53 3
    public function __construct(
54
        ManagerRegistry $managerRegistry,
55
        Selectable $passwordRepository,
56
        InputFilterInterface $inputFilter,
57
        LoggerInterface $logger,
58
        PasswordManagerInterface $passwordManager,
59
        HydratorInterface $hydrator
60
    ) {
61 3
        $this->managerRegistry = $managerRegistry;
62 3
        $this->passwordRepository = $passwordRepository;
63 3
        $this->logger = $logger;
64 3
        $this->passwordManager = $passwordManager;
65 3
        $this->inputFilter = $inputFilter;
66 3
        $this->hydrator = $hydrator;
67 3
    }
68
69
    /**
70
     * @inheritdoc
71
     */
72 3
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
73
    {
74 3
        $data = $request->getParsedBody();
75 3
        if (!is_array($data)) {
76
            return (new DataValidationResponseFactory())('password');
77
        }
78 3
        $this->inputFilter->setData($data);
79
80 3
        if (!$this->inputFilter->isValid()) {
81 1
            return (new ValidationResponseFactory())('password', $this->inputFilter);
82
        }
83 2
        $em = $this->managerRegistry->getManagerForClass(Password::class);
84 2
        if ($em === null) {
85
            return (new GeneralErrorResponseFactory())('Could not retrieve ObjectManager', 'password');
86
        }
87 2
        if (!($em instanceof EntityManagerInterface)) {
88
            return (new GeneralErrorResponseFactory())('Could not use current ObjectManager', 'password');
89
        }
90 2
        $em->beginTransaction();
91
        try {
92 2
            $pw = $this->updatePassword($data);
93 1
            $em->flush();
94 1
            $em->commit();
95
96 1
            $msg = 'Password successfully updated.';
97 1
            return (new GeneralSuccessResponseFactory())($msg, 'password', $this->hydrator->extract($pw));
98 1
        } catch (PasswordRestrictionsException | \InvalidArgumentException $exception) {
99 1
            $em->rollback();
100 1
            return (new GeneralErrorResponseFactory())($exception->getMessage(), 'password', 400);
101
        } catch (\Exception $exception) {
102
            $this->logger->error((string)$exception);
103
            $em->rollback();
104
            return (new GeneralErrorResponseFactory())('There was an error while updating password.', 'password', 400);
105
        }
106
    }
107
108
    /**
109
     * @param array $data
110
     * @return Password
111
     * @throws PasswordRestrictionsException
112
     * @throws \Exception
113
     */
114 2
    private function updatePassword(array $data): Password
115
    {
116 2
        $userPasswords = $this->passwordRepository->matching(
117 2
            Criteria::create()->where(
118 2
                Criteria::expr()->eq('owner', $data[ClaimedResourceInterface::OWNER_PARAM])
119
            )
120
        );
121
        # check if mentioned
122 2
        $em = $this->managerRegistry->getManagerForClass(Password::class);
123
        /** @var Password $item */
124 2
        foreach ($userPasswords as $item) {
125 2
            if (password_verify($data['new_password'], $item->getHash())) {
126 1
                throw new PasswordRestrictionsException(
127 1
                    'You have already used this password before. Please use a new one.'
128
                );
129
            }
130 2
            if ($item->isActive()) {
131 2
                $item->setActive(false);
132 2
                $em->persist($item);
133
            }
134
        }
135
136
        /** @var Password $password */
137 1
        $data['password'] = $data['new_password'];
138 1
        unset($data['new_password']);
139 1
        $data['created_at'] = (new \DateTime())->format(\DateTime::RFC3339);
140 1
        $data['due'] = (new \DateTime())->add(new \DateInterval('P1Y'))->format(\DateTime::RFC3339);
141 1
        $data['active'] = $data['active'] ?? true;
142
143 1
        $password = $this->hydrator->hydrate($data, new Password());
144 1
        $em->persist($password);
145
146 1
        return $password;
147
    }
148
}
149