1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
use felicityiiith\OpenIDConnectClient; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Auth Library |
7
|
|
|
*/ |
8
|
|
|
class auth_lib extends Library { |
9
|
|
|
|
10
|
|
|
private static $oidc = false; |
|
|
|
|
11
|
|
|
|
12
|
|
|
private function construct_oidc() { |
13
|
|
|
global $keycloak_cfg; |
14
|
|
|
$oidc = new OpenIDConnectClient($keycloak_cfg['host'], $keycloak_cfg['client_id'], $keycloak_cfg['client_secret']); |
15
|
|
|
$oidc->setCertPath($keycloak_cfg['server_ca_cert']); |
16
|
|
|
return $oidc; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
public function force_authentication() { |
20
|
|
|
if ($this->is_authenticated()) return; |
21
|
|
|
$oidc = $this->construct_oidc(); |
22
|
|
|
$oidc->authenticate(); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function is_authenticated() { |
26
|
|
|
return (bool) $this->get_user(); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function logout() { |
30
|
|
|
$oidc = $this->construct_oidc(); |
31
|
|
|
// XXX: Hack to logout from kong, i.e. unset lua_resty_session cookies |
32
|
|
|
setcookie('session', '', time() - 3600, '/'); |
33
|
|
|
setcookie('session_2', '', time() - 3600, '/'); |
34
|
|
|
setcookie('session_3', '', time() - 3600, '/'); |
35
|
|
|
$oidc->signOut($oidc->getAccessToken(), base_url()); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function get_user() { |
39
|
|
|
$user = $this->get_user_details(); |
40
|
|
|
|
41
|
|
|
if ($user && !empty($user->preferred_username)) { |
42
|
|
|
return $user->preferred_username; |
43
|
|
|
} |
44
|
|
|
return false; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private function admin_details() { |
48
|
|
|
$object = new stdClass(); |
49
|
|
|
$object->preferred_username = "admin"; |
50
|
|
|
return $object; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function get_user_details() { |
54
|
|
|
global $cfg; |
55
|
|
|
if ($cfg['debug']) return $this->admin_details(); |
56
|
|
|
|
57
|
|
|
$oidc = $this->construct_oidc(); |
58
|
|
|
if (!$oidc->getIdToken()) { |
59
|
|
|
return false; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$details = $oidc->requestUserInfo(); |
63
|
|
|
if (isset($details->error)) $oidc->refreshTokens(); |
64
|
|
|
return $oidc->requestUserInfo(); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|