auth_lib   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 30
dl 0
loc 57
rs 10
c 4
b 0
f 0
wmc 13

7 Methods

Rating   Name   Duplication   Size   Complexity  
A get_user() 0 7 3
A construct_oidc() 0 5 1
A force_authentication() 0 4 2
A logout() 0 7 1
A admin_details() 0 4 1
A get_user_details() 0 12 4
A is_authenticated() 0 2 1
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;
0 ignored issues
show
introduced by
The private property $oidc is not used, and could be removed.
Loading history...
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