Completed
Pull Request — master (#4336)
by Lukas
23:47 queued 09:54
created
lib/private/AppFramework/Utility/ControllerMethodReflector.php 1 patch
Indentation   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -32,102 +32,102 @@
 block discarded – undo
32 32
  * Reads and parses annotations from doc comments
33 33
  */
34 34
 class ControllerMethodReflector implements IControllerMethodReflector {
35
-	public $annotations = [];
36
-	private $types = [];
37
-	private $parameters = [];
35
+    public $annotations = [];
36
+    private $types = [];
37
+    private $parameters = [];
38 38
 
39
-	/**
40
-	 * @param object $object an object or classname
41
-	 * @param string $method the method which we want to inspect
42
-	 */
43
-	public function reflect($object, $method){
44
-		$reflection = new \ReflectionMethod($object, $method);
45
-		$docs = $reflection->getDocComment();
39
+    /**
40
+     * @param object $object an object or classname
41
+     * @param string $method the method which we want to inspect
42
+     */
43
+    public function reflect($object, $method){
44
+        $reflection = new \ReflectionMethod($object, $method);
45
+        $docs = $reflection->getDocComment();
46 46
 
47
-		// extract everything prefixed by @ and first letter uppercase
48
-		preg_match_all('/^\h+\*\h+@(?P<annotation>[A-Z]\w+)((?P<parameter>.*))?$/m', $docs, $matches);
49
-		foreach($matches['annotation'] as $key => $annontation) {
50
-			$annotationValue = $matches['parameter'][$key];
51
-			if(isset($annotationValue[0]) && $annotationValue[0] === '(' && $annotationValue[strlen($annotationValue) - 1] === ')') {
52
-				$cutString = substr($annotationValue, 1, -1);
53
-				$cutString = str_replace(' ', '', $cutString);
54
-				$splittedArray = explode(',', $cutString);
55
-				foreach($splittedArray as $annotationValues) {
56
-					list($key, $value) = explode('=', $annotationValues);
57
-					$this->annotations[$annontation][$key] = $value;
58
-				}
59
-				continue;
60
-			}
47
+        // extract everything prefixed by @ and first letter uppercase
48
+        preg_match_all('/^\h+\*\h+@(?P<annotation>[A-Z]\w+)((?P<parameter>.*))?$/m', $docs, $matches);
49
+        foreach($matches['annotation'] as $key => $annontation) {
50
+            $annotationValue = $matches['parameter'][$key];
51
+            if(isset($annotationValue[0]) && $annotationValue[0] === '(' && $annotationValue[strlen($annotationValue) - 1] === ')') {
52
+                $cutString = substr($annotationValue, 1, -1);
53
+                $cutString = str_replace(' ', '', $cutString);
54
+                $splittedArray = explode(',', $cutString);
55
+                foreach($splittedArray as $annotationValues) {
56
+                    list($key, $value) = explode('=', $annotationValues);
57
+                    $this->annotations[$annontation][$key] = $value;
58
+                }
59
+                continue;
60
+            }
61 61
 
62
-			$this->annotations[$annontation] = [$annotationValue];
63
-		}
62
+            $this->annotations[$annontation] = [$annotationValue];
63
+        }
64 64
 
65
-		// extract type parameter information
66
-		preg_match_all('/@param\h+(?P<type>\w+)\h+\$(?P<var>\w+)/', $docs, $matches);
67
-		$this->types = array_combine($matches['var'], $matches['type']);
65
+        // extract type parameter information
66
+        preg_match_all('/@param\h+(?P<type>\w+)\h+\$(?P<var>\w+)/', $docs, $matches);
67
+        $this->types = array_combine($matches['var'], $matches['type']);
68 68
 
69
-		foreach ($reflection->getParameters() as $param) {
70
-			// extract type information from PHP 7 scalar types and prefer them
71
-			// over phpdoc annotations
72
-			if (method_exists($param, 'getType')) {
73
-				$type = $param->getType();
74
-				if ($type !== null) {
75
-					$this->types[$param->getName()] = (string) $type;
76
-				}
77
-			}
69
+        foreach ($reflection->getParameters() as $param) {
70
+            // extract type information from PHP 7 scalar types and prefer them
71
+            // over phpdoc annotations
72
+            if (method_exists($param, 'getType')) {
73
+                $type = $param->getType();
74
+                if ($type !== null) {
75
+                    $this->types[$param->getName()] = (string) $type;
76
+                }
77
+            }
78 78
 
79
-			if($param->isOptional()) {
80
-				$default = $param->getDefaultValue();
81
-			} else {
82
-				$default = null;
83
-			}
84
-			$this->parameters[$param->name] = $default;
85
-		}
86
-	}
79
+            if($param->isOptional()) {
80
+                $default = $param->getDefaultValue();
81
+            } else {
82
+                $default = null;
83
+            }
84
+            $this->parameters[$param->name] = $default;
85
+        }
86
+    }
87 87
 
88
-	/**
89
-	 * Inspects the PHPDoc parameters for types
90
-	 * @param string $parameter the parameter whose type comments should be
91
-	 * parsed
92
-	 * @return string|null type in the type parameters (@param int $something)
93
-	 * would return int or null if not existing
94
-	 */
95
-	public function getType($parameter) {
96
-		if(array_key_exists($parameter, $this->types)) {
97
-			return $this->types[$parameter];
98
-		} else {
99
-			return null;
100
-		}
101
-	}
88
+    /**
89
+     * Inspects the PHPDoc parameters for types
90
+     * @param string $parameter the parameter whose type comments should be
91
+     * parsed
92
+     * @return string|null type in the type parameters (@param int $something)
93
+     * would return int or null if not existing
94
+     */
95
+    public function getType($parameter) {
96
+        if(array_key_exists($parameter, $this->types)) {
97
+            return $this->types[$parameter];
98
+        } else {
99
+            return null;
100
+        }
101
+    }
102 102
 
103
-	/**
104
-	 * @return array the arguments of the method with key => default value
105
-	 */
106
-	public function getParameters() {
107
-		return $this->parameters;
108
-	}
103
+    /**
104
+     * @return array the arguments of the method with key => default value
105
+     */
106
+    public function getParameters() {
107
+        return $this->parameters;
108
+    }
109 109
 
110
-	/**
111
-	 * Check if a method contains an annotation
112
-	 * @param string $name the name of the annotation
113
-	 * @return bool true if the annotation is found
114
-	 */
115
-	public function hasAnnotation($name) {
116
-		return array_key_exists($name, $this->annotations);
117
-	}
110
+    /**
111
+     * Check if a method contains an annotation
112
+     * @param string $name the name of the annotation
113
+     * @return bool true if the annotation is found
114
+     */
115
+    public function hasAnnotation($name) {
116
+        return array_key_exists($name, $this->annotations);
117
+    }
118 118
 
119
-	/**
120
-	 * Get optional annotation parameter by key
121
-	 *
122
-	 * @param string $name the name of the annotation
123
-	 * @param string $key the string of the annotation
124
-	 * @return string
125
-	 */
126
-	public function getAnnotationParameter($name, $key) {
127
-		if(isset($this->annotations[$name][$key])) {
128
-			return $this->annotations[$name][$key];
129
-		}
119
+    /**
120
+     * Get optional annotation parameter by key
121
+     *
122
+     * @param string $name the name of the annotation
123
+     * @param string $key the string of the annotation
124
+     * @return string
125
+     */
126
+    public function getAnnotationParameter($name, $key) {
127
+        if(isset($this->annotations[$name][$key])) {
128
+            return $this->annotations[$name][$key];
129
+        }
130 130
 
131
-		return '';
132
-	}
131
+        return '';
132
+    }
133 133
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php 1 patch
Indentation   +190 added lines, -190 removed lines patch added patch discarded remove patch
@@ -64,219 +64,219 @@
 block discarded – undo
64 64
  * check fails
65 65
  */
66 66
 class SecurityMiddleware extends Middleware {
67
-	/** @var INavigationManager */
68
-	private $navigationManager;
69
-	/** @var IRequest */
70
-	private $request;
71
-	/** @var ControllerMethodReflector */
72
-	private $reflector;
73
-	/** @var string */
74
-	private $appName;
75
-	/** @var IURLGenerator */
76
-	private $urlGenerator;
77
-	/** @var ILogger */
78
-	private $logger;
79
-	/** @var ISession */
80
-	private $session;
81
-	/** @var bool */
82
-	private $isLoggedIn;
83
-	/** @var bool */
84
-	private $isAdminUser;
85
-	/** @var ContentSecurityPolicyManager */
86
-	private $contentSecurityPolicyManager;
87
-	/** @var CsrfTokenManager */
88
-	private $csrfTokenManager;
89
-	/** @var ContentSecurityPolicyNonceManager */
90
-	private $cspNonceManager;
91
-	/** @var Throttler */
92
-	private $throttler;
67
+    /** @var INavigationManager */
68
+    private $navigationManager;
69
+    /** @var IRequest */
70
+    private $request;
71
+    /** @var ControllerMethodReflector */
72
+    private $reflector;
73
+    /** @var string */
74
+    private $appName;
75
+    /** @var IURLGenerator */
76
+    private $urlGenerator;
77
+    /** @var ILogger */
78
+    private $logger;
79
+    /** @var ISession */
80
+    private $session;
81
+    /** @var bool */
82
+    private $isLoggedIn;
83
+    /** @var bool */
84
+    private $isAdminUser;
85
+    /** @var ContentSecurityPolicyManager */
86
+    private $contentSecurityPolicyManager;
87
+    /** @var CsrfTokenManager */
88
+    private $csrfTokenManager;
89
+    /** @var ContentSecurityPolicyNonceManager */
90
+    private $cspNonceManager;
91
+    /** @var Throttler */
92
+    private $throttler;
93 93
 
94
-	/**
95
-	 * @param IRequest $request
96
-	 * @param ControllerMethodReflector $reflector
97
-	 * @param INavigationManager $navigationManager
98
-	 * @param IURLGenerator $urlGenerator
99
-	 * @param ILogger $logger
100
-	 * @param ISession $session
101
-	 * @param string $appName
102
-	 * @param bool $isLoggedIn
103
-	 * @param bool $isAdminUser
104
-	 * @param ContentSecurityPolicyManager $contentSecurityPolicyManager
105
-	 * @param CSRFTokenManager $csrfTokenManager
106
-	 * @param ContentSecurityPolicyNonceManager $cspNonceManager
107
-	 * @param Throttler $throttler
108
-	 */
109
-	public function __construct(IRequest $request,
110
-								ControllerMethodReflector $reflector,
111
-								INavigationManager $navigationManager,
112
-								IURLGenerator $urlGenerator,
113
-								ILogger $logger,
114
-								ISession $session,
115
-								$appName,
116
-								$isLoggedIn,
117
-								$isAdminUser,
118
-								ContentSecurityPolicyManager $contentSecurityPolicyManager,
119
-								CsrfTokenManager $csrfTokenManager,
120
-								ContentSecurityPolicyNonceManager $cspNonceManager,
121
-								Throttler $throttler) {
122
-		$this->navigationManager = $navigationManager;
123
-		$this->request = $request;
124
-		$this->reflector = $reflector;
125
-		$this->appName = $appName;
126
-		$this->urlGenerator = $urlGenerator;
127
-		$this->logger = $logger;
128
-		$this->session = $session;
129
-		$this->isLoggedIn = $isLoggedIn;
130
-		$this->isAdminUser = $isAdminUser;
131
-		$this->contentSecurityPolicyManager = $contentSecurityPolicyManager;
132
-		$this->csrfTokenManager = $csrfTokenManager;
133
-		$this->cspNonceManager = $cspNonceManager;
134
-		$this->throttler = $throttler;
135
-	}
94
+    /**
95
+     * @param IRequest $request
96
+     * @param ControllerMethodReflector $reflector
97
+     * @param INavigationManager $navigationManager
98
+     * @param IURLGenerator $urlGenerator
99
+     * @param ILogger $logger
100
+     * @param ISession $session
101
+     * @param string $appName
102
+     * @param bool $isLoggedIn
103
+     * @param bool $isAdminUser
104
+     * @param ContentSecurityPolicyManager $contentSecurityPolicyManager
105
+     * @param CSRFTokenManager $csrfTokenManager
106
+     * @param ContentSecurityPolicyNonceManager $cspNonceManager
107
+     * @param Throttler $throttler
108
+     */
109
+    public function __construct(IRequest $request,
110
+                                ControllerMethodReflector $reflector,
111
+                                INavigationManager $navigationManager,
112
+                                IURLGenerator $urlGenerator,
113
+                                ILogger $logger,
114
+                                ISession $session,
115
+                                $appName,
116
+                                $isLoggedIn,
117
+                                $isAdminUser,
118
+                                ContentSecurityPolicyManager $contentSecurityPolicyManager,
119
+                                CsrfTokenManager $csrfTokenManager,
120
+                                ContentSecurityPolicyNonceManager $cspNonceManager,
121
+                                Throttler $throttler) {
122
+        $this->navigationManager = $navigationManager;
123
+        $this->request = $request;
124
+        $this->reflector = $reflector;
125
+        $this->appName = $appName;
126
+        $this->urlGenerator = $urlGenerator;
127
+        $this->logger = $logger;
128
+        $this->session = $session;
129
+        $this->isLoggedIn = $isLoggedIn;
130
+        $this->isAdminUser = $isAdminUser;
131
+        $this->contentSecurityPolicyManager = $contentSecurityPolicyManager;
132
+        $this->csrfTokenManager = $csrfTokenManager;
133
+        $this->cspNonceManager = $cspNonceManager;
134
+        $this->throttler = $throttler;
135
+    }
136 136
 
137 137
 
138
-	/**
139
-	 * This runs all the security checks before a method call. The
140
-	 * security checks are determined by inspecting the controller method
141
-	 * annotations
142
-	 * @param Controller $controller the controller
143
-	 * @param string $methodName the name of the method
144
-	 * @throws SecurityException when a security check fails
145
-	 */
146
-	public function beforeController($controller, $methodName) {
138
+    /**
139
+     * This runs all the security checks before a method call. The
140
+     * security checks are determined by inspecting the controller method
141
+     * annotations
142
+     * @param Controller $controller the controller
143
+     * @param string $methodName the name of the method
144
+     * @throws SecurityException when a security check fails
145
+     */
146
+    public function beforeController($controller, $methodName) {
147 147
 
148
-		// this will set the current navigation entry of the app, use this only
149
-		// for normal HTML requests and not for AJAX requests
150
-		$this->navigationManager->setActiveEntry($this->appName);
148
+        // this will set the current navigation entry of the app, use this only
149
+        // for normal HTML requests and not for AJAX requests
150
+        $this->navigationManager->setActiveEntry($this->appName);
151 151
 
152
-		// security checks
153
-		$isPublicPage = $this->reflector->hasAnnotation('PublicPage');
154
-		if(!$isPublicPage) {
155
-			if(!$this->isLoggedIn) {
156
-				throw new NotLoggedInException();
157
-			}
152
+        // security checks
153
+        $isPublicPage = $this->reflector->hasAnnotation('PublicPage');
154
+        if(!$isPublicPage) {
155
+            if(!$this->isLoggedIn) {
156
+                throw new NotLoggedInException();
157
+            }
158 158
 
159
-			if(!$this->reflector->hasAnnotation('NoAdminRequired')) {
160
-				if(!$this->isAdminUser) {
161
-					throw new NotAdminException();
162
-				}
163
-			}
164
-		}
159
+            if(!$this->reflector->hasAnnotation('NoAdminRequired')) {
160
+                if(!$this->isAdminUser) {
161
+                    throw new NotAdminException();
162
+                }
163
+            }
164
+        }
165 165
 
166
-		if ($this->reflector->hasAnnotation('PasswordConfirmationRequired')) {
167
-			$lastConfirm = (int) $this->session->get('last-password-confirm');
168
-			if ($lastConfirm < (time() - (30 * 60 + 15))) { // allow 15 seconds delay
169
-				throw new NotConfirmedException();
170
-			}
171
-		}
166
+        if ($this->reflector->hasAnnotation('PasswordConfirmationRequired')) {
167
+            $lastConfirm = (int) $this->session->get('last-password-confirm');
168
+            if ($lastConfirm < (time() - (30 * 60 + 15))) { // allow 15 seconds delay
169
+                throw new NotConfirmedException();
170
+            }
171
+        }
172 172
 
173
-		// Check for strict cookie requirement
174
-		if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
175
-			if(!$this->request->passesStrictCookieCheck()) {
176
-				throw new StrictCookieMissingException();
177
-			}
178
-		}
179
-		// CSRF check - also registers the CSRF token since the session may be closed later
180
-		Util::callRegister();
181
-		if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
182
-			/*
173
+        // Check for strict cookie requirement
174
+        if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
175
+            if(!$this->request->passesStrictCookieCheck()) {
176
+                throw new StrictCookieMissingException();
177
+            }
178
+        }
179
+        // CSRF check - also registers the CSRF token since the session may be closed later
180
+        Util::callRegister();
181
+        if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
182
+            /*
183 183
 			 * Only allow the CSRF check to fail on OCS Requests. This kind of
184 184
 			 * hacks around that we have no full token auth in place yet and we
185 185
 			 * do want to offer CSRF checks for web requests.
186 186
 			 */
187
-			if(!$this->request->passesCSRFCheck() && !(
188
-					$controller instanceof OCSController &&
189
-					$this->request->getHeader('OCS-APIREQUEST') === 'true')) {
190
-				throw new CrossSiteRequestForgeryException();
191
-			}
192
-		}
187
+            if(!$this->request->passesCSRFCheck() && !(
188
+                    $controller instanceof OCSController &&
189
+                    $this->request->getHeader('OCS-APIREQUEST') === 'true')) {
190
+                throw new CrossSiteRequestForgeryException();
191
+            }
192
+        }
193 193
 
194
-		if($this->reflector->hasAnnotation('BruteForceProtection')) {
195
-			$action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action');
196
-			$this->throttler->sleepDelay($this->request->getRemoteAddress(), $action);
197
-			$this->throttler->registerAttempt($action, $this->request->getRemoteAddress());
198
-		}
194
+        if($this->reflector->hasAnnotation('BruteForceProtection')) {
195
+            $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action');
196
+            $this->throttler->sleepDelay($this->request->getRemoteAddress(), $action);
197
+            $this->throttler->registerAttempt($action, $this->request->getRemoteAddress());
198
+        }
199 199
 
200
-		/**
201
-		 * FIXME: Use DI once available
202
-		 * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
203
-		 * The getAppPath() check is here since components such as settings also use the AppFramework and
204
-		 * therefore won't pass this check.
205
-		 */
206
-		if(\OC_App::getAppPath($this->appName) !== false && !\OC_App::isEnabled($this->appName)) {
207
-			throw new AppNotEnabledException();
208
-		}
200
+        /**
201
+         * FIXME: Use DI once available
202
+         * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
203
+         * The getAppPath() check is here since components such as settings also use the AppFramework and
204
+         * therefore won't pass this check.
205
+         */
206
+        if(\OC_App::getAppPath($this->appName) !== false && !\OC_App::isEnabled($this->appName)) {
207
+            throw new AppNotEnabledException();
208
+        }
209 209
 
210
-	}
210
+    }
211 211
 
