AccessToken   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 4
dl 0
loc 78
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A user() 0 4 1
A getUserByToken() 0 11 2
A validateToken() 0 9 2
A createToken() 0 18 1
1
<?php
2
3
namespace App\Model;
4
5
use Firebase\JWT\JWT;
6
7
/**
8
 * Class AccessToken
9
 *
10
 * @property integer        $id
11
 * @property string         $access_token
12
 * @property integer        $user_id
13
 * @property \Carbon\Carbon $created_at
14
 *
15
 * @package App\Model
16
 */
17
final class AccessToken extends BaseModel
18
{
19
    protected $table = 'access_tokens';
20
21
    protected $fillable = [
22
        'access_token',
23
        'user_id',
24
    ];
25
26
    public $timestamps = false;
27
28
    /**
29
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
30
     */
31
    public function user()
32
    {
33
        return $this->belongsTo('App\Model\User');
34
    }
35
36
    /**
37
     * @param string $accessToken
38
     *
39
     * @return User|null
40
     */
41
    public static function getUserByToken($accessToken)
42
    {
43
        $user        = null;
44
        $accessToken = self::where('access_token', md5($accessToken))->first();
45
46
        if ($accessToken) {
47
            $user = $accessToken->user;
48
        }
49
50
        return $user;
51
    }
52
53
    /**
54
     * @param string $token
55
     * @param array  $settings
56
     *
57
     * @return bool
58
     */
59
    public static function validateToken($token, array $settings)
60
    {
61
        try {
62
            $payload = JWT::decode($token, $settings['secretKey'], ['HS256']);
63
            return in_array($payload->aud, explode(',', $settings['allowHosts']));
64
        } catch (\Exception $e) {
65
            return false;
66
        }
67
    }
68
69
    /**
70
     * @param User   $user
71
     * @param string $host
72
     * @param array  $settings
73
     *
74
     * @return string
75
     */
76
    public static function createToken(User $user, $host, array $settings)
77
    {
78
        $token = [
79
            'iss' => $settings['iss'],
80
            'aud' => $host,
81
            'iat' => time(),
82
            'exp' => time() + $settings['ttl'],
83
        ];
84
85
        $jwt = JWT::encode($token, $settings['secretKey']);
86
87
        $user->accessTokens()->create([
88
            'access_token' => md5($jwt),
89
            'created_at'   => date('Y-m-d H:i:s'),
90
        ]);
91
92
        return $jwt;
93
    }
94
}
95