|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace hiapi\Core\Http\Psr15\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use hiapi\exceptions\NotAuthenticatedException; |
|
6
|
|
|
use hiapi\legacy\lib\mrdpAuth; |
|
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
9
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
10
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
11
|
|
|
|
|
12
|
|
|
class AuthMiddleware implements MiddlewareInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var mrdpAuth |
|
16
|
|
|
*/ |
|
17
|
|
|
private $auth; |
|
18
|
|
|
|
|
19
|
|
|
|
|
20
|
|
|
public function __construct(mrdpAuth $auth) |
|
21
|
|
|
{ |
|
22
|
|
|
$this->auth = $auth; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @inheritDoc |
|
27
|
|
|
*/ |
|
28
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
29
|
|
|
{ |
|
30
|
|
|
$this->passIp($request); |
|
31
|
|
|
if ($this->login($request)) { |
|
32
|
|
|
return $handler->handle($request); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
throw new NotAuthenticatedException($this->auth->get('error')); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
private function login(ServerRequestInterface $request): bool |
|
39
|
|
|
{ |
|
40
|
|
|
$token = $this->getAccessToken($request); |
|
41
|
|
|
if ($token) { |
|
42
|
|
|
return $this->auth->loginOauth2($token, ''); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
$login = $this->getParam($request, 'auth_login'); |
|
46
|
|
|
if ($login) { |
|
47
|
|
|
return $this->auth->loginPasswd($login, $this->getParam($request, 'auth_password')); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
return $this->auth->checkLite(); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
private function passIp($request): void |
|
54
|
|
|
{ |
|
55
|
|
|
$ip = $request->getAttribute(ClientIpMiddleware::ATTRIBUTE_NAME); |
|
56
|
|
|
if (!empty($ip)) { |
|
57
|
|
|
$this->auth->set('ip', $ip); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
private function getAccessToken(ServerRequestInterface $request): ?string |
|
62
|
|
|
{ |
|
63
|
|
|
$header = $request->getHeader('Authorization'); |
|
64
|
|
|
if (preg_match('/^Bearer\s+([a-fA-F0-9]{30,50})$/', $header, $matches)) { |
|
65
|
|
|
return $matches[1]; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
return $this->getParam($request, 'access_token'); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
public function getParam(ServerRequestInterface $request, string $name): ?string |
|
72
|
|
|
{ |
|
73
|
|
|
return $request->getParsedBody()[$name] ?? $request->getQueryParams()[$name] ?? null; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|