Passed
Pull Request — master (#1078)
by Pauli
06:30 queued 03:46
created

AmpacheImageService   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 36
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getToken() 0 9 2
A getUserForToken() 0 12 3
1
<?php declare(strict_types=1);
2
3
/**
4
 * ownCloud - Music app
5
 *
6
 * This file is licensed under the Affero General Public License version 3 or
7
 * later. See the COPYING file.
8
 *
9
 * @author Pauli Järvinen <[email protected]>
10
 * @copyright Pauli Järvinen 2023
11
 */
12
13
namespace OCA\Music\Utility;
14
15
use OCA\Music\AppFramework\Core\Logger;
16
use OCA\Music\Db\AmpacheUserMapper;
17
18
class AmpacheImageService {
19
20
	private $userMapper;
21
	private $logger;
22
23
	public function __construct(
24
			AmpacheUserMapper $userMapper,
25
			Logger $logger) {
26
		$this->userMapper = $userMapper;
27
		$this->logger = $logger;
28
	}
29
30
	public function getToken(string $entityType, int $entityId, int $apiKeyId) : ?string {
31
		$keyHash = $this->userMapper->getPasswordHash($apiKeyId);
32
33
		if ($keyHash !== null) {
34
			$entityHash = \hash('sha256', "$entityType-$entityId-$keyHash");
35
			$truncatedHash = \substr($entityHash, 0, 32);
36
			return (string)$apiKeyId . '-' . $truncatedHash;
37
		} else {
38
			return null;
39
		}
40
	}
41
42
	public function getUserForToken(string $token, string $entityType, int $entityId) : ?string {
43
		$userId = null;
44
		$parts = \explode('-', $token, 2);
45
		if (\count($parts) === 2) {
46
			$apiKeyId = (int)$parts[0];
47
			$correctToken = $this->getToken($entityType, $entityId, $apiKeyId);
48
49
			if ($token === $correctToken) {
50
				$userId = $this->userMapper->getUserId($apiKeyId);
51
			}
52
		}
53
		return $userId;
54
	}
55
56
}