AuthManager   A
last analyzed

Complexity

Total Complexity 39

Size/Duplication

Total Lines 190
Duplicated Lines 0 %

Importance

Changes 10
Bugs 2 Features 0
Metric Value
eloc 97
c 10
b 2
f 0
dl 0
loc 190
rs 9.28
wmc 39

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getAuthenticationHeader() 0 18 4
B deleteTokenFor() 0 24 8
C getToken() 0 38 16
B loginToGateway() 0 63 10
1
<?php
2
3
namespace MedianetDev\PConnector;
4
5
use InvalidArgumentException;
6
7
class AuthManager
8
{
9
    /**
10
     * @var \MedianetDev\PConnector\Contracts\Http
11
     *
12
     * The http client
13
     */
14
    private $httpClient;
15
16
    public function __construct()
17
    {
18
        $httpClient = config('p-connector.http_client');
19
        $this->httpClient = new $httpClient(false);
20
    }
21
22
    /**
23
     * Delete token for a profile.
24
     *
25
     * @param  string  $profile
26
     * @return void
27
     */
28
    public static function deleteTokenFor($profile)
29
    {
30
        if ('basic' !== config('p-connector.profiles.'.$profile.'.auth.auth_method', config('p-connector.auth.auth_method', 'basic'))) {
31
            if (config('p-connector.profiles.'.$profile.'.session')) {
32
                if (session()->has('p-connector.session_'.$profile)) {
33
                    $value = session()->get('p-connector.session_'.$profile);
34
                    $value['token'] = null;
35
36
                    session()->put(['p-connector.session_'.$profile => $value]);
37
                }
38
                session()->save();
39
            } elseif (config('p-connector.session')) {
40
                if (session()->has(config('p-connector.session_name'))) {
41
                    foreach (session()->get(config('p-connector.session_name')) as $key => $value) {
42
                        if ($value['gateway_profile'] === $profile) {
43
                            $value['token'] = null;
44
                        }
45
                    }
46
                }
47
                session()->save();
48
            } else {
49
                app('db')->table(config('p-connector.table', 'p_connector'))->updateOrInsert(
50
                    ['gateway_profile' => $profile],
51
                    ['token' => null, 'updated_at' => date('Y-m-d H:i:s')]
52
                );
53
            }
54
        }
55
    }
56
57
    /**
58
     * Get the authentication header for a profile.
59
     *
60
     * @param  string  $profile
61
     * @return array
62
     */
63
    public function getAuthenticationHeader($profile)
64
    {
65
        $token = $this->getToken($profile);
66
        $authMethod = config('p-connector.profiles.'.$profile.'.auth.auth_method', config('p-connector.auth.auth_method', 'basic'));
67
68
        switch ($authMethod) {
69
            case 'api_key':
70
                return [config('p-connector.profiles.'.$profile.'.auth.api_key', config(
71
                    'p-connector.auth.api_key',
72
                    'X-AUTH-TOKEN'
73
                )) => $token];
74
            case 'basic':
75
                return ['Authorization' => 'Basic '.$token];
76
            case 'bearer':
77
                return ['Authorization' => 'Bearer '.$token];
78
79
            default:
80
                throw new InvalidArgumentException('Invalid method "'.$authMethod.'".');
81
        }
82
    }
83
84
    /**
85
     * get access token from database.
86
     *
87
     * @return string
88
     */
89
    private function getToken($profile)
90
    {
91
        if ('basic' === config('p-connector.profiles.'.$profile.'.auth.auth_method', config('p-connector.auth.auth_method', 'basic'))) {
92
            $auth = config('p-connector.profiles.'.$profile.'.auth.credentials', config('p-connector.auth.credentials', []));
93
            if (! array_key_exists('username', $auth) || ! array_key_exists('password', $auth)) {
94
                throw new InvalidArgumentException("config('p-connector.profiles.$profile.auth.credentials') array must have a username and password keys.");
95
            }
96
97
            return base64_encode($auth['username'].':'.$auth['password']);
98
        }
99
100
        if (config('p-connector.profiles.'.$profile.'.session')) {
101
            if (session()->has('p-connector.session_'.$profile)) {
102
                $token = session()->get('p-connector.session_'.$profile);
103
104
                if ($token && ! empty($token['token'])) {
105
                    return $token['token'];
106
                }
107
            }
108
        } elseif (config('p-connector.session')) {
109
            if (session()->has(config('p-connector.session_name'))) {
110
                foreach (session()->get(config('p-connector.session_name')) as $token) {
111
                    if ($token['gateway_profile'] === $profile) {
112
                        if ($token && ! empty($token['token'])) {
113
                            return $token['token'];
114
                        }
115
                    }
116
                }
117
            }
118
        } else {
119
            $token = app('db')->table(config('p-connector.table', 'p_connector'))->where('gateway_profile', $profile)->first();
120
121
            if ($token && ! empty($token->token)) {
122
                return $token->token;
123
            }
124
        }
125
126
        return $this->loginToGateway($profile);
127
    }
128
129
    /**
130
     * Send request to login to the gateway, save the received token and return it.
131
     *
132
     * @return string
133
     */
134
    private function loginToGateway($profile)
135
    {
136
        $result = $this->httpClient->send(
137
            build_url(config('p-connector.profiles.'.$profile.'.auth.login_path', config('p-connector.auth.login_path', 'login')), $profile),
138
            config('p-connector.profiles.'.$profile.'.auth.credentials', config('p-connector.auth.credentials', [])),
139
            strtoupper(config('p-connector.profiles.'.$profile.'.auth.login_http_method', config('p-connector.auth.login_http_method', 'POST'))),
140
            $profile,
141
            false,
142
            config('p-connector.profiles.'.$profile.'.auth.headers', config('p-connector.auth.headers', [])),
143
        );
144
145
        if ($result['status'] && in_array($result['response']['status_code'], config('p-connector.profiles.'.$profile.'.auth.success_login_code', config('p-connector.auth.success_login_code', [])))) {
146
            $token = _get(json_decode($result['response']['body']), explode('.', config('p-connector.profiles.'.$profile.'.auth.token_path', config('p-connector.auth.token_path', 'token'))), '');
147
            if ('string' !== gettype($token)) {
148
                throw new InvalidArgumentException('The returned token is not of type string (type: "'.gettype($token).'").');
149
            }
150
151
            if (config('p-connector.profiles.'.$profile.'.session')) {
152
                $data = [
153
                    'gateway_profile' => $profile,
154
                    'token' => $token,
155
                ];
156
157
                session()->put(['p-connector.session_'.$profile => $data]);
158
159
                session()->save();
160
            } elseif (config('p-connector.session')) {
161
                $data = [
162
                    'gateway_profile' => $profile,
163
                    'token' => $token,
164
                ];
165
166
                if (session()->has(config('p-connector.session_name'))) {
167
                    $index = -1;
168
                    foreach (session()->get(config('p-connector.session_name')) as $key => $value) {
169
                        if ($value['gateway_profile'] === $profile) {
170
                            $index = $key;
171
                            break;
172
                        }
173
                    }
174
                    if ($index != -1) {
175
                        session()->get(config('p-connector.session_name'))[$index] = $token;
176
                    } else {
177
                        session()->push(config('p-connector.session_name'), $data);
178
                    }
179
                } else {
180
                    session()->put([
181
                        config('p-connector.session_name') => [$data],
182
                    ]);
183
                }
184
185
                session()->save();
186
            } else {
187
                app('db')->table(config('p-connector.table', 'p_connector'))->updateOrInsert(
188
                    ['gateway_profile' => $profile],
189
                    ['token' => $token, 'updated_at' => date('Y-m-d H:i:s')]
190
                );
191
            }
192
193
            return $token;
194
        }
195
196
        return null;
197
    }
198
}
199