212
-	/**
213
-	 * Performs the default CSP modifications that may be injected by other
214
-	 * applications
215
-	 *
216
-	 * @param Controller $controller
217
-	 * @param string $methodName
218
-	 * @param Response $response
219
-	 * @return Response
220
-	 */
221
-	public function afterController($controller, $methodName, Response $response) {
222
-		$policy = !is_null($response->getContentSecurityPolicy()) ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy();
212
+    /**
213
+     * Performs the default CSP modifications that may be injected by other
214
+     * applications
215
+     *
216
+     * @param Controller $controller
217
+     * @param string $methodName
218
+     * @param Response $response
219
+     * @return Response
220
+     */
221
+    public function afterController($controller, $methodName, Response $response) {
222
+        $policy = !is_null($response->getContentSecurityPolicy()) ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy();
223 223
 
224
-		if (get_class($policy) === EmptyContentSecurityPolicy::class) {
225
-			return $response;
226
-		}
224
+        if (get_class($policy) === EmptyContentSecurityPolicy::class) {
225
+            return $response;
226
+        }
227 227
 
228
-		$defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
229
-		$defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
228
+        $defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
229
+        $defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
230 230
 
231
-		if($this->cspNonceManager->browserSupportsCspV3()) {
232
-			$defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
233
-		}
231
+        if($this->cspNonceManager->browserSupportsCspV3()) {
232
+            $defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
233
+        }
234 234
 
235
-		$response->setContentSecurityPolicy($defaultPolicy);
235
+        $response->setContentSecurityPolicy($defaultPolicy);
236 236
 
237
-		return $response;
238
-	}
237
+        return $response;
238
+    }
239 239
 
