Completed
Push — master ( 4076c0...886762 )
by Morris
122:17 queued 106:43
created

SwiftFactory::auth()   C

Complexity

Conditions 8
Paths 14

Size

Total Lines 29
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 23
nc 14
nop 2
dl 0
loc 29
rs 5.3846
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
/**
4
 * @copyright Copyright (c) 2018 Robin Appelman <[email protected]>
5
 *
6
 * @license GNU AGPL version 3 or any later version
7
 *
8
 * This program is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License as
10
 * published by the Free Software Foundation, either version 3 of the
11
 * License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License
19
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
 *
21
 */
22
23
namespace OC\Files\ObjectStore;
24
25
use GuzzleHttp\Client;
26
use GuzzleHttp\Exception\ClientException;
27
use GuzzleHttp\Exception\ConnectException;
28
use GuzzleHttp\Exception\RequestException;
29
use GuzzleHttp\HandlerStack;
30
use OCP\Files\StorageAuthException;
31
use OCP\Files\StorageNotAvailableException;
32
use OCP\ICache;
33
use OpenStack\Common\Error\BadResponseError;
34
use OpenStack\Common\Auth\Token;
35
use OpenStack\Identity\v2\Service as IdentityV2Service;
36
use OpenStack\Identity\v3\Service as IdentityV3Service;
37
use OpenStack\OpenStack;
38
use OpenStack\Common\Transport\Utils as TransportUtils;
39
use Psr\Http\Message\RequestInterface;
40
use OpenStack\ObjectStore\v1\Models\Container;
41
42
class SwiftFactory {
43
	private $cache;
44
	private $params;
45
	/** @var Container|null */
46
	private $container = null;
47
48
	public function __construct(ICache $cache, array $params) {
49
		$this->cache = $cache;
50
		$this->params = $params;
51
	}
52
53
	private function getCachedToken(string $cacheKey) {
54
		$cachedTokenString = $this->cache->get($cacheKey . '/token');
55
		if ($cachedTokenString) {
56
			return json_decode($cachedTokenString);
57
		} else {
58
			return null;
59
		}
60
	}
61
62
	private function cacheToken(Token $token, string $cacheKey) {
63
		$this->cache->set($cacheKey . '/token', json_encode($token));
64
	}
65
66
	/**
67
	 * @return OpenStack
68
	 * @throws StorageAuthException
69
	 */
70
	private function getClient() {
71
		if (isset($this->params['bucket'])) {
72
			$this->params['container'] = $this->params['bucket'];
73
		}
74
		if (!isset($this->params['container'])) {
75
			$this->params['container'] = 'owncloud';
76
		}
77
		if (!isset($this->params['autocreate'])) {
78
			// should only be true for tests
79
			$this->params['autocreate'] = false;
80
		}
81
		if (isset($this->params['user']) && is_array($this->params['user'])) {
82
			$userName = $this->params['user']['name'];
83
		} else {
84
			if (!isset($this->params['username']) && isset($this->params['user'])) {
85
				$this->params['username'] = $this->params['user'];
86
			}
87
			$userName = $this->params['username'];
88
		}
89
		if (!isset($this->params['tenantName']) && isset($this->params['tenant'])) {
90
			$this->params['tenantName'] = $this->params['tenant'];
91
		}
92
93
		$cacheKey = $userName . '@' . $this->params['url'] . '/' . $this->params['bucket'];
94
		$token = $this->getCachedToken($cacheKey);
95
		$hasToken = is_array($token) && (new \DateTimeImmutable($token['expires_at'])) > (new \DateTimeImmutable('now'));
96
		if ($hasToken) {
97
			$this->params['cachedToken'] = $token;
98
		}
99
100
		$httpClient = new Client([
101
			'base_uri' => TransportUtils::normalizeUrl($this->params['url']),
102
			'handler' => HandlerStack::create()
103
		]);
104
105
		if (isset($this->params['user']) && isset($this->params['user']['name'])) {
106
			return $this->auth(IdentityV3Service::factory($httpClient), $cacheKey);
107
		} else {
108
			return $this->auth(IdentityV2Service::factory($httpClient), $cacheKey);
109
		}
110
	}
111
112
	/**
113
	 * @param IdentityV2Service|IdentityV3Service $authService
114
	 * @param string $cacheKey
115
	 * @return OpenStack
116
	 * @throws StorageAuthException
117
	 */
118
	private function auth($authService, string $cacheKey) {
119
		$this->params['identityService'] = $authService;
120
		$this->params['authUrl'] = $this->params['url'];
121
		$client = new OpenStack($this->params);
122
123
		if (!isset($this->params['cachedToken'])) {
124
			try {
125
				$token = $authService->generateToken($this->params);
126
				$this->cacheToken($token, $cacheKey);
127
			} catch (ConnectException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ConnectException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
128
				throw new StorageAuthException('Failed to connect to keystone, verify the keystone url', $e);
129
			} catch (ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
130
				$statusCode = $e->getResponse()->getStatusCode();
131
				if ($statusCode === 404) {
132
					throw new StorageAuthException('Keystone not found, verify the keystone url', $e);
133
				} else if ($statusCode === 412) {
134
					throw new StorageAuthException('Precondition failed, verify the keystone url', $e);
135
				} else if ($statusCode === 401) {
136
					throw new StorageAuthException('Authentication failed, verify the username, password and possibly tenant', $e);
137
				} else {
138
					throw new StorageAuthException('Unknown error', $e);
139
				}
140
			} catch (RequestException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\RequestException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
141
				throw new StorageAuthException('Connection reset while connecting to keystone, verify the keystone url', $e);
142
			}
143
		}
144
145
		return $client;
146
	}
147
148
	/**
149
	 * @return \OpenStack\ObjectStore\v1\Models\Container
150
	 * @throws StorageAuthException
151
	 * @throws StorageNotAvailableException
152
	 */
153
	public function getContainer() {
154
		if (is_null($this->container)) {
155
			$this->container = $this->createContainer();
156
		}
157
158
		return $this->container;
159
	}
160
161
	/**
162
	 * @return \OpenStack\ObjectStore\v1\Models\Container
163
	 * @throws StorageAuthException
164
	 * @throws StorageNotAvailableException
165
	 */
166
	private function createContainer() {
167
		$client = $this->getClient();
168
		$objectStoreService = $client->objectStoreV1();
169
170
		$autoCreate = isset($this->params['autocreate']) && $this->params['autocreate'] === true;
171
		try {
172
			$container = $objectStoreService->getContainer($this->params['container']);
173
			if ($autoCreate) {
174
				$container->getMetadata();
175
			}
176
			return $container;
177
		} catch (BadResponseError $ex) {
0 ignored issues
show
Bug introduced by
The class OpenStack\Common\Error\BadResponseError does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
178
			// if the container does not exist and autocreate is true try to create the container on the fly
179
			if ($ex->getResponse()->getStatusCode() === 404 && $autoCreate) {
180
				return $objectStoreService->createContainer([
181
					'name' => $this->params['container']
182
				]);
183
			} else {
184
				throw new StorageNotAvailableException('Invalid response while trying to get container info', StorageNotAvailableException::STATUS_ERROR, $e);
185
			}
186
		} catch (ConnectException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ConnectException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
187
			/** @var RequestInterface $request */
188
			$request = $e->getRequest();
189
			$host = $request->getUri()->getHost() . ':' . $request->getUri()->getPort();
190
			\OC::$server->getLogger()->error("Can't connect to object storage server at $host");
191
			throw new StorageNotAvailableException("Can't connect to object storage server at $host", StorageNotAvailableException::STATUS_ERROR, $e);
192
		}
193
	}
194
}
195