|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
/** |
|
4
|
|
|
* Minotaur |
|
5
|
|
|
* |
|
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); you may not |
|
7
|
|
|
* use this file except in compliance with the License. You may obtain a copy of |
|
8
|
|
|
* the License at |
|
9
|
|
|
* |
|
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
|
11
|
|
|
* |
|
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
|
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
|
14
|
|
|
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
|
15
|
|
|
* License for the specific language governing permissions and limitations under |
|
16
|
|
|
* the License. |
|
17
|
|
|
* |
|
18
|
|
|
* @copyright 2015-2017 Appertly |
|
19
|
|
|
* @license Apache-2.0 |
|
20
|
|
|
*/ |
|
21
|
|
|
namespace Minotaur\Route; |
|
22
|
|
|
|
|
23
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
|
24
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
|
25
|
|
|
use Caridea\Auth\Principal; |
|
26
|
|
|
use Aura\Router\Route; |
|
27
|
|
|
use Aura\Router\Rule\RuleInterface; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Aura Router rule to test user is authenticated. |
|
31
|
|
|
*/ |
|
32
|
|
|
class AuthRule implements RuleInterface |
|
33
|
|
|
{ |
|
34
|
|
|
/** |
|
35
|
|
|
* Check if the Request matches the Route. |
|
36
|
|
|
* |
|
37
|
|
|
* @param \Psr\Http\Message\ServerRequestInterface $request The HTTP request |
|
38
|
|
|
* @param \Aura\Router\Route $route The route. |
|
39
|
|
|
* @return bool `true` on success, `false` on failure |
|
40
|
|
|
*/ |
|
41
|
3 |
|
public function __invoke(Request $request, Route $route): bool |
|
42
|
|
|
{ |
|
43
|
3 |
|
return !$route->auth || !$this->getPrincipal($request)->isAnonymous(); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* Gets the stored principal, or the anonymous user if none was found. |
|
48
|
|
|
* |
|
49
|
|
|
* @param \Psr\Http\Message\ServerRequestInterface $request The HTTP request |
|
50
|
|
|
* @return \Caridea\Auth\Principal The authenticated principal |
|
51
|
|
|
*/ |
|
52
|
2 |
|
protected function getPrincipal(Request $request): Principal |
|
53
|
|
|
{ |
|
54
|
2 |
|
$principal = $request->getAttribute('principal', Principal::getAnonymous()); |
|
55
|
2 |
|
if (!($principal instanceof Principal)) { |
|
56
|
|
|
throw new \UnexpectedValueException("Type mismatch: principal"); |
|
57
|
|
|
} |
|
58
|
2 |
|
return $principal; |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|