240
-	/**
241
-	 * If an SecurityException is being caught, ajax requests return a JSON error
242
-	 * response and non ajax requests redirect to the index
243
-	 * @param Controller $controller the controller that is being called
244
-	 * @param string $methodName the name of the method that will be called on
245
-	 *                           the controller
246
-	 * @param \Exception $exception the thrown exception
247
-	 * @throws \Exception the passed in exception if it can't handle it
248
-	 * @return Response a Response object or null in case that the exception could not be handled
249
-	 */
250
-	public function afterException($controller, $methodName, \Exception $exception) {
251
-		if($exception instanceof SecurityException) {
252
-			if($exception instanceof StrictCookieMissingException) {
253
-				return new RedirectResponse(\OC::$WEBROOT);
254
- 			}
255
-			if (stripos($this->request->getHeader('Accept'),'html') === false) {
256
-				$response = new JSONResponse(
257
-					array('message' => $exception->getMessage()),
258
-					$exception->getCode()
259
-				);
260
-			} else {
261
-				if($exception instanceof NotLoggedInException) {
262
-					$url = $this->urlGenerator->linkToRoute(
263
-						'core.login.showLoginForm',
264
-						[
265
-							'redirect_url' => $this->request->server['REQUEST_URI'],
266
-						]
267
-					);
268
-					$response = new RedirectResponse($url);
269
-				} else {
270
-					$response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest');
271
-					$response->setStatus($exception->getCode());
272
-				}
273
-			}
240
+    /**
241
+     * If an SecurityException is being caught, ajax requests return a JSON error
242
+     * response and non ajax requests redirect to the index
243
+     * @param Controller $controller the controller that is being called
244
+     * @param string $methodName the name of the method that will be called on
245
+     *                           the controller
246
+     * @param \Exception $exception the thrown exception
247
+     * @throws \Exception the passed in exception if it can't handle it
248
+     * @return Response a Response object or null in case that the exception could not be handled
249
+     */
250
+    public function afterException($controller, $methodName, \Exception $exception) {
251
+        if($exception instanceof SecurityException) {
252
+            if($exception instanceof StrictCookieMissingException) {
253
+                return new RedirectResponse(\OC::$WEBROOT);
254
+                }
255
+            if (stripos($this->request->getHeader('Accept'),'html') === false) {
256
+                $response = new JSONResponse(
257
+                    array('message' => $exception->getMessage()),
258
+                    $exception->getCode()
259
+                );
260
+            } else {
261
+                if($exception instanceof NotLoggedInException) {
262
+                    $url = $this->urlGenerator->linkToRoute(
263
+                        'core.login.showLoginForm',
264
+                        [
265
+                            'redirect_url' => $this->request->server['REQUEST_URI'],
266
+                        ]
267
+                    );
268
+                    $response = new RedirectResponse($url);
269
+                } else {
270
+                    $response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest');
271
+                    $response->setStatus($exception->getCode());
272
+                }
273
+            }
274 274
 
275
-			$this->logger->debug($exception->getMessage());
276
-			return $response;
277
-		}
275
+            $this->logger->debug($exception->getMessage());
276
+            return $response;
277
+        }
278 278
 
279
-		throw $exception;
280
-	}
279
+        throw $exception;
280
+    }
281 281
 
