Completed
Push — master ( 9a366d...5cc45f )
by Pavel
17s
created

AccessToken::validateToken()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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