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

PasswordConfirmationMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 93.75%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 5
dl 0
loc 39
ccs 15
cts 16
cp 0.9375
rs 10
c 0
b 0
f 0

2 Methods

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