Passed
Push — master ( 279881...b4f44a )
by Divine Niiquaye
10:48
created

CsrfTokenAuthenticator::setToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 1
dl 0
loc 2
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Biurad opensource projects.
7
 *
8
 * PHP version 7.4 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2019 Biurad Group (https://biurad.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 *
17
 */
18
19
namespace Biurad\Security\Authenticator;
20
21
use Biurad\Security\Interfaces\AuthenticatorInterface;
22
use Psr\Http\Message\ServerRequestInterface;
23
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
24
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
25
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
26
use Symfony\Component\Security\Csrf\CsrfToken;
27
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
28
29
/**
30
 * Authenticates whether the given CSRF token is valid.
31
 *
32
 * @author Divine Niiquaye Ibok <[email protected]>
33
 */
34
class CsrfTokenAuthenticator implements AuthenticatorInterface
35
{
36
    private CsrfTokenManagerInterface $csrfTokenManager;
37
    private string $csrfTokenId;
38
    private string $csrfParameter;
39
40
    public function __construct(CsrfTokenManagerInterface $csrfTokenManager, string $csrfTokenId = 'authenticate', string $csrfParameter = '_csrf_token')
41
    {
42
        $this->csrfTokenManager = $csrfTokenManager;
43
        $this->csrfTokenId = $csrfTokenId;
44
        $this->csrfParameter = $csrfParameter;
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public function supports(ServerRequestInterface $request): bool
51
    {
52
        return 'POST' === $request->getMethod();
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function authenticate(ServerRequestInterface $request, array $credentials, string $firewallName): ?TokenInterface
59
    {
60
        if (empty($csrfToken = $credentials[$this->csrfParameter] ?? null)) {
61
            return null;
62
        }
63
64
        if (!\is_string($csrfToken)) {
65
            throw new BadRequestException(\sprintf('The key "%s" must be a string, "%s" given.', $this->csrfParameter, \gettype($csrfToken)));
66
        }
67
68
        $csrfToken = new CsrfToken($this->csrfTokenId, $csrfToken);
69
70
        if (!$this->csrfTokenManager->isTokenValid($csrfToken)) {
71
            throw new InvalidCsrfTokenException('Invalid CSRF token.');
72
        }
73
74
        return null;
75
    }
76
}
77