|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Modules\Core\Http\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Http\Request; |
|
6
|
|
|
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; |
|
7
|
|
|
use Tymon\JWTAuth\Exceptions\JWTException; |
|
8
|
|
|
use Tymon\JWTAuth\JWTAuth; |
|
9
|
|
|
|
|
10
|
|
|
abstract class BaseAuthenticate |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* The JWT Authenticator. |
|
14
|
|
|
* |
|
15
|
|
|
* @var \Tymon\JWTAuth\JWTAuth |
|
16
|
|
|
*/ |
|
17
|
|
|
protected $auth; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Create a new BaseMiddleware instance. |
|
21
|
|
|
* |
|
22
|
|
|
* @param \Tymon\JWTAuth\JWTAuth $auth |
|
23
|
|
|
* |
|
24
|
|
|
* @return void |
|
25
|
|
|
*/ |
|
26
|
|
|
public function __construct(JWTAuth $auth) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->auth = $auth; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Check the request for the presence of a token. |
|
33
|
|
|
* |
|
34
|
|
|
* @param \Illuminate\Http\Request $request |
|
35
|
|
|
* |
|
36
|
|
|
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException |
|
37
|
|
|
* |
|
38
|
|
|
* @return void |
|
39
|
|
|
*/ |
|
40
|
|
|
public function checkForToken(Request $request) |
|
41
|
|
|
{ |
|
42
|
|
|
if (!$this->auth->parser()->setRequest($request)->hasToken()) { |
|
43
|
|
|
throw new UnauthorizedHttpException('jwt-auth', 'Token not provided'); |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Attempt to authenticate a user via the token in the request. |
|
49
|
|
|
* |
|
50
|
|
|
* @param \Illuminate\Http\Request $request |
|
51
|
|
|
* |
|
52
|
|
|
* @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException |
|
53
|
|
|
* |
|
54
|
|
|
* @return void |
|
55
|
|
|
*/ |
|
56
|
|
|
public function authenticate(Request $request) |
|
57
|
|
|
{ |
|
58
|
|
|
$this->checkForToken($request); |
|
59
|
|
|
|
|
60
|
|
|
try { |
|
61
|
|
|
if (!$this->auth->parseToken()->authenticate()) { |
|
62
|
|
|
throw new UnauthorizedHttpException('jwt-auth', 'User not found'); |
|
63
|
|
|
} |
|
64
|
|
|
} catch (JWTException $e) { |
|
65
|
|
|
throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode()); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* Set the authentication header. |
|
71
|
|
|
* |
|
72
|
|
|
* @param \Illuminate\Http\Response|\Illuminate\Http\JsonResponse $response |
|
73
|
|
|
* @param string|null $token |
|
74
|
|
|
* |
|
75
|
|
|
* @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse |
|
76
|
|
|
*/ |
|
77
|
|
|
protected function setAuthenticationHeader($response, $token = null) |
|
78
|
|
|
{ |
|
79
|
|
|
$token = $token ?: $this->auth->refresh(); |
|
80
|
|
|
$response->headers->set('Authorization', 'Bearer '.$token); |
|
81
|
|
|
|
|
82
|
|
|
return $response; |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|