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

PasswordConfirmationMiddleware::process()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 4.0027

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 17
cts 18
cp 0.9444
rs 9.44
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4.0027
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