Authenticate::handle()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
c 0
b 0
f 0
cc 5
nc 3
nop 3
rs 9.3888
1
<?php
2
declare(strict_types=1);
3
4
namespace Tfboe\FmLib\Http\Middleware;
5
6
use Closure;
7
use Illuminate\Contracts\Auth\Factory as Auth;
8
use Tfboe\FmLib\Entity\UserInterface;
9
use Tfboe\FmLib\Exceptions\AuthenticationException;
10
use Tymon\JWTAuth\Payload;
11
12
/**
13
 * Class Authenticate
14
 * @package App\Http\Middleware
15
 */
16
class Authenticate
17
{
18
//<editor-fold desc="Fields">
19
  /**
20
   * The authentication guard factory instance.
21
   *
22
   * @var \Illuminate\Contracts\Auth\Factory
23
   */
24
  protected $auth;
25
//</editor-fold desc="Fields">
26
27
//<editor-fold desc="Constructor">
28
  /**
29
   * Create a new middleware instance.
30
   *
31
   * @param  \Illuminate\Contracts\Auth\Factory $auth
32
   */
33
  public function __construct(Auth $auth)
34
  {
35
    $this->auth = $auth;
36
  }
37
//</editor-fold desc="Constructor">
38
39
//<editor-fold desc="Public Methods">
40
  /**
41
   * Handle an incoming request.
42
   *
43
   * @param  \Illuminate\Http\Request $request
44
   * @param  \Closure $next
45
   * @param  string|null $guardName
46
   * @return mixed
47
   * @throws AuthenticationException if request doesn't provide valid authentication token
48
   */
49
  public function handle($request, Closure $next, $guardName = null)
50
  {
51
    $guard = $this->auth->guard($guardName);
52
    if ($guard->guest()) {
53
      throw new AuthenticationException("Not logged in!");
54
    }
55
    /** @var Payload $payload */
56
    $payload = $guard->getPayload();
57
    /** @var UserInterface $user */
58
    $user = $guard->getUser();
59
    if (!$payload->hasKey('ver') || !($user instanceof UserInterface) || $payload->get(['ver'])[0] <
60
      $user->getJwtVersion()) {
61
      throw new AuthenticationException("Payload version expired!");
62
    }
63
64
    return $next($request);
65
  }
66
//</editor-fold desc="Public Methods">
67
}
68