282 282
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Middleware/Security/RateLimitingMiddleware.php 1 patch
Indentation   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -48,87 +48,87 @@
 block discarded – undo
48 48
  * @package OC\AppFramework\Middleware\Security
49 49
  */
50 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;
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 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
-	}
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 75
 
76
-	/**
77
-	 * {@inheritDoc}
78
-	 * @throws RateLimitExceededException
79
-	 */
80
-	public function beforeController($controller, $methodName) {
81
-		parent::beforeController($controller, $methodName);
76
+    /**
77
+     * {@inheritDoc}
78
+     * @throws RateLimitExceededException
79
+     */
80
+    public function beforeController($controller, $methodName) {
81
+        parent::beforeController($controller, $methodName);
82 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()
94
-			);
95
-		} elseif ($anonLimit !== '' && $anonPeriod !== '') {
96
-			$this->limiter->registerAnonRequest(
97
-				$rateLimitIdentifier,
98
-				$anonLimit,
99
-				$anonPeriod,
100
-				$this->request->getRemoteAddress()
101
-			);
102
-		}
103
-	}
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()
94
+            );
95
+        } elseif ($anonLimit !== '' && $anonPeriod !== '') {
96
+            $this->limiter->registerAnonRequest(
97
+                $rateLimitIdentifier,
98
+                $anonLimit,
99
+                $anonPeriod,
100
+                $this->request->getRemoteAddress()
101
+            );
102
+        }
103
+    }
104 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
-			} else {
118
-					$response = new TemplateResponse(
119
-						'core',
120
-						'403',
121
-							[
122
-								'file' => $exception->getMessage()
123
-							],
124
-						'guest'
125
-					);
126
-					$response->setStatus($exception->getCode());
127
-			}
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
+            } 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 128
 
129
-			return $response;
130
-		}
129
+            return $response;
130
+        }
131 131
 
132
-		throw $exception;
133
-	}
132
+        throw $exception;
133
+    }
134 134
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 1 patch
Indentation   +361 added lines, -361 removed lines patch added patch discarded remove patch
@@ -62,365 +62,365 @@
 block discarded – undo
62 62
 
