Passed
Push — master ( 15dbbb...1bbd90 )
by Medianet
15:12 queued 12:36
created

AuthManager::getAuthenticationHeader()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
cc 4
eloc 14
c 4
b 1
f 0
nc 4
nop 1
dl 0
loc 18
rs 9.7998
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 => $data]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $data seems to be never defined.
Loading history...
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
        );
143
144
        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', [])))) {
145
            $token = _get(json_decode($result['response']['body']), explode('.', config('p-connector.profiles.'.$profile.'.auth.token_path', config('p-connector.auth.token_path', 'token'))), '');
146
            if ('string' !== gettype($token)) {
147
                throw new InvalidArgumentException('The returned token is not of type string (type: "'.gettype($token).'").');
148
            }
149
150
            if (config('p-connector.profiles.'.$profile.'.session')) {
151
                $data = [
152
                    'gateway_profile' => $profile,
153
                    'token' => $token,
154
                ];
155
156
                session()->put(['p-connector.session_'.$profile => $data]);
157
158
                session()->save();
159
            } elseif (config('p-connector.session')) {
160
                $data = [
161
                    'gateway_profile' => $profile,
162
                    'token' => $token,
163
                ];
164
165
                if (session()->has(config('p-connector.session_name'))) {
166
                    $index = -1;
167
                    foreach (session()->get(config('p-connector.session_name')) as $key => $value) {
168
                        if ($value['gateway_profile'] === $profile) {
169
                            $index = $key;
170
                            break;
171
                        }
172
                    }
173
                    if ($index != -1) {
174
                        session()->get(config('p-connector.session_name'))[$index] = $token;
175
                    } else {
176
                        session()->push(config('p-connector.session_name'), $data);
177
                    }
178
                } else {
179
                    session()->put([
180
                        config('p-connector.session_name') => [$data],
181
                    ]);
182
                }
183
184
                session()->save();
185
            } else {
186
                app('db')->table(config('p-connector.table', 'p_connector'))->updateOrInsert(
187
                    ['gateway_profile' => $profile],
188
                    ['token' => $token, 'updated_at' => date('Y-m-d H:i:s')]
189
                );
190
            }
191
192
            return $token;
193
        }
194
195
        return null;
196
    }
197
}
198