Passed
Push — master ( 239f94...e6897d )
by Medianet
02:33
created

AuthManager::getToken()   C

Complexity

Conditions 12
Paths 7

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 12
eloc 16
c 3
b 0
f 0
nc 7
nop 1
dl 0
loc 31
rs 6.9666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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.session')) {
32
                if (session()->has(config('p-connector.session_name'))) {
33
                    foreach (session()->get(config('p-connector.session_name')) as $key => $value) {
34
                        if ($value['gateway_profile'] === $profile) {
35
                            $value['token'] = null;
36
                        }
37
                    };
38
                }
39
                session()->save();
40
            } else {
41
                app('db')->table(config('p-connector.table', 'p_connector'))->updateOrInsert(
42
                    ['gateway_profile' => $profile],
43
                    ['token' => null, 'updated_at' => date('Y-m-d H:i:s')]
44
                );
45
            }
46
        }
47
    }
48
49
    /**
50
     * Get the authentication header for a profile.
51
     *
52
     * @param  string  $profile
53
     * @return array
54
     */
55
    public function getAuthenticationHeader($profile)
56
    {
57
        $token = $this->getToken($profile);
58
        $authMethod = config('p-connector.profiles.' . $profile . '.auth.auth_method', config('p-connector.auth.auth_method', 'basic'));
59
60
        switch ($authMethod) {
61
            case 'api_key':
62
                return [config('p-connector.profiles.' . $profile . '.auth.api_key', config(
63
                    'p-connector.auth.api_key',
64
                    'X-AUTH-TOKEN'
65
                )) => $token];
66
            case 'basic':
67
                return ['Authorization' => 'Basic ' . $token];
68
            case 'bearer':
69
                return ['Authorization' => 'Bearer ' . $token];
70
71
            default:
72
                throw new InvalidArgumentException('Invalid method "' . $authMethod . '".');
73
        }
74
    }
75
76
    /**
77
     * get access token from database.
78
     *
79
     * @return string
80
     */
81
    private function getToken($profile)
82
    {
83
        if ('basic' === config('p-connector.profiles.' . $profile . '.auth.auth_method', config('p-connector.auth.auth_method', 'basic'))) {
84
            $auth = config('p-connector.profiles.' . $profile . '.auth.credentials', config('p-connector.auth.credentials', []));
85
            if (!array_key_exists('username', $auth) || !array_key_exists('password', $auth)) {
86
                throw new InvalidArgumentException("config('p-connector.profiles.$profile.auth.credentials') array must have a username and password keys.");
87
            }
88
89
            return base64_encode($auth['username'] . ':' . $auth['password']);
90
        }
91
92
        if (config('p-connector.session')) {
93
            if (session()->has(config('p-connector.session_name'))) {
94
                foreach (session()->get(config('p-connector.session_name')) as $token) {
95
                    if ($token['gateway_profile'] === $profile) {
96
                        if ($token && !empty($token->token)) {
97
                            return $token->token;
98
                        }
99
                    }
100
                };
101
            }
102
        } else {
103
            $token = app('db')->table(config('p-connector.table', 'p_connector'))->where('gateway_profile', $profile)->first();
104
105
            if ($token && !empty($token->token)) {
106
                return $token->token;
107
            }
108
        }
109
110
111
        return $this->loginToGateway($profile);
112
    }
113
114
    /**
115
     * Send request to login to the gateway, save the received token and return it.
116
     *
117
     * @return string
118
     */
119
    private function loginToGateway($profile)
120
    {
121
        $result = $this->httpClient->send(
122
            build_url(config('p-connector.profiles.' . $profile . '.auth.login_path', config('p-connector.auth.login_path', 'login')), $profile),
123
            config('p-connector.profiles.' . $profile . '.auth.credentials', config('p-connector.auth.credentials', [])),
124
            strtoupper(config('p-connector.profiles.' . $profile . '.auth.login_http_method', config('p-connector.auth.login_http_method', 'POST'))),
125
            $profile,
126
            false
127
        );
128
129
        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', [])))) {
130
            $token = _get(json_decode($result['response']['body']), explode('.', config('p-connector.profiles.' . $profile . '.auth.token_path', config('p-connector.auth.token_path', 'token'))), '');
131
            if ('string' !== gettype($token)) {
132
                throw new InvalidArgumentException('The returned token is not of type string (type: "' . gettype($token) . '").');
133
            }
134
135
            if (config('p-connector.session')) {
136
                $data = [
137
                    'gateway_profile' => $profile,
138
                    'token' => $token
139
                ];
140
141
                if (session()->has(config('p-connector.session_name'))) {
142
                    $index = -1;
143
                    foreach (session()->get(config('p-connector.session_name')) as $key => $value) {
144
                        if ($value['gateway_profile'] === $profile) {
145
                            $index = $key;
146
                            break;
147
                        }
148
                    };
149
                    if ($index != -1) {
150
                        session()->get(config('p-connector.session_name'))[$index] = $token;
151
                    } else {
152
                        session()->push(config('p-connector.session_name'), $data);
153
                    }
154
                } else {
155
                    session()->put([
156
                        config('p-connector.session_name') => [$data]
157
                    ]);
158
                }
159
160
                session()->save();
161
            } else {
162
                app('db')->table(config('p-connector.table', 'p_connector'))->updateOrInsert(
163
                    ['gateway_profile' => $profile],
164
                    ['token' => $token, 'updated_at' => date('Y-m-d H:i:s')]
165
                );
166
            }
167
168
            return $token;
169
        }
170
171
        return null;
172
    }
173
}