63 63
 class DIContainer extends SimpleContainer implements IAppContainer {
64 64
 
65
-	/**
66
-	 * @var array
67
-	 */
68
-	private $middleWares = array();
69
-
70
-	/** @var ServerContainer */
71
-	private $server;
72
-
73
-	/**
74
-	 * Put your class dependencies in here
75
-	 * @param string $appName the name of the app
76
-	 * @param array $urlParams
77
-	 * @param ServerContainer $server
78
-	 */
79
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
80
-		parent::__construct();
81
-		$this['AppName'] = $appName;
82
-		$this['urlParams'] = $urlParams;
83
-
84
-		/** @var \OC\ServerContainer $server */
85
-		if ($server === null) {
86
-			$server = \OC::$server;
87
-		}
88
-		$this->server = $server;
89
-		$this->server->registerAppContainer($appName, $this);
90
-
91
-		// aliases
92
-		$this->registerAlias('appName', 'AppName');
93
-		$this->registerAlias('webRoot', 'WebRoot');
94
-		$this->registerAlias('userId', 'UserId');
95
-
96
-		/**
97
-		 * Core services
98
-		 */
99
-		$this->registerService(IOutput::class, function($c){
100
-			return new Output($this->getServer()->getWebRoot());
101
-		});
102
-
103
-		$this->registerService(Folder::class, function() {
104
-			return $this->getServer()->getUserFolder();
105
-		});
106
-
107
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
108
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
109
-		});
110
-
111
-		$this->registerService(IL10N::class, function($c) {
112
-			return $this->getServer()->getL10N($c->query('AppName'));
113
-		});
114
-
115
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
116
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
117
-
118
-		$this->registerService(IRequest::class, function() {
119
-			return $this->getServer()->query(IRequest::class);
120
-		});
121
-		$this->registerAlias('Request', IRequest::class);
122
-
123
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
124
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
125
-
126
-		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
127
-
128
-		$this->registerService(IServerContainer::class, function ($c) {
129
-			return $this->getServer();
130
-		});
131
-		$this->registerAlias('ServerContainer', IServerContainer::class);
132
-
133
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
134
-			return $c->query('OCA\WorkflowEngine\Manager');
135
-		});
136
-
137
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
138
-			return $c;
139
-		});
140
-
141
-		// commonly used attributes
142
-		$this->registerService('UserId', function ($c) {
143
-			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
144
-		});
145
-
146
-		$this->registerService('WebRoot', function ($c) {
147
-			return $c->query('ServerContainer')->getWebRoot();
148
-		});
149
-
150
-		$this->registerService('fromMailAddress', function() {
151
-			return Util::getDefaultEmailAddress('no-reply');
152
-		});
153
-
154
-		$this->registerService('OC_Defaults', function ($c) {
155
-			return $c->getServer()->getThemingDefaults();
156
-		});
157
-
158
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
159
-			return $this->getServer()->getEncryptionManager();
160
-		});
161
-
162
-		$this->registerService(IValidator::class, function($c) {
163
-			return $c->query(Validator::class);
164
-		});
165
-
166
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
167
-			return new \OC\Security\IdentityProof\Manager(
168
-				$this->getServer()->getAppDataDir('identityproof'),
169
-				$this->getServer()->getCrypto()
170
-			);
171
-		});
172
-
173
-		/**
174
-		 * App Framework APIs
175
-		 */
176
-		$this->registerService('API', function($c){
177
-			$c->query('OCP\\ILogger')->debug(
178
-				'Accessing the API class is deprecated! Use the appropriate ' .
179
-				'services instead!'
180
-			);
181
-			return new API($c['AppName']);
182
-		});
183
-
184
-		$this->registerService('Protocol', function($c){
185
-			/** @var \OC\Server $server */
186
-			$server = $c->query('ServerContainer');
187
-			$protocol = $server->getRequest()->getHttpProtocol();
188
-			return new Http($_SERVER, $protocol);
189
-		});
190
-
191
-		$this->registerService('Dispatcher', function($c) {
192
-			return new Dispatcher(
193
-				$c['Protocol'],
194
-				$c['MiddlewareDispatcher'],
195
-				$c['ControllerMethodReflector'],
196
-				$c['Request']
197
-			);
198
-		});
199
-
200
-		/**
201
-		 * App Framework default arguments
202
-		 */
203
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
204
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
205
-		$this->registerParameter('corsMaxAge', 1728000);
206
-
207
-		/**
208
-		 * Middleware
209
-		 */
210
-		$app = $this;
211
-		$this->registerService('SecurityMiddleware', function($c) use ($app){
212
-			/** @var \OC\Server $server */
213
-			$server = $app->getServer();
214
-
215
-			return new SecurityMiddleware(
216
-				$c['Request'],
217
-				$c['ControllerMethodReflector'],
218
-				$server->getNavigationManager(),
219
-				$server->getURLGenerator(),
220
-				$server->getLogger(),
221
-				$server->getSession(),
222
-				$c['AppName'],
223
-				$app->isLoggedIn(),
224
-				$app->isAdminUser(),
225
-				$server->getContentSecurityPolicyManager(),
226
-				$server->getCsrfTokenManager(),
227
-				$server->getContentSecurityPolicyNonceManager(),
228
-				$server->getBruteForceThrottler()
229
-			);
230
-
231
-		});
232
-
233
-		$this->registerService('RateLimitingMiddleware', function($c) use ($app) {
234
-			/** @var \OC\Server $server */
235
-			$server = $app->getServer();
236
-
237
-			return new RateLimitingMiddleware(
238
-				$server->getRequest(),
239
-				$server->getUserSession(),
240
-				$c['ControllerMethodReflector'],
241
-				$c->query(OC\Security\RateLimiting\Limiter::class)
242
-			);
243
-		});
244
-
245
-		$this->registerService('CORSMiddleware', function($c) {
246
-			return new CORSMiddleware(
247
-				$c['Request'],
248
-				$c['ControllerMethodReflector'],
249
-				$c->query(IUserSession::class),
250
-				$c->getServer()->getBruteForceThrottler()
251
-			);
252
-		});
253
-
254
-		$this->registerService('SessionMiddleware', function($c) use ($app) {
255
-			return new SessionMiddleware(
256
-				$c['Request'],
257
-				$c['ControllerMethodReflector'],
258
-				$app->getServer()->getSession()
259
-			);
260
-		});
261
-
262
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
263
-			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
264
-			$userSession = $app->getServer()->getUserSession();
265
-			$session = $app->getServer()->getSession();
266
-			$urlGenerator = $app->getServer()->getURLGenerator();
267
-			$reflector = $c['ControllerMethodReflector'];
268
-			$request = $app->getServer()->getRequest();
269
-			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
270
-		});
271
-
272
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
273
-			return new OCSMiddleware(
274
-				$c['Request']
275
-			);
276
-		});
277
-
278
-		$middleWares = &$this->middleWares;
279
-		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
280
-			$dispatcher = new MiddlewareDispatcher();
281
-			$dispatcher->registerMiddleware($c['CORSMiddleware']);
282
-			$dispatcher->registerMiddleware($c['OCSMiddleware']);
283
-			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
284
-			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
285
-			$dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
286
-
287
-			foreach($middleWares as $middleWare) {
288
-				$dispatcher->registerMiddleware($c[$middleWare]);
289
-			}
290
-
291
-			$dispatcher->registerMiddleware($c['SessionMiddleware']);
292
-			return $dispatcher;
293
-		});
294
-
295
-	}
296
-
297
-
298
-	/**
299
-	 * @deprecated implements only deprecated methods
300
-	 * @return IApi
301
-	 */
302
-	function getCoreApi()
303
-	{
304
-		return $this->query('API');
305
-	}
306
-
307
-	/**
308
-	 * @return \OCP\IServerContainer
309
-	 */
310
-	function getServer()
311
-	{
312
-		return $this->server;
313
-	}
314
-
315
-	/**
316
-	 * @param string $middleWare
317
-	 * @return boolean|null
318
-	 */
319
-	function registerMiddleWare($middleWare) {
320
-		array_push($this->middleWares, $middleWare);
321
-	}
322
-
323
-	/**
324
-	 * used to return the appname of the set application
325
-	 * @return string the name of your application
326
-	 */
327
-	function getAppName() {
328
-		return $this->query('AppName');
329
-	}
330
-
331
-	/**
332
-	 * @deprecated use IUserSession->isLoggedIn()
333
-	 * @return boolean
334
-	 */
335
-	function isLoggedIn() {
336
-		return \OC::$server->getUserSession()->isLoggedIn();
337
-	}
338
-
339
-	/**
340
-	 * @deprecated use IGroupManager->isAdmin($userId)
341
-	 * @return boolean
342
-	 */
343
-	function isAdminUser() {
344
-		$uid = $this->getUserId();
345
-		return \OC_User::isAdminUser($uid);
346
-	}
347
-
348
-	private function getUserId() {
349
-		return $this->getServer()->getSession()->get('user_id');
350
-	}
351
-
352
-	/**
353
-	 * @deprecated use the ILogger instead
354
-	 * @param string $message
355
-	 * @param string $level
356
-	 * @return mixed
357
-	 */
358
-	function log($message, $level) {
359
-		switch($level){
360
-			case 'debug':
361
-				$level = \OCP\Util::DEBUG;
362
-				break;
363
-			case 'info':
364
-				$level = \OCP\Util::INFO;
365
-				break;
366
-			case 'warn':
367
-				$level = \OCP\Util::WARN;
368
-				break;
369
-			case 'fatal':
370
-				$level = \OCP\Util::FATAL;
371
-				break;
372
-			default:
373
-				$level = \OCP\Util::ERROR;
374
-				break;
375
-		}
376
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
377
-	}
378
-
379
-	/**
380
-	 * Register a capability
381
-	 *
382
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
383
-	 */
384
-	public function registerCapability($serviceName) {
385
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
386
-			return $this->query($serviceName);
387
-		});
388
-	}
389
-
390
-	/**
391
-	 * @param string $name
392
-	 * @return mixed
393
-	 * @throws QueryException if the query could not be resolved
394
-	 */
395
-	public function query($name) {
396
-		try {
397
-			return $this->queryNoFallback($name);
398
-		} catch (QueryException $e) {
399
-			return $this->getServer()->query($name);
400
-		}
401
-	}
402
-
403
-	/**
404
-	 * @param string $name
405
-	 * @return mixed
406
-	 * @throws QueryException if the query could not be resolved
407
-	 */
408
-	public function queryNoFallback($name) {
409
-		$name = $this->sanitizeName($name);
410
-
411
-		if ($this->offsetExists($name)) {
412
-			return parent::query($name);
413
-		} else {
414
-			if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
415
-				return parent::query($name);
416
-			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
417
-				return parent::query($name);
418
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
419
-				return parent::query($name);
420
-			}
421
-		}
422
-
423
-		throw new QueryException('Could not resolve ' . $name . '!' .
424
-			' Class can not be instantiated');
425
-	}
65
+    /**
66
+     * @var array
67
+     */
68
+    private $middleWares = array();
69
+
70
+    /** @var ServerContainer */
71
+    private $server;
72
+
73
+    /**
74
+     * Put your class dependencies in here
75
+     * @param string $appName the name of the app
76
+     * @param array $urlParams
77
+     * @param ServerContainer $server
78
+     */
79
+    public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
80
+        parent::__construct();
81
+        $this['AppName'] = $appName;
82
+        $this['urlParams'] = $urlParams;
83
+
84
+        /** @var \OC\ServerContainer $server */
85
+        if ($server === null) {
86
+            $server = \OC::$server;
87
+        }
88
+        $this->server = $server;
89
+        $this->server->registerAppContainer($appName, $this);
90
+
91
+        // aliases
92
+        $this->registerAlias('appName', 'AppName');
93
+        $this->registerAlias('webRoot', 'WebRoot');
94
+        $this->registerAlias('userId', 'UserId');
95
+
96
+        /**
97
+         * Core services
98
+         */
99
+        $this->registerService(IOutput::class, function($c){
100
+            return new Output($this->getServer()->getWebRoot());
101
+        });
102
+
103
+        $this->registerService(Folder::class, function() {
104
+            return $this->getServer()->getUserFolder();
105
+        });
106
+
107
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
108
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
109
+        });
110
+
111
+        $this->registerService(IL10N::class, function($c) {
112
+            return $this->getServer()->getL10N($c->query('AppName'));
113
+        });
114
+
115
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
116
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
117
+
118
+        $this->registerService(IRequest::class, function() {
119
+            return $this->getServer()->query(IRequest::class);
120
+        });
121
+        $this->registerAlias('Request', IRequest::class);
122
+
123
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
124
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
125
+
126
+        $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
127
+
128
+        $this->registerService(IServerContainer::class, function ($c) {
129
+            return $this->getServer();
130
+        });
131
+        $this->registerAlias('ServerContainer', IServerContainer::class);
132
+
133
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
134
+            return $c->query('OCA\WorkflowEngine\Manager');
135
+        });
136
+
137
+        $this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
138
+            return $c;
139
+        });
140
+
141
+        // commonly used attributes
142
+        $this->registerService('UserId', function ($c) {
143
+            return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
144
+        });
145
+
146
+        $this->registerService('WebRoot', function ($c) {
147
+            return $c->query('ServerContainer')->getWebRoot();
148
+        });
149
+
150
+        $this->registerService('fromMailAddress', function() {
151
+            return Util::getDefaultEmailAddress('no-reply');
152
+        });
153
+
154
+        $this->registerService('OC_Defaults', function ($c) {
155
+            return $c->getServer()->getThemingDefaults();
156
+        });
157
+
158
+        $this->registerService('OCP\Encryption\IManager', function ($c) {
159
+            return $this->getServer()->getEncryptionManager();
160
+        });
161
+
162
+        $this->registerService(IValidator::class, function($c) {
163
+            return $c->query(Validator::class);
164
+        });
165
+
166
+        $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
167
+            return new \OC\Security\IdentityProof\Manager(
168
+                $this->getServer()->getAppDataDir('identityproof'),
169
+                $this->getServer()->getCrypto()
170
+            );
171
+        });
172
+
173
+        /**
174
+         * App Framework APIs
175
+         */
176
+        $this->registerService('API', function($c){
177
+            $c->query('OCP\\ILogger')->debug(
178
+                'Accessing the API class is deprecated! Use the appropriate ' .
179
+                'services instead!'
180
+            );
181
+            return new API($c['AppName']);
182
+        });
183
+
184
+        $this->registerService('Protocol', function($c){
185
+            /** @var \OC\Server $server */
186
+            $server = $c->query('ServerContainer');
187
+            $protocol = $server->getRequest()->getHttpProtocol();
188
+            return new Http($_SERVER, $protocol);
189
+        });
190
+
191
+        $this->registerService('Dispatcher', function($c) {
192
+            return new Dispatcher(
193
+                $c['Protocol'],
194
+                $c['MiddlewareDispatcher'],
195
+                $c['ControllerMethodReflector'],
196
+                $c['Request']
197
+            );
198
+        });
199
+
200
+        /**
201
+         * App Framework default arguments
202
+         */
203
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
204
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
205
+        $this->registerParameter('corsMaxAge', 1728000);
206
+
207
+        /**
208
+         * Middleware
209
+         */
210
+        $app = $this;
211
+        $this->registerService('SecurityMiddleware', function($c) use ($app){
212
+            /** @var \OC\Server $server */
213
+            $server = $app->getServer();
214
+
215
+            return new SecurityMiddleware(
216
+                $c['Request'],
217
+                $c['ControllerMethodReflector'],
218
+                $server->getNavigationManager(),
219
+                $server->getURLGenerator(),
220
+                $server->getLogger(),
221
+                $server->getSession(),
222
+                $c['AppName'],
223
+                $app->isLoggedIn(),
224
+                $app->isAdminUser(),
225
+                $server->getContentSecurityPolicyManager(),
226
+                $server->getCsrfTokenManager(),
227
+                $server->getContentSecurityPolicyNonceManager(),
228
+                $server->getBruteForceThrottler()
229
+            );
230
+
231
+        });
232
+
233
+        $this->registerService('RateLimitingMiddleware', function($c) use ($app) {
234
+            /** @var \OC\Server $server */
235
+            $server = $app->getServer();
236
+
237
+            return new RateLimitingMiddleware(
238
+                $server->getRequest(),
239
+                $server->getUserSession(),
240
+                $c['ControllerMethodReflector'],
241
+                $c->query(OC\Security\RateLimiting\Limiter::class)
242
+            );
243
+        });
244
+
245
+        $this->registerService('CORSMiddleware', function($c) {
246
+            return new CORSMiddleware(
247
+                $c['Request'],
248
+                $c['ControllerMethodReflector'],
249
+                $c->query(IUserSession::class),
250
+                $c->getServer()->getBruteForceThrottler()
251
+            );
252
+        });
253
+
254
+        $this->registerService('SessionMiddleware', function($c) use ($app) {
255
+            return new SessionMiddleware(
256
+                $c['Request'],
257
+                $c['ControllerMethodReflector'],
258
+                $app->getServer()->getSession()
259
+            );
260
+        });
261
+
262
+        $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
263
+            $twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
264
+            $userSession = $app->getServer()->getUserSession();
265
+            $session = $app->getServer()->getSession();
266
+            $urlGenerator = $app->getServer()->getURLGenerator();
267
+            $reflector = $c['ControllerMethodReflector'];
268
+            $request = $app->getServer()->getRequest();
269
+            return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
270
+        });
271
+
272
+        $this->registerService('OCSMiddleware', function (SimpleContainer $c) {
273
+            return new OCSMiddleware(
274
+                $c['Request']
275
+            );
276
+        });
277
+
278
+        $middleWares = &$this->middleWares;
279
+        $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
280
+            $dispatcher = new MiddlewareDispatcher();
281
+            $dispatcher->registerMiddleware($c['CORSMiddleware']);
282
+            $dispatcher->registerMiddleware($c['OCSMiddleware']);
283
+            $dispatcher->registerMiddleware($c['SecurityMiddleware']);
284
+            $dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
285
+            $dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
286
+
287
+            foreach($middleWares as $middleWare) {
288
+                $dispatcher->registerMiddleware($c[$middleWare]);
289
+            }
290
+
291
+            $dispatcher->registerMiddleware($c['SessionMiddleware']);
292
+            return $dispatcher;
293
+        });
294
+
295
+    }
296
+
297
+
298
+    /**
299
+     * @deprecated implements only deprecated methods
300
+     * @return IApi
301
+     */
302
+    function getCoreApi()
303
+    {
304
+        return $this->query('API');
305
+    }
306
+
307
+    /**
308
+     * @return \OCP\IServerContainer
309
+     */
310
+    function getServer()
311
+    {
312
+        return $this->server;
313
+    }
314
+
315
+    /**
316
+     * @param string $middleWare
317
+     * @return boolean|null
318
+     */
319
+    function registerMiddleWare($middleWare) {
320
+        array_push($this->middleWares, $middleWare);
321
+    }
322
+
323
+    /**
324
+     * used to return the appname of the set application
325
+     * @return string the name of your application
326
+     */
327
+    function getAppName() {
328
+        return $this->query('AppName');
329
+    }
330
+
331
+    /**
332
+     * @deprecated use IUserSession->isLoggedIn()
333
+     * @return boolean
334
+     */
335
+    function isLoggedIn() {
336
+        return \OC::$server->getUserSession()->isLoggedIn();
337
+    }
338
+
339
+    /**
340
+     * @deprecated use IGroupManager->isAdmin($userId)
341
+     * @return boolean
342
+     */
343
+    function isAdminUser() {
344
+        $uid = $this->getUserId();
345
+        return \OC_User::isAdminUser($uid);
346
+    }
347
+
348
+    private function getUserId() {
349
+        return $this->getServer()->getSession()->get('user_id');
350
+    }
351
+
352
+    /**
353
+     * @deprecated use the ILogger instead
354
+     * @param string $message
355
+     * @param string $level
356
+     * @return mixed
357
+     */
358
+    function log($message, $level) {
359
+        switch($level){
360
+            case 'debug':
361
+                $level = \OCP\Util::DEBUG;
362
+                break;
363
+            case 'info':
364
+                $level = \OCP\Util::INFO;
365
+                break;
366
+            case 'warn':
367
+                $level = \OCP\Util::WARN;
368
+                break;
369
+            case 'fatal':
370
+                $level = \OCP\Util::FATAL;
371
+                break;
372
+            default:
373
+                $level = \OCP\Util::ERROR;
374
+                break;
375
+        }
376
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
377
+    }
378
+
379
+    /**
380
+     * Register a capability
381
+     *
382
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
383
+     */
384
+    public function registerCapability($serviceName) {
385
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
386
+            return $this->query($serviceName);
387
+        });
388
+    }
389
+
390
+    /**
391
+     * @param string $name
392
+     * @return mixed
393
+     * @throws QueryException if the query could not be resolved
394
+     */
395
+    public function query($name) {
396
+        try {
397
+            return $this->queryNoFallback($name);
398
+        } catch (QueryException $e) {
399
+            return $this->getServer()->query($name);
400
+        }
401
+    }
402
+
403
+    /**
404
+     * @param string $name
405
+     * @return mixed
406
+     * @throws QueryException if the query could not be resolved
407
+     */
408
+    public function queryNoFallback($name) {
409
+        $name = $this->sanitizeName($name);
410
+
411
+        if ($this->offsetExists($name)) {
412
+            return parent::query($name);
413
+        } else {
414
+            if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
415
+                return parent::query($name);
416
+            } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
417
+                return parent::query($name);
418
+            } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
419
+                return parent::query($name);
420
+            }
421
+        }
422
+
423
+        throw new QueryException('Could not resolve ' . $name . '!' .
424
+            ' Class can not be instantiated');
425
+    }
426 426
 }
