Completed
Push — 2.0 ( 60f4f1...be6014 )
by Kirill
04:10
created

TokenAuth::user()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
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 App\Models\User;
12
use Carbon\Carbon;
13
use Illuminate\Contracts\Auth\Authenticatable;
14
use Illuminate\Contracts\Auth\Guard;
15
use Illuminate\Contracts\Encryption\DecryptException;
16
use Illuminate\Encryption\Encrypter;
17
use Illuminate\Support\Arr;
18
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
19
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
20
use Tymon\JWTAuth\Exceptions\JWTException;
21
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
22
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
23
use Tymon\JWTAuth\Providers\JWT\JWTInterface;
24
25
/**
26
 * Class TokenAuth
27
 * @package App\Services
28
 */
29
class TokenAuth
30
{
31
    /**
32
     * @var JWTInterface
33
     */
34
    private $jwt;
35
36
    /**
37
     * @var Guard
38
     */
39
    private $guard;
40
41
    /**
42
     * TokenAuth constructor.
43
     * @param JWTInterface $jwt
44
     * @param Guard $guard
45
     */
46
    public function __construct(JWTInterface $jwt, Guard $guard)
47
    {
48
        $this->jwt = $jwt;
49
        $this->guard = $guard;
50
    }
51
52
    /**
53
     * @param string $email
54
     * @param string $password
55
     * @return Authenticatable
56
     */
57
    public function attemptFromEmailAndPassword(string $email, string $password): ?Authenticatable
58
    {
59
        if (! $this->guard->validate(['email' => $email, 'password' => $password])) {
60
            return null;
61
        }
62
63
        return User::whereEmail($email)->first();
64
    }
65
66
    /**
67
     * @param int $id
68
     * @param string $password
69
     * @return Authenticatable
70
     */
71
    public function resolveFromIdAndPassword(int $id, string $password): ?Authenticatable
72
    {
73
        if (! $this->guard->validate(['id' => $id, 'password' => $password])) {
74
            return null;
75
        }
76
77
        return User::find($id);
78
    }
79
80
    /**
81
     * @return Authenticatable
82
     */
83
    public function guest(): Authenticatable
84
    {
85
        return new User(['id' => 0, 'name' => 'Guest']);
86
    }
87
88
    /**
89
     * @param string $token
90
     * @return array
91
     */
92
    public function decode(string $token): array
93
    {
94
        return $this->jwt->decode($token);
95
    }
96
97
    /**
98
     * @param Guard $guard
99
     * @return string
100
     */
101
    public function fromGuard(Guard $guard): string
102
    {
103
        return $this->fromUser($guard->check() ? $guard->user() : $this->guest());
104
    }
105
106
    /**
107
     * @param Authenticatable $user
108
     * @return string
109
     */
110
    public function fromUser(Authenticatable $user): string
111
    {
112
        return $this->encode([
113
            'user'  => [
114
                'id'       => $user->getAuthIdentifier(),
115
                'password' => $user->getAuthPassword(),
116
            ],
117
            'token' => $user->getRememberToken(),
118
        ]);
119
    }
120
121
    /**
122
     * @param string $token
123
     * @return Authenticatable
124
     * @throws BadRequestHttpException
125
     * @throws UnprocessableEntityHttpException
126
     */
127
    public function fromToken(string $token): Authenticatable
128
    {
129
        try {
130
            $userInfo = $this->decode($token);
131
        } catch (TokenExpiredException $e) {
132
            throw new BadRequestHttpException('Token lifetime is timed out.');
133
        } catch (JWTException $invalidException) {
134
            throw new BadRequestHttpException('Broken api token.');
135
        }
136
137
        [$id, $password] = [
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...
138
            (int)Arr::get($userInfo, 'user.id'),
139
            Arr::get($userInfo, 'user.password'),
140
        ];
141
142
        if ($id !== 0) {
143
            $user = User::where('id', $id)->where('password', $password)->first();
144
145
            if (! $user) {
146
                throw new UnprocessableEntityHttpException('Invalid user credentials.');
147
            }
148
149
            return $user;
150
        }
151
152
        return $this->guest();
153
    }
154
155
    /**
156
     * @param array $payload
157
     * @return string
158
     */
159
    public function encode(array $payload): string
160
    {
161
        return $this->jwt->encode($payload);
162
    }
163
}