TokenAuth::fromToken()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 6
nop 1
dl 0
loc 17
rs 9.2
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of laravel.su package.
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
declare(strict_types=1);
8
9
namespace App\Services;
10
11
use Carbon\Carbon;
12
use App\Models\User;
13
use Illuminate\Support\Arr;
14
use Illuminate\Contracts\Auth\Guard;
15
use Tymon\JWTAuth\Exceptions\JWTException;
16
use Tymon\JWTAuth\Providers\JWT\JWTInterface;
17
use Illuminate\Contracts\Auth\Authenticatable;
18
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
19
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
20
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
21
22
/**
23
 * Class TokenAuth.
24
 */
25
class TokenAuth
26
{
27
    /**
28
     * @var JWTInterface
29
     */
30
    private $jwt;
31
32
    /**
33
     * @var Guard
34
     */
35
    private $guard;
36
37
    /**
38
     * TokenAuth constructor.
39
     * @param JWTInterface $jwt
40
     * @param Guard $guard
41
     */
42
    public function __construct(JWTInterface $jwt, Guard $guard)
43
    {
44
        $this->jwt = $jwt;
45
        $this->guard = $guard;
46
    }
47
48
    /**
49
     * @param string $email
50
     * @param string $password
51
     * @return Authenticatable
52
     */
53
    public function attemptFromEmailAndPassword(string $email, string $password): ?Authenticatable
54
    {
55
        if (! $this->guard->validate(['email' => $email, 'password' => $password])) {
56
            return null;
57
        }
58
59
        return User::whereEmail($email)->first();
60
    }
61
62
    /**
63
     * @param int $id
64
     * @param string $password
65
     * @return Authenticatable
66
     */
67
    public function resolveFromIdAndPassword(int $id, string $password): ?Authenticatable
68
    {
69
        if (! $this->guard->validate(['id' => $id, 'password' => $password])) {
70
            return null;
71
        }
72
73
        return User::find($id);
74
    }
75
76
    /**
77
     * @param Guard $guard
78
     * @return string
79
     */
80
    public function fromGuard(Guard $guard): string
81
    {
82
        return $this->fromUser($guard->check() ? $guard->user() : $this->guest());
83
    }
84
85
    /**
86
     * @param Authenticatable $user
87
     * @return string
88
     */
89
    public function fromUser(Authenticatable $user): string
90
    {
91
        return $this->encode([
92
            'user'    => [
93
                'id'       => $user->getAuthIdentifier(),
94
                'password' => $user->getAuthPassword(),
95
            ],
96
            'created' => Carbon::now()->toRfc3339String(),
97
            'guest'   => 0 === (int) $user->getAuthIdentifier(),
98
            'token'   => $user->getRememberToken(),
99
        ]);
100
    }
101
102
    /**
103
     * @param array $payload
104
     * @return string
105
     */
106
    public function encode(array $payload): string
107
    {
108
        return $this->jwt->encode($payload);
109
    }
110
111
    /**
112
     * @return Authenticatable
113
     */
114
    public function guest(): Authenticatable
115
    {
116
        return new User(['id' => 0, 'name' => 'Guest']);
117
    }
118
119
    /**
120
     * @param string $token
121
     * @return Authenticatable
122
     * @throws BadRequestHttpException
123
     * @throws UnprocessableEntityHttpException
124
     */
125
    public function fromToken(string $token): Authenticatable
126
    {
127
        try {
128
            $userInfo = $this->decode($token);
129
            $this->verifyTokenCreated($userInfo);
130
        } catch (TokenExpiredException $e) {
131
            throw new BadRequestHttpException('Token lifetime is timed out.');
132
        } catch (JWTException $invalidException) {
133
            throw new BadRequestHttpException('Broken api token.');
134
        }
135
136
        if (false !== Arr::get($userInfo, 'guest', true)) {
137
            return $this->resolveExistingUser($userInfo);
138
        }
139
140
        return $this->guest();
141
    }
142
143
    /**
144
     * @param array $userInfo
145
     * @throws TokenExpiredException
146
     */
147
    private function verifyTokenCreated(array $userInfo): void
148
    {
149
        $created = Carbon::parse($userInfo['created'] ?? '0001-00-00 00:00');
150
151
        if (Carbon::now()->subMinutes(config('jwt.ttl')) > $created) {
152
            throw new TokenExpiredException();
153
        }
154
    }
155
156
    /**
157
     * @param string $token
158
     * @return array
159
     */
160
    public function decode(string $token): array
161
    {
162
        return $this->jwt->decode($token);
163
    }
164
165
    /**
166
     * @param array $userInfo
167
     * @return mixed
168
     * @throws UnprocessableEntityHttpException
169
     */
170
    private function resolveExistingUser(array $userInfo)
171
    {
172
        [$id, $password, $token] = [
0 ignored issues
show
Bug introduced by
The variable $id does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $password does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $token does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
173
            (int) Arr::get($userInfo, 'user.id'),
174
            (string) Arr::get($userInfo, 'user.password'),
175
            (string) Arr::get($userInfo, 'token'),
176
        ];
177
178
        $user = User::where('id', $id)->where('password', $password)->first();
179
180
        if ($user->remember_token !== $token) {
181
            throw new UnprocessableEntityHttpException('Invalid remember token');
182
        }
183
184
        if (! $user) {
185
            throw new UnprocessableEntityHttpException('Invalid user credentials.');
186
        }
187
188
        return $user;
189
    }
190
}
191