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

PasswordConfirmationMiddleware::process()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4.0072

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 12
cts 13
cp 0.9231
rs 9.552
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4.0072
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