Passed
Push — master ( 1bf36a...3f521f )
by Pauli
02:26
created

AmpacheMiddleware::errorResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 7
ccs 0
cts 5
cp 0
crap 2
rs 10
1
<?php
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 Morris Jobke <[email protected]>
10
 * @author Pauli Järvinen <[email protected]>
11
 * @copyright Morris Jobke 2013, 2014
12
 * @copyright Pauli Järvinen 2018 - 2020
13
 */
14
15
namespace OCA\Music\Middleware;
16
17
use \OCP\IRequest;
0 ignored issues
show
Bug introduced by
The type OCP\IRequest was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use \OCP\AppFramework\Middleware;
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\Middleware was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
20
use \OCA\Music\AppFramework\BusinessLayer\BusinessLayerException;
21
use \OCA\Music\AppFramework\Core\Logger;
22
use \OCA\Music\Controller\AmpacheController;
23
use \OCA\Music\Db\AmpacheSessionMapper;
24
use \OCA\Music\Utility\AmpacheUser;
25
26
/**
27
 * Checks the authentication on each Ampache API call before the
28
 * request is allowed to be passed to AmpacheController.
29
 * Map identified exceptions from the controller to proper Ampache error results.
30
 */
31
class AmpacheMiddleware extends Middleware {
32
	private $appname;
0 ignored issues
show
introduced by
The private property $appname is not used, and could be removed.
Loading history...
33
	private $request;
34
	private $ampacheSessionMapper;
35
	private $ampacheUser;
36
	private $logger;
37
38
	/**
39
	 * @param Request $request an instance of the request
0 ignored issues
show
Bug introduced by
The type OCA\Music\Middleware\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
40
	 */
41
	public function __construct(
42
			IRequest $request, AmpacheSessionMapper $ampacheSessionMapper,
43
			AmpacheUser $ampacheUser, Logger $logger) {
44
		$this->request = $request;
45
		$this->ampacheSessionMapper = $ampacheSessionMapper;
46
		$this->ampacheUser = $ampacheUser; // used to share user info with controller
47
		$this->logger = $logger;
48
	}
49
50
	/**
51
	 * This runs all the security checks before a method call. The
52
	 * security checks are determined by inspecting the controller method
53
	 * annotations
54
	 * @param Controller $controller the controller that is being called
0 ignored issues
show
Bug introduced by
The type OCA\Music\Middleware\Controller was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
55
	 * @param string $methodName the name of the method
56
	 * @throws AmpacheException when a security check fails
57
	 */
58
	public function beforeController($controller, $methodName) {
59
60
		if ($controller instanceof AmpacheController) {
61
62
			if ($methodName === 'jsonApi') {
63
				$controller->setJsonMode(true);
64
			}
65
66
			// don't try to authenticate for the handshake request
67
			if ($this->request['action'] !== 'handshake') {
68
				$this->checkAuthentication();
69
			}
70
		}
71
	}
72
73
	private function checkAuthentication() {
74
		$token = $this->request['auth'] ?: $this->request['ssid'] ?: null;
75
76
		if (empty($token)) {
77
			// ping is allowed without a session (but if session token is passed, then it has to be valid)
78
			if ($this->request['action'] !== 'ping') {
79
				throw new AmpacheException('Invalid Login - session token missing', 401);
80
			}
81
		}
82
		else {
83
			$user = $this->ampacheSessionMapper->findByToken($token);
84
			if ($user !== false && \array_key_exists('user_id', $user)) {
85
				$this->ampacheUser->setUserId($user['user_id']);
86
			} else {
87
				throw new AmpacheException('Invalid Login - invalid session token', 401);
88
			}
89
		}
90
	}
91
92
	/**
93
	 * If an AmpacheException is being caught, the appropiate ampache
94
	 * exception response is rendered
95
	 * @param Controller $controller the controller that is being called
96
	 * @param string $methodName the name of the method that will be called on
97
	 *                           the controller
98
	 * @param \Exception $exception the thrown exception
99
	 * @throws \Exception the passed in exception if it wasn't handled
100
	 * @return Response a Response object if the exception was handled
0 ignored issues
show
Bug introduced by
The type OCA\Music\Middleware\Response was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
101
	 */
102
	public function afterException($controller, $methodName, \Exception $exception) {
103
		if ($controller instanceof AmpacheController) {
104
			if ($exception instanceof AmpacheException) {
105
				return $this->errorResponse($controller, $exception->getCode(), $exception->getMessage());
106
			}
107
			elseif ($exception instanceof BusinessLayerException) {
108
				return $this->errorResponse($controller, 400, 'Entity not found');
109
			}
110
		}
111
		throw $exception;
112
	}
113
114
	private function errorResponse(AmpacheController $controller, $code, $message) {
115
		$this->logger->log($message, 'debug');
116
117
		return $controller->ampacheResponse([
118
			'error' => [
119
				'code' => $code,
120
				'value' => $message
121
			]
122
		]);
123
	}
124
}
125