Completed
Push — master ( 079467...2df5cb )
by Sébastien
11:56
created

JwtService::parsePlainToken()   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
c 0
b 0
f 0
ccs 6
cts 6
cp 1
rs 9.4285
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
     * @return Token
70
     */
71 6
    public function createToken(array $claims = [], int $expiration = null): Token
72
    {
73 6
        if ($expiration === null) {
74 5
            $expiration = $this->expiration;
75
        }
76
77 6
        $jwtBuilder = new Builder();
78
79 6
        foreach ($claims as $key => $value) {
80 4
            $jwtBuilder->set($key, $value);
81
        }
82
83 6
        $jwtBuilder->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
84 6
                   ->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
        */
93
94
        // This will change with lcobucci v4
95 6
        $jwtBuilder->sign($this->signer, $this->verificationKey);
96
97 6
        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
     *
107
     * @return Token
108
     */
109 9
    public function parsePlainToken(string $tokenString): Token
110
    {
111 9
        $tokenParser = new Parser();
112
        try {
113 9
            $token = $tokenParser->parse($tokenString);
114 3
        } catch (\Throwable $invalidToken) {
115 3
            throw new Exception\InvalidTokenException('Cannot parse the JWT token', 1, $invalidToken);
116
        }
117
        /*
118
        if (!$token->validate(new ValidationData())) {
119
            throw new Exception\InvalidTokenException('Validation of JWT token failed', 2);
120
        }
121
        */
122 6
        return $token;
123
    }
124
125
    /**
126
     * Parse and verify a token.
127
     *
128
     * @throws Exception\InvalidTokenException
129
     *
130
     * @param string $tokenString
131
     *
132
     * @return bool
133
     */
134 2
    public function verifyPlainToken(string $tokenString): bool
135
    {
136 2
        $token = $this->parsePlainToken($tokenString);
137
138 1
        return $token->verify($this->signer, $this->verificationKey);
139
    }
140
141
    /**
142
     * @return Signer
143
     */
144 4
    public function getSigner(): Signer
145
    {
146 4
        return $this->signer;
147
    }
148
149
    /**
150
     * Return private key.
151
     *
152
     * @return string
153
     */
154 4
    public function getPrivateKey(): string
155
    {
156 4
        return $this->verificationKey;
157
    }
158
}
159