Completed
Push — master ( 3bc7c8...a199f7 )
by Oleg
03:54
created

UpdatePasswordAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 9.7666
c 0
b 0
f 0
cc 1
nc 1
nop 6
crap 1
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\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 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 = $request->getParsedBody();
77 6
        if (!is_array($data)) {
78
            return (new DataValidationResponseFactory())('password');
79
        }
80 6
        $this->inputFilter->setData($data);
81
82 6
        if (!$this->inputFilter->isValid()) {
83 2
            return (new ValidationResponseFactory())('password', $this->inputFilter);
84
        }
85 4
        $em = $this->managerRegistry->getManagerForClass(Password::class);
86 4
        $em->beginTransaction();
87
        try {
88 4
            $pw = $this->updatePassword($data);
89 2
            $em->flush();
90 2
            $em->commit();
91
92 2
            $msg = 'Password successfully updated.';
93 2
            return (new GeneralSuccessResponseFactory())($msg, 'password', $this->hydrator->extract($pw));
94 2
        } catch (PasswordRestrictionsException | \InvalidArgumentException $exception) {
95 2
            $em->rollback();
96 2
            return (new GeneralErrorResponseFactory())($exception->getMessage(), 'password', 400);
97
        } catch (ORMException $exception) {
98
            $this->logger->error((string)$exception);
99
            $em->rollback();
100
            return (new GeneralErrorResponseFactory())('There was an error while updating password.', 'password', 400);
101
        }
102
    }
103
104
    /**
105
     * @param array $data
106
     * @return Password
107
     * @throws PasswordRestrictionsException
108
     * @throws \Exception
109
     */
110 4
    private function updatePassword(array $data): Password
111
    {
112 4
        $userPasswords = $this->passwordRepository->matching(
113 4
            Criteria::create()->where(
114 4
                Criteria::expr()->eq('owner', $data[ClaimedResourceInterface::OWNER_PARAM])
115
            )
116
        );
117
        # check if mentioned
118 4
        $em = $this->managerRegistry->getManagerForClass(Password::class);
119
        /** @var Password $item */
120 4
        foreach ($userPasswords as $item) {
121 4
            if (password_verify($data['new_password'], $item->getHash())) {
122 2
                throw new PasswordRestrictionsException(
123 2
                    'You have already used this password before. Please use a new one.'
124
                );
125
            }
126 4
            if ($item->isActive()) {
127 4
                $item->setActive(false);
128 4
                $em->persist($item);
129
            }
130
        }
131
132
        /** @var Password $password */
133 2
        $data['password'] = $data['new_password'];
134 2
        unset($data['new_password']);
135 2
        $data['created_at'] = (new \DateTime())->format(\DateTime::RFC3339);
136 2
        $data['due'] = (new \DateTime())->add(new \DateInterval('P1Y'))->format(\DateTime::RFC3339);
137 2
        $data['active'] = $data['active'] ?? true;
138
139 2
        $password = $this->hydrator->hydrate($data, new Password());
140 2
        $em->persist($password);
141
142 2
        return $password;
143
    }
144
}
145