Please login to merge, or discard this patch.
lib/private/Security/RateLimiting/Backend/MemoryCache.php 1 patch
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -32,85 +32,85 @@
 block discarded – undo
32 32
  * @package OC\Security\RateLimiting\Backend
33 33
  */
34 34
 class MemoryCache implements IBackend {
35
-	/** @var ICache */
36
-	private $cache;
37
-	/** @var ITimeFactory */
38
-	private $timeFactory;
35
+    /** @var ICache */
36
+    private $cache;
37
+    /** @var ITimeFactory */
38
+    private $timeFactory;
39 39
 
40
-	/**
41
-	 * @param ICacheFactory $cacheFactory
42
-	 * @param ITimeFactory $timeFactory
43
-	 */
44
-	public function __construct(ICacheFactory $cacheFactory,
45
-								ITimeFactory $timeFactory) {
46
-		$this->cache = $cacheFactory->create(__CLASS__);
47
-		$this->timeFactory = $timeFactory;
48
-	}
40
+    /**
41
+     * @param ICacheFactory $cacheFactory
42
+     * @param ITimeFactory $timeFactory
43
+     */
44
+    public function __construct(ICacheFactory $cacheFactory,
45
+                                ITimeFactory $timeFactory) {
46
+        $this->cache = $cacheFactory->create(__CLASS__);
47
+        $this->timeFactory = $timeFactory;
48
+    }
49 49
 
50
-	/**
51
-	 * @param string $methodIdentifier
52
-	 * @param string $userIdentifier
53
-	 * @return string
54
-	 */
55
-	private function hash($methodIdentifier,
56
-						  $userIdentifier) {
57
-		return hash('sha512', $methodIdentifier . $userIdentifier);
58
-	}
50
+    /**
51
+     * @param string $methodIdentifier
52
+     * @param string $userIdentifier
53
+     * @return string
54
+     */
55
+    private function hash($methodIdentifier,
56
+                            $userIdentifier) {
57
+        return hash('sha512', $methodIdentifier . $userIdentifier);
58
+    }
59 59
 
60
-	/**
61
-	 * @param string $identifier
62
-	 * @return array
63
-	 */
64
-	private function getExistingAttempts($identifier) {
65
-		$cachedAttempts = json_decode($this->cache->get($identifier), true);
66
-		if(is_array($cachedAttempts)) {
67
-			return $cachedAttempts;
68
-		}
60
+    /**
61
+     * @param string $identifier
62
+     * @return array
63
+     */
64
+    private function getExistingAttempts($identifier) {
65
+        $cachedAttempts = json_decode($this->cache->get($identifier), true);
66
+        if(is_array($cachedAttempts)) {
67
+            return $cachedAttempts;
68
+        }
69 69
 
70
-		return [];
71
-	}
70
+        return [];
71
+    }
72 72
 
73
-	/**
74
-	 * {@inheritDoc}
75
-	 */
76
-	public function getAttempts($methodIdentifier,
77
-								$userIdentifier,
78
-								$seconds) {
79
-		$identifier = $this->hash($methodIdentifier, $userIdentifier);
80
-		$existingAttempts = $this->getExistingAttempts($identifier);
73
+    /**
74
+     * {@inheritDoc}
75
+     */
76
+    public function getAttempts($methodIdentifier,
77
+                                $userIdentifier,
78
+                                $seconds) {
79
+        $identifier = $this->hash($methodIdentifier, $userIdentifier);
80
+        $existingAttempts = $this->getExistingAttempts($identifier);
81 81
 
82
-		$count = 0;
83
-		$currentTime = $this->timeFactory->getTime();
84
-		/** @var array $existingAttempts */
85
-		foreach ($existingAttempts as $attempt) {
86
-			if(($attempt + $seconds) > $currentTime) {
87
-				$count++;
88
-			}
89
-		}
82
+        $count = 0;
83
+        $currentTime = $this->timeFactory->getTime();
84
+        /** @var array $existingAttempts */
85
+        foreach ($existingAttempts as $attempt) {
86
+            if(($attempt + $seconds) > $currentTime) {
87
+                $count++;
88
+            }
89
+        }
90 90
 
91
-		return $count;
92
-	}
91
+        return $count;
92
+    }
93 93
 
94
-	/**
95
-	 * {@inheritDoc}
96
-	 */
97
-	public function registerAttempt($methodIdentifier,
98
-									$userIdentifier,
99
-									$period) {
100
-		$identifier = $this->hash($methodIdentifier, $userIdentifier);
101
-		$existingAttempts = $this->getExistingAttempts($identifier);
102
-		$currentTime = $this->timeFactory->getTime();
94
+    /**
95
+     * {@inheritDoc}
96
+     */
97
+    public function registerAttempt($methodIdentifier,
98
+                                    $userIdentifier,
99
+                                    $period) {
100
+        $identifier = $this->hash($methodIdentifier, $userIdentifier);
101
+        $existingAttempts = $this->getExistingAttempts($identifier);
102
+        $currentTime = $this->timeFactory->getTime();
103 103
 
104
-		// Unset all attempts older than $period
105
-		foreach ($existingAttempts as $key => $attempt) {
106
-			if(($attempt + $period) < $currentTime) {
107
-				unset($existingAttempts[$key]);
108
-			}
109
-		}
110
-		$existingAttempts = array_values($existingAttempts);
104
+        // Unset all attempts older than $period
105
+        foreach ($existingAttempts as $key => $attempt) {
106
+            if(($attempt + $period) < $currentTime) {
107
+                unset($existingAttempts[$key]);
108
+            }
109
+        }
110
+        $existingAttempts = array_values($existingAttempts);
111 111
 
112
-		// Store the new attempt
113
-		$existingAttempts[] = (string)$currentTime;
114
-		$this->cache->set($identifier, json_encode($existingAttempts));
115
-	}
112
+        // Store the new attempt
113
+        $existingAttempts[] = (string)$currentTime;
114
+        $this->cache->set($identifier, json_encode($existingAttempts));
115
+    }
116 116
 }
