Completed
Push — master ( 76ae44...61569d )
by Raffael
01:46
created

Auth::injectAdapter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
declare(strict_types = 1);
3
4
/**
5
 * Micro
6
 *
7
 * @author    Raffael Sahli <[email protected]>
8
 * @copyright Copyright (c) 2017 gyselroth GmbH (https://gyselroth.com)
9
 * @license   MIT https://opensource.org/licenses/MIT
10
 */
11
12
namespace Micro;
13
14
use \Micro\Auth\Exception;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Micro\Exception.

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...
15
use \Micro\Auth\Adapter\AdapterInterface;
16
use \Micro\Auth\Identity;
17
use \Psr\Log\LoggerInterface as Logger;
18
use \Micro\Auth\AttributeMap;
19
20
class Auth
21
{
22
    /**
23
     * Adapter
24
     *
25
     * @var array
26
     */
27
    protected $adapter = [];
28
    
29
30
    /**
31
     * Identity
32
     *
33
     * @var Identity
34
     */
35
    protected $identity;
36
37
38
    /**
39
     * Logger
40
     *
41
     * @var Logger
42
     */
43
    protected $logger;
44
45
46
    /**
47
     * Identity class
48
     *  
49
     * @var string
50
     */
51
    protected $identity_class = Identity::class;
52
    
53
    
54
    /**
55
     * Attribute map class
56
     *  
57
     * @var string
58
     */
59
    protected $attribute_map_class = AttributeMap::class;
60
61
62
    /**
63
     * Initialize
64
     *
65
     * @param   Iterable $config
66
     * @param   Logger $logger
67
     * @return  void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
68
     */
69
    public function __construct(? Iterable $config = null, Logger $logger)
70
    {
71
        $this->logger = $logger;
72
        $this->setOptions($config);
73
    }
74
75
76
    /**
77
     * Set options
78
     *
79
     * @param  Iterable $config
80
     * @return Auth
81
     */
82
    public function setOptions(? Iterable $config = null) : Auth
83
    {
84
        if ($config === null) {
85
            return $this;
86
        }
87
88
        foreach ($config as $option => $value) {
89
            switch ($option) {
90
                case 'identity_class': 
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
91
                case 'attribute_map_class': 
92
                    $this->{$option} = (string)$value;
93
                break;
94
95
                case 'adapter':
96
                    foreach ($value as $name => $adapter) {
97
                        if (!isset($adapter['enabled']) || $adapter['enabled'] === '1') {
98
                            if (!isset($adapter['class'])) {
99
                                throw new Exception('class option is required');
100
                            }
101
                        
102
                            if (isset($adapter['config'])) {
103
                                $config = $adapter['config'];
104
                            } else {
105
                                $config = null;
106
                            }
107
                            $this->addAdapter($name, $adapter['class'], $config);
108
                        } else {
109
                            $this->logger->debug("skip disabled authentication adapter [".$name."]", [
110
                                'category' => get_class($this)
111
                            ]);
112
                        }
113
                    }
114
                break;
115
            }
116
        }    
117
    
118
        return $this;
119
    }
120
121
122
    /**
123
     * Has adapter
124
     *
125
     * @param  string $name
126
     * @return bool
127
     */
128
    public function hasAdapter(string $name): bool
129
    {
130
        return isset($this->adapter[$name]);
131
    }
132
133
134
    /**
135
     * Add adapter
136
     *
137
     * @param  string $name
138
     * @param  string $class
139
     * @param  Iterable $config
140
     * @return AdapterInterface
141
     */
142
    public function addAdapter(string $name, string $class, ? Iterable $config = null) : AdapterInterface
143
    {
144
        if ($this->hasAdapter($name)) {
145
            throw new Exception('auth adapter '.$name.' is already registered');
146
        }
147
            
148
        $adapter = new $class($config, $this->logger);
149
        if (!($adapter instanceof AdapterInterface)) {
150
            throw new Exception('auth adapter must include AdapterInterface interface');
151
        }
152
        $this->adapter[$name] = $adapter;
153
        return $adapter;
154
    }
155
156
157
    /**
158
     * Inject adapter
159
     *
160
     * @param  string $name
161
     * @param  AdapterInterface $adapter
162
     * @return AdapterInterface
163
     */
164
    public function injectAdapter(string $name, AdapterInterface $adapter) : AdapterInterface
165
    {
166
        if ($this->hasAdapter($name)) {
167
            throw new Exception('auth adapter '.$name.' is already registered');
168
        }
169
            
170
        $this->adapter[$name] = $adapter;
171
        return $adapter;
172
    }
173
174
175
    /**
176
     * Get adapter
177
     *      
178
     * @param  string $name
179
     * @return AdapterInterface
180
     */
181
    public function getAdapter(string $name): AdapterInterface
182
    {
183
        if (!$this->hasAdapter($name)) {
184
            throw new Exception('auth adapter '.$name.' is not registered');
185
        }
186
187
        return $this->adapter[$name];
188
    }
189
190
191
    /**
192
     * Get adapters
193
     *      
194
     * @param  array $adapters
195
     * @return array
196
     */
197
    public function getAdapters(array $adapters = []): array
0 ignored issues
show
Unused Code introduced by
The parameter $adapters is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
198
    {
199
        if (empty($adapter)) {
0 ignored issues
show
Bug introduced by
The variable $adapter does not exist. Did you mean $adapters?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
200
            return $this->adapter;
201
        } else {
202
            $list = [];
203
            foreach ($adapter as $name) {
204
                if (!$this->hasAdapter($name)) {
205
                    throw new Exception('auth adapter '.$name.' is not registered');
206
                }
207
                $list[$name] = $this->adapter[$name];
208
            }
209
210
            return $list;
211
        }
212
    }
213
214
215
    /**
216
     * Create identity
217
     *
218
     * @param  AdapterInterface $adapter
219
     * @return Identity
220
     */
221
    protected function createIdentity(AdapterInterface $adapter): Identity
222
    {
223
        $map = new $this->attribute_map_class($adapter->getAttributeMap(), $this->logger);
224
        $this->identity = new $this->identity_class($adapter, $map, $this->logger);
225
        return $this->identity;
226
    }
227
228
229
    /**
230
     * Authenticate
231
     *
232
     * @return  bool
233
     */
234
    public function requireOne(): bool
235
    {
236
        $result = false;
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
237
        
238
        foreach ($this->adapter as $name => $adapter) {
239
            try {
240
                if ($adapter->authenticate()) {
241
                    $this->createIdentity($adapter);      
242
 
243
                    $this->logger->info("identity [{$this->identity->getIdentifier()}] authenticated over adapter [{$name}]", [
244
                        'category' => get_class($this)
245
                    ]);
246
                    $_SERVER['REMOTE_USER'] = $this->identity->getIdentifier();
247
                    
248
                    return true;
249
                }
250
            } catch (\Exception $e) {
251
                $this->logger->error("failed authenticate user, unexcepted exception was thrown", [
252
                    'category' => get_class($this),
253
                    'exception'=> $e
254
                ]);
255
            }
256
        
257
            $this->logger->debug("auth adapter [{$name}] failed", [
258
                'category' => get_class($this)
259
            ]);
260
        }
261
        
262
        $this->logger->warning("all authentication adapter have failed", [
263
            'category' => get_class($this)
264
        ]);
265
266
        return false;
267
    }
268
269
270
    /**
271
     * Get identity
272
     *
273
     * @return Identity
274
     */
275
    public function getIdentity(): Identity
276
    {
277
        if (!$this->isAuthenticated()) {
278
            throw new Exception('no valid authentication yet');
279
        } else {
280
            return $this->identity;
281
        }
282
    }
283
284
285
    /**
286
     * Check if valid identity exists
287
     *
288
     * @return bool
289
     */
290
    public function isAuthenticated(): bool
291
    {
292
        return ($this->identity instanceof Identity);
293
    }
294
}
295