Completed
Push — master ( 5c0b6f...5c71f2 )
by Oleg
10:16
created

PasswordConfirmationMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 95.24%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 6
dl 0
loc 46
ccs 20
cts 21
cp 0.9524
rs 10
c 0
b 0
f 0

2 Methods

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