Middleware   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 22
c 1
b 0
f 0
dl 0
loc 39
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 11 1
A validate() 0 12 2
A __construct() 0 6 1
1
<?php
2
3
namespace Erykai\Routes;
4
5
class Middleware
6
{
7
    protected string $key;
8
    protected string $header;
9
10
    public function __construct()
11
    {
12
        $this->key = KEY_JWT;
13
        $this->header = base64_encode(json_encode([
14
            'typ' => 'JWT',
15
            'alg' => 'HS256'
16
        ]));
17
    }
18
19
    public function create(string $email): string
20
    {
21
        $key = KEY_JWT;
0 ignored issues
show
Unused Code introduced by
The assignment to $key is dead and can be removed.
Loading history...
22
23
        $payload = base64_encode(json_encode([
24
            'email' => $email,
25
        ]));
26
27
        $sign = hash_hmac('sha256', $this->header . "." . $payload, $this->key, true);
28
        $sign = base64_encode($sign);
29
        return $this->header . '.' . $payload . '.' . $sign;
30
    }
31
32
    public function validate(): bool
33
    {
34
        if(empty(getallheaders()['Authorization'])){
35
            return false;
36
        }
37
        $barer = str_replace('Bearer ', '', getallheaders()['Authorization']);
38
        $barers = explode('.', $barer);
39
        $payload = $barers[1];
40
        $sign = hash_hmac('sha256', $this->header . "." . $payload, $this->key, true);
41
        $sign = base64_encode($sign);
42
        $keyBarer = $this->header . '.' . $payload . '.' . $sign;
43
        return $keyBarer === $barer;
44
    }
45
}