Completed
Push — master ( 52244a...079467 )
by Sébastien
07:24
created

JwtService::parseTokenString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Soluble\Wallit\Service;
6
7
use Soluble\Wallit\Exception;
8
use Lcobucci\JWT\Builder;
9
use Lcobucci\JWT\Token;
10
use Lcobucci\JWT\Signer;
11
use Lcobucci\JWT\Parser;
12
13
class JwtService
14
{
15
    /**
16
     * @var Signer
17
     */
18
    protected $signer;
19
20
    /**
21
     * @var Parser
22
     */
23
    protected $tokenParser;
24
25
    /**
26
     * @var string
27
     */
28
    protected $verificationKey;
29
30
    /**
31
     * @var string|null
32
     */
33
    protected $publicKey;
34
35
    /**
36
     * @var int
37
     */
38
    protected $expiration;
39
40
    /**
41
     * JwtService constructor.
42
     *
43
     * @param Signer $signer
44
     * @param string $verificationKey
45
     * @param string $publicKey       Only needed for asymmetric support
46
     */
47 15
    public function __construct(Signer $signer, string $verificationKey, string $publicKey = null)
48
    {
49 15
        if (trim($verificationKey) === '') {
50 1
            throw new \InvalidArgumentException('Private key key cannot be empty');
51
        }
52
53 14
        if ($publicKey !== null && trim($publicKey) === '') {
54 1
            throw new \InvalidArgumentException('If public key is provided it cannot be empty');
55
        }
56
57 13
        $this->signer = $signer;
58 13
        $this->verificationKey = $verificationKey;
59 13
        $this->publicKey = $publicKey;
60 13
        $this->expiration = time() + 3600;
61 13
    }
62
63
    /**
64
     * Create new signed token.
65
     *
66
     * @param array $claims
67
     * @param int   $expiration
68
     *
69 6
     * @return Token
70
     */
71 6
    public function createToken(array $claims = [], int $expiration = null): Token
72 5
    {
73
        if ($expiration === null) {
74
            $expiration = $this->expiration;
75 6
        }
76
77 6
        $jwtBuilder = new Builder();
78 4
79
        foreach ($claims as $key => $value) {
80
            $jwtBuilder->set($key, $value);
81 6
        }
82 6
83
        $jwtBuilder->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
84
                   ->setExpiration($expiration); // Configures the expiration time of the token (nbf claim)
85
86
        /*
87
        ->setIssuer('http://example.com') // Configures the issuer (iss claim)
88
        ->setAudience('http://example.org') // Configures the audience (aud claim)
89
        ->setNotBefore(time() + 60) // Configures the time that the token can be used (nbf claim)
90
        ->setId('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
91
        //$jwtBuilder->set('uid', 1); // Configures a new claim, called "uid"
92 6
        */
93
94 6
        // This will change with lcobucci v4
95
        $jwtBuilder->sign($this->signer, $this->verificationKey);
96
97
        return $jwtBuilder->getToken();
98
    }
99
100
    /**
101
     * Parse a token string into a JWT\Token.
102
     *
103
     * @throws Exception\InvalidTokenException
104
     *
105
     * @param string $tokenString
106 9
     *
107
     * @return Token
108 9
     */
109
    public function parsePlainToken(string $tokenString): Token
110 9
    {
111 3
        $tokenParser = new Parser();
112 3
        try {
113
            $token = $tokenParser->parse($tokenString);
114
        } catch (\Throwable $invalidToken) {
115
            throw new Exception\InvalidTokenException('Cannot parse the JWT token', 1, $invalidToken);
116
        }
117
        /*
118
        if (!$token->validate(new ValidationData())) {
119 6
            throw new Exception\InvalidTokenException('Validation of JWT token failed', 2);
120
        }
121
        */
122
        return $token;
123
    }
124
125
    /**
126
     * Parse and verify a token.
127
     *
128
     * @throws Exception\InvalidTokenException
129
     *
130
     * @param string $tokenString
131 2
     *
132
     * @return bool
133 2
     */
134
    public function verifyPlainToken(string $tokenString): bool
135 1
    {
136
        $token = $this->parsePlainToken($tokenString);
137
138
        return $token->verify($this->signer, $this->verificationKey);
139
    }
140
141 4
    /**
142
     * @return Signer
143 4
     */
144
    public function getSigner(): Signer
145
    {
146
        return $this->signer;
147
    }
148
149
    /**
150
     * Return private key.
151 4
     *
152
     * @return string
153 4
     */
154
    public function getPrivateKey(): string
155
    {
156
        return $this->verificationKey;
157
    }
158
}
159