Completed
Push — master ( 4f3de5...9b9e7a )
by Pavel
05:51
created

AccessToken::getUserByAccessToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 11
rs 9.4285
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
        return $this->belongsTo('App\Model\User');
29
    }
30
31
    /**
32
     * @param string $accessToken
33
     *
34
     * @return User|null
35
     */
36
    public static function getUserByAccessToken($accessToken)
37
    {
38
        $user        = null;
39
        $accessToken = self::where('access_token', md5($accessToken))->first();
40
41
        if ($accessToken) {
42
            $user = $accessToken->user;
43
        }
44
45
        return $user;
46
    }
47
48
    /**
49
     * @param string $token
50
     * @param array  $whiteList
51
     *
52
     * @return bool
53
     */
54
    public static function validateToken($token, $whiteList = [])
55
    {
56
        try {
57
            $payload = JWT::decode($token, getenv('SECRET_KEY'), ['HS256']);
58
            return in_array($payload->aud, $whiteList);
59
        } catch (\Exception $e){
60
            return false;
61
        }
62
    }
63
64
    /**
65
     * @param string $host
66
     * @param int    $tokenExpire
67
     * @param User   $user
68
     *
69
     * @return string
70
     */
71
    public static function createToken($host, $tokenExpire = 3600, User $user)
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
72
    {
73
        $secret_key = getenv('SECRET_KEY');
74
        $token      = [
75
            'iss' => getenv('AUTH_ISS'),
76
            'aud' => $host,
77
            'iat' => time(),
78
            'exp' => time() + $tokenExpire,
79
        ];
80
81
        $jwt = JWT::encode($token, $secret_key);
82
83
        $user->access_tokens()->create([
84
            'access_token' => md5($jwt),
85
            'created_at'   => date('Y-m-d H:i:s'),
86
        ]);
87
88
        return $jwt;
89
    }
90
}
91