Completed
Push — master ( 9b9ca0...f3dbfd )
by Lukas
13:11
created

RateLimitingMiddleware   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 85
Duplicated Lines 12.94 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
dl 11
loc 85
rs 10
c 0
b 0
f 0
wmc 10
lcom 1
cbo 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
B beforeController() 0 24 6
B afterException() 11 26 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2017 Lukas Reschke <[email protected]>
4
 *
5
 * @license GNU AGPL version 3 or any later version
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as
9
 * published by the Free Software Foundation, either version 3 of the
10
 * License, or (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 *
20
 */
21
22
namespace OC\AppFramework\Middleware\Security;
23
24
use OC\AppFramework\Utility\ControllerMethodReflector;
25
use OC\Security\RateLimiting\Exception\RateLimitExceededException;
26
use OC\Security\RateLimiting\Limiter;
27
use OCP\AppFramework\Http\JSONResponse;
28
use OCP\AppFramework\Http\Response;
29
use OCP\AppFramework\Http\TemplateResponse;
30
use OCP\AppFramework\Middleware;
31
use OCP\IRequest;
32
use OCP\IUserSession;
33
34
/**
35
 * Class RateLimitingMiddleware is the middleware responsible for implementing the
36
 * ratelimiting in Nextcloud.
37
 *
38
 * It parses annotations such as:
39
 *
40
 * @UserRateThrottle(limit=5, period=100)
41
 * @AnonRateThrottle(limit=1, period=100)
42
 *
43
 * Those annotations above would mean that logged-in users can access the page 5
44
 * times within 100 seconds, and anonymous users 1 time within 100 seconds. If
45
 * only an AnonRateThrottle is specified that one will also be applied to logged-in
46
 * users.
47
 *
48
 * @package OC\AppFramework\Middleware\Security
49
 */
50
class RateLimitingMiddleware extends Middleware {
51
	/** @var IRequest $request */
52
	private $request;
53
	/** @var IUserSession */
54
	private $userSession;
55
	/** @var ControllerMethodReflector */
56
	private $reflector;
57
	/** @var Limiter */
58
	private $limiter;
59
60
	/**
61
	 * @param IRequest $request
62
	 * @param IUserSession $userSession
63
	 * @param ControllerMethodReflector $reflector
64
	 * @param Limiter $limiter
65
	 */
66
	public function __construct(IRequest $request,
67
								IUserSession $userSession,
68
								ControllerMethodReflector $reflector,
69
								Limiter $limiter) {
70
		$this->request = $request;
71
		$this->userSession = $userSession;
72
		$this->reflector = $reflector;
73
		$this->limiter = $limiter;
74
	}
75
76
	/**
77
	 * {@inheritDoc}
78
	 * @throws RateLimitExceededException
79
	 */
80
	public function beforeController($controller, $methodName) {
81
		parent::beforeController($controller, $methodName);
82
83
		$anonLimit = $this->reflector->getAnnotationParameter('AnonRateThrottle', 'limit');
84
		$anonPeriod = $this->reflector->getAnnotationParameter('AnonRateThrottle', 'period');
85
		$userLimit = $this->reflector->getAnnotationParameter('UserRateThrottle', 'limit');
86
		$userPeriod = $this->reflector->getAnnotationParameter('UserRateThrottle', 'period');
87
		$rateLimitIdentifier = get_class($controller) . '::' . $methodName;
88
		if($userLimit !== '' && $userPeriod !== '' && $this->userSession->isLoggedIn()) {
89
			$this->limiter->registerUserRequest(
90
				$rateLimitIdentifier,
91
				$userLimit,
92
				$userPeriod,
93
				$this->userSession->getUser()
0 ignored issues
show
Bug introduced by
It seems like $this->userSession->getUser() can be null; however, registerUserRequest() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
94
			);
95
		} elseif ($anonLimit !== '' && $anonPeriod !== '') {
96
			$this->limiter->registerAnonRequest(
97
				$rateLimitIdentifier,
98
				$anonLimit,
99
				$anonPeriod,
100
				$this->request->getRemoteAddress()
101
			);
102
		}
103
	}
104
105
	/**
106
	 * {@inheritDoc}
107
	 */
108
	public function afterException($controller, $methodName, \Exception $exception) {
109
		if($exception instanceof RateLimitExceededException) {
110
			if (stripos($this->request->getHeader('Accept'),'html') === false) {
111
				$response = new JSONResponse(
112
					[
113
						'message' => $exception->getMessage(),
114
					],
115
					$exception->getCode()
116
				);
117 View Code Duplication
			} else {
118
					$response = new TemplateResponse(
119
						'core',
120
						'403',
121
							[
122
								'file' => $exception->getMessage()
123
							],
124
						'guest'
125
					);
126
					$response->setStatus($exception->getCode());
127
			}
128
129
			return $response;
130
		}
131
132
		throw $exception;
133
	}
134
}
135