Completed
Push — master ( 298ac7...0024da )
by Oleg
12:58
created

PasswordConfirmationMiddleware   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 5
dl 0
loc 44
ccs 0
cts 27
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B process() 0 28 3
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Authentication\Middleware;
5
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Psr\Http\Server\MiddlewareInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
use SlayerBirden\DataFlowServer\Authentication\PasswordManagerInterface;
11
use SlayerBirden\DataFlowServer\Notification\DangerMessage;
12
use Zend\Diactoros\Response\JsonResponse;
13
14
class PasswordConfirmationMiddleware implements MiddlewareInterface
15
{
16
    /**
17
     * @var PasswordManagerInterface
18
     */
19
    private $passwordManager;
20
21
    public function __construct(PasswordManagerInterface $passwordManager)
22
    {
23
        $this->passwordManager = $passwordManager;
24
    }
25
26
    /**
27
     * @inheritdoc
28
     */
29
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
30
    {
31
        $data = $request->getParsedBody();
32
33
        $password = $data['password'] ?? null;
34
35
        if (empty($password)) {
36
            return new JsonResponse([
37
                'data' => [],
38
                'success' => false,
39
                'msg' => new DangerMessage('The action requires password confirmation. No password provided.'),
40
            ], 412);
41
        } else {
42
            unset($data['password']);
43
        }
44
45
        $user = $request->getAttribute(TokenMiddleware::USER_PARAM);
46
        if (!$this->passwordManager->isValid((string)$password, $user)) {
47
            return new JsonResponse([
48
                'data' => [],
49
                'success' => false,
50
                'msg' => new DangerMessage('Invalid password provided.'),
51
            ], 412);
52
        }
53
54
        // serve down the pipe without password data
55
        return $handler->handle($request->withParsedBody($data));
56
    }
57
}
58