Completed
Push — master ( 098c1d...89670e )
by Jacob
02:08
created

BaseGuard::setRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016 Canis.io
4
 * @license   MIT
5
 */
6
namespace Canis\Lumen\Jwt;
7
8
use Auth;
9
use Illuminate\Http\Request;
10
use Illuminate\Support\Str;
11
use Illuminate\Auth\GuardHelpers;
12
use Illuminate\Contracts\Auth\UserProvider;
13
use Illuminate\Contracts\Auth\Guard;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Canis\Lumen\Jwt\Guard.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
14
use Illuminate\Contracts\Auth\Authenticatable;
15
use Canis\Lumen\Jwt\Exceptions\InvalidTokenException;
16
use Canis\Lumen\Jwt\Exceptions\InvalidAdapterException;
17
18
abstract class BaseGuard
19
    implements Guard, GuardInterface
0 ignored issues
show
Coding Style introduced by
The implements keyword must be on the same line as the class name
Loading history...
20
{
21
    use GuardHelpers;
22
23
    private $request;
24
    private $providerIdentifier;
25
26 3
    public function __construct($provider, Request $request)
27
    {
28 3
        $this->request = $request;
29 3
        $this->providerIdentifier = $provider;
30 3
        $this->provider = Auth::createUserProvider($provider);
31 3
    }
32
33 3
    public function getAdapterFactoryClass()
34
    {
35 3
        $config = config('jwt');
36 3
        if (!isset($config['adapter'])) {
37 1
            $config['adapter'] = 'lcobucci';
38 1
        }
39 3
        if (class_exists($config['adapter'])) {
40 1
            $factoryClass = $config['adapter'];
41 1
        } else {
42 2
            $factoryClass = 'Canis\Lumen\Jwt\Adapters\\' . ucfirst($config['adapter']) .'\Factory';
43 2
            if (!class_exists($factoryClass)) {
44 1
                throw new InvalidAdapterException("{$config['adapter']} is not available");
45
            }
46
        }
47 2
        return $factoryClass;
48
    }
49
50 3
    protected function getAdapterFactory()
51
    {
52 3
        static $factory;
53 3
        if (!isset($factory)) {
54 3
            $config = config('jwt');
55 3
            $factoryClass = $this->getAdapterFactoryClass();
56 2
            $factory = new $factoryClass($config);
57 2
        }
58 2
        return $factory;
59
    }
60
61 1
    protected function getProcessor()
62
    {
63 1
        return $this->getAdapterFactory()->getProcessor();
64
    }
65
66 3
    protected function getGenerator()
67
    {
68 3
        return $this->getAdapterFactory()->getGenerator();
69
    }
70
71
    public function getProvider()
72
    {
73
        return $this->provider;
74
    }
75
76
    /**
77
     * @inheritdoc
78
     */
79
    public function user()
80
    {
81
        if (!is_null($this->user)) {
82
            return $this->user;
83
        }
84
        $user = null;
85
        $token = $this->getBearerToken();
86
        if ($token !== false) {
87
            $user = $this->getProvider()->retrieveById($token->getClaim('sub'));
88
        }
89
        return $this->user = $user;
90
    }
91
92
    public function getBearerToken()
93
    {
94
        $authHeader = $this->request->headers->get('Authorization');
95
        if (empty($authHeader)) {
96
            return false;
97
        }
98
        if (!Str::startsWith(strtolower($authHeader), 'bearer')) {
99
            return false;
100
        }
101
        $token = trim(str_ireplace('bearer', '', $authHeader));
102
        $processor = $this->getProcessor();
103
        return $processor($token);
104
    }
105
106
    /**
107
     * @inheritdoc
108
     */
109
    public function validate(array $credentials = [])
110
    {
111
        $user = $this->getProvider()->retrieveByCredentials($credentials);
112
        if ($this->hasValidCredentials($user, $credentials)) {
0 ignored issues
show
Bug introduced by
The method hasValidCredentials() does not seem to exist on object<Canis\Lumen\Jwt\BaseGuard>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
113
            return true;
114
        }
115
        return false;
116
    }
117
118
    public function setRequest(Request $request)
119
    {
120
        $this->request = $request;
121
    }
122
123
    /**
124
     * Attempt to authenticate a user using the given credentials.
125
     *
126
     * @param  array  $credentials
127
     * @return bool
128
     */
129
    public function attempt(array $credentials = [])
130
    {
131
        $user = $this->getProvider()->retrieveByCredentials($credentials);
132
        if ($this->hasValidCredentials($user, $credentials)) {
0 ignored issues
show
Bug introduced by
The method hasValidCredentials() does not seem to exist on object<Canis\Lumen\Jwt\BaseGuard>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
133
            $tokenGenerator = $this->getGenerator();
134
            $claims = $user->getJWTClaims();
0 ignored issues
show
Bug introduced by
The method getJWTClaims() does not seem to exist on object<Illuminate\Contracts\Auth\Authenticatable>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
135
            $claims['sub'] = $user->getJWTSubject();
0 ignored issues
show
Bug introduced by
The method getJWTSubject() does not seem to exist on object<Illuminate\Contracts\Auth\Authenticatable>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
136
            $claims['type'] = $this->providerIdentifier;
137
            if (!($token = $tokenGenerator($claims))) {
138
                throw new InvalidTokenException("Unable to generate token");
139
            }
140
            return $token;
141
        }
142
        return false;
143
    }
144
}
145