JWTCommand   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
c 1
b 0
f 0
dl 0
loc 70
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A checkPublicKey() 0 7 2
A buildJWT() 0 8 2
A handle() 0 23 1
1
<?php
2
3
namespace tbclla\Revolut\Console\Commands;
4
5
use Exception;
6
use Firebase\JWT\JWT;
7
use Illuminate\Console\Command;
8
use tbclla\Revolut\Auth\ClientAssertion;
9
use tbclla\Revolut\Exceptions\ConfigurationException;
10
11
class JWTCommand extends Command
12
{
13
    /**
14
     * The name and signature of the console command.
15
     *
16
     * @var string
17
     */
18
    protected $signature = 'revolut:jwt {--public= : The path to your public key}';
19
20
    /**
21
     * The console command description.
22
     *
23
     * @var string
24
     */
25
    protected $description = "Generate a JSON Web Token for Revolut's Oauth process.";
26
27
    /**
28
     * Execute the console command.
29
     *
30
     * @return mixed
31
     */
32
    public function handle()
33
    {
34
        // build the JWT
35
        $jwt = $this->buildJWT();
36
37
        $this->info('Your JSON web token was created successfully:');
38
        $this->info('<fg=black;bg=yellow>' . $jwt . '</>');
39
40
        // optionally, verify the key
41
        $key = $this->checkPublicKey($this->option('public') ?? null);
42
43
        $decoded = JWT::decode($jwt, $key, [ClientAssertion::ALGORYTHM]);
44
45
        $headers = ['parameter', 'value'];
46
        $data = [
47
            ['issuer', $decoded->iss],
48
            ['subject', $decoded->sub],
49
            ['expiry', $decoded->exp],
50
            ['audience', $decoded->aud],
51
        ];
52
53
        $this->info('Your JWT has been verified and is valid.');
54
        $this->table($headers, $data);
55
    }
56
57
    /**
58
     * @return string
59
     */
60
    private function buildJWT()
61
    {
62
        try {
63
            $clientAssertion = resolve(ClientAssertion::class);
64
            return $clientAssertion->build();
65
        } catch (ConfigurationException $e) {
66
            $this->error($e->getMessage());
67
            return;
68
        }
69
    }
70
71
    /**
72
     * @return string
73
     */
74
    private function checkPublicKey($key = null)
75
    {
76
        try {
77
            return file_get_contents($key ?? $this->ask('If you want to validate this JWT, enter the path to your public key'));
78
        } catch (Exception $e) {
79
            $this->error($e->getMessage());
80
            return $this->checkPublicKey();
81
        }
82
    }
83
}
84