Please login to merge, or discard this patch.
lib/private/Security/RateLimiting/Backend/IBackend.php 1 patch
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -29,26 +29,26 @@
 block discarded – undo
29 29
  * @package OC\Security\RateLimiting\Backend
30 30
  */
31 31
 interface IBackend {
32
-	/**
33
-	 * Gets the amount of attempts within the last specified seconds
34
-	 *
35
-	 * @param string $methodIdentifier Identifier for the method
36
-	 * @param string $userIdentifier Identifier for the user
37
-	 * @param int $seconds Seconds to look back at
38
-	 * @return int
39
-	 */
40
-	public function getAttempts($methodIdentifier,
41
-								$userIdentifier,
42
-								$seconds);
32
+    /**
33
+     * Gets the amount of attempts within the last specified seconds
34
+     *
35
+     * @param string $methodIdentifier Identifier for the method
36
+     * @param string $userIdentifier Identifier for the user
37
+     * @param int $seconds Seconds to look back at
38
+     * @return int
39
+     */
40
+    public function getAttempts($methodIdentifier,
41
+                                $userIdentifier,
42
+                                $seconds);
43 43
 
44
-	/**
45
-	 * Registers an attempt
46
-	 *
47
-	 * @param string $methodIdentifier Identifier for the method
48
-	 * @param string $userIdentifier Identifier for the user
49
-	 * @param int $period Period in seconds how long this attempt should be stored
50
-	 */
51
-	public function registerAttempt($methodIdentifier,
52
-									$userIdentifier,
53
-									$period);
44
+    /**
45
+     * Registers an attempt
46
+     *
47
+     * @param string $methodIdentifier Identifier for the method
48
+     * @param string $userIdentifier Identifier for the user
49
+     * @param int $period Period in seconds how long this attempt should be stored
50
+     */
51
+    public function registerAttempt($methodIdentifier,
52
+                                    $userIdentifier,
53
+                                    $period);
54 54
 }
Please login to merge, or discard this patch.