1
|
|
|
<?php |
2
|
|
|
namespace Http; |
3
|
|
|
|
4
|
|
|
use \Psr\Http\Message\ServerRequestInterface as Request; |
5
|
|
|
use \Psr\Http\Message\ResponseInterface as Response; |
6
|
|
|
|
7
|
|
|
require 'vendor/autoload.php'; |
8
|
|
|
|
9
|
|
|
class AuthMiddleware |
10
|
|
|
{ |
11
|
|
|
private function getUserFromSession() |
12
|
|
|
{ |
13
|
|
|
if(\FlipSession::isLoggedIn()) |
14
|
|
|
{ |
15
|
|
|
return \FlipSession::getUser(); |
16
|
|
|
} |
17
|
|
|
return false; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/* |
21
|
|
|
* @SuppressWarnings("Superglobals") |
22
|
|
|
* @SuppressWarnings("StaticAccess") |
23
|
|
|
*/ |
24
|
|
View Code Duplication |
private function getUserFromBasicAuth($header) |
|
|
|
|
25
|
|
|
{ |
26
|
|
|
$auth = \AuthProvider::getInstance(); |
27
|
|
|
$auth->login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); |
28
|
|
|
$user = FlipSession::getUser(); |
29
|
|
|
if($user === false) |
30
|
|
|
{ |
31
|
|
|
$data = substr($header, 6); |
32
|
|
|
$userpass = explode(':', base64_decode($data)); |
33
|
|
|
$user = $auth->getUserByLogin($userpass[0], $userpass[1]); |
34
|
|
|
} |
35
|
|
|
return $user; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/* |
39
|
|
|
* @SuppressWarnings("StaticAccess") |
40
|
|
|
*/ |
41
|
|
|
private function getUserFromToken($header) |
42
|
|
|
{ |
43
|
|
|
$auth = \AuthProvider::getInstance(); |
44
|
|
|
$key = substr($header, 7); |
45
|
|
|
return $auth->getUserByAccessCode($key); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
View Code Duplication |
private function getUserFromHeader($header) |
|
|
|
|
49
|
|
|
{ |
50
|
|
|
if(strncmp($header, 'Basic', 5) == 0) |
51
|
|
|
{ |
52
|
|
|
return $this->getUserFromBasicAuth($header); |
53
|
|
|
} |
54
|
|
|
return $this->getUserFromToken($header); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function __invoke($request, $response, $next) |
58
|
|
|
{ |
59
|
|
|
$auth = $request->getHeader('Authorization'); |
60
|
|
|
if(empty($auth)) |
61
|
|
|
{ |
62
|
|
|
$request = $request->withAttribute('user', $this->getUserFromSession()); |
63
|
|
|
} |
64
|
|
|
else |
65
|
|
|
{ |
66
|
|
|
$request = $request->withAttribute('user', $this->getUserFromHeader($auth)); |
67
|
|
|
} |
68
|
|
|
$response = $next($request, $response); |
69
|
|
|
return $response; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.