Passed
Push — master ( 4d4a22...bfc37a )
by Joas
14:44 queued 14s
created
lib/private/AppFramework/Middleware/Security/BruteForceMiddleware.php 2 patches
Indentation   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -51,93 +51,93 @@
 block discarded – undo
51 51
  * @package OC\AppFramework\Middleware\Security
52 52
  */
53 53
 class BruteForceMiddleware extends Middleware {
54
-	public function __construct(
55
-		protected ControllerMethodReflector $reflector,
56
-		protected Throttler $throttler,
57
-		protected IRequest $request,
58
-		protected LoggerInterface $logger,
59
-	) {
60
-	}
61
-
62
-	/**
63
-	 * {@inheritDoc}
64
-	 */
65
-	public function beforeController($controller, $methodName) {
66
-		parent::beforeController($controller, $methodName);
67
-
68
-		if ($this->reflector->hasAnnotation('BruteForceProtection')) {
69
-			$action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action');
70
-			$this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), $action);
71
-		} else {
72
-			$reflectionMethod = new ReflectionMethod($controller, $methodName);
73
-			$attributes = $reflectionMethod->getAttributes(BruteForceProtection::class);
74
-
75
-			if (!empty($attributes)) {
76
-				$remoteAddress = $this->request->getRemoteAddress();
77
-
78
-				foreach ($attributes as $attribute) {
79
-					/** @var BruteForceProtection $protection */
80
-					$protection = $attribute->newInstance();
81
-					$action = $protection->getAction();
82
-					$this->throttler->sleepDelayOrThrowOnMax($remoteAddress, $action);
83
-				}
84
-			}
85
-		}
86
-	}
87
-
88
-	/**
89
-	 * {@inheritDoc}
90
-	 */
91
-	public function afterController($controller, $methodName, Response $response) {
92
-		if ($response->isThrottled()) {
93
-			if ($this->reflector->hasAnnotation('BruteForceProtection')) {
94
-				$action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action');
95
-				$ip = $this->request->getRemoteAddress();
96
-				$this->throttler->sleepDelay($ip, $action);
97
-				$this->throttler->registerAttempt($action, $ip, $response->getThrottleMetadata());
98
-			} else {
99
-				$reflectionMethod = new ReflectionMethod($controller, $methodName);
100
-				$attributes = $reflectionMethod->getAttributes(BruteForceProtection::class);
101
-
102
-				if (!empty($attributes)) {
103
-					$ip = $this->request->getRemoteAddress();
104
-					$metaData = $response->getThrottleMetadata();
105
-
106
-					foreach ($attributes as $attribute) {
107
-						/** @var BruteForceProtection $protection */
108
-						$protection = $attribute->newInstance();
109
-						$action = $protection->getAction();
110
-
111
-						if (!isset($metaData['action']) || $metaData['action'] === $action) {
112
-							$this->throttler->sleepDelay($ip, $action);
113
-							$this->throttler->registerAttempt($action, $ip, $metaData);
114
-						}
115
-					}
116
-				} else {
117
-					$this->logger->debug('Response for ' . get_class($controller) . '::' . $methodName . ' got bruteforce throttled but has no annotation nor attribute defined.');
118
-				}
119
-			}
120
-		}
121
-
122
-		return parent::afterController($controller, $methodName, $response);
123
-	}
124
-
125
-	/**
126
-	 * @param Controller $controller
127
-	 * @param string $methodName
128
-	 * @param \Exception $exception
129
-	 * @throws \Exception
130
-	 * @return Response
131
-	 */
132
-	public function afterException($controller, $methodName, \Exception $exception): Response {
133
-		if ($exception instanceof MaxDelayReached) {
134
-			if ($controller instanceof OCSController) {
135
-				throw new OCSException($exception->getMessage(), Http::STATUS_TOO_MANY_REQUESTS);
136
-			}
137
-
138
-			return new TooManyRequestsResponse();
139
-		}
140
-
141
-		throw $exception;
142
-	}
54
+    public function __construct(
55
+        protected ControllerMethodReflector $reflector,
56
+        protected Throttler $throttler,
57
+        protected IRequest $request,
58
+        protected LoggerInterface $logger,
59
+    ) {
60
+    }
61
+
62
+    /**
63
+     * {@inheritDoc}
64
+     */
65
+    public function beforeController($controller, $methodName) {
66
+        parent::beforeController($controller, $methodName);
67
+
68
+        if ($this->reflector->hasAnnotation('BruteForceProtection')) {
69
+            $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action');
70
+            $this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), $action);
71
+        } else {
72
+            $reflectionMethod = new ReflectionMethod($controller, $methodName);
73
+            $attributes = $reflectionMethod->getAttributes(BruteForceProtection::class);
74
+
75
+            if (!empty($attributes)) {
76
+                $remoteAddress = $this->request->getRemoteAddress();
77
+
78
+                foreach ($attributes as $attribute) {
79
+                    /** @var BruteForceProtection $protection */
80
+                    $protection = $attribute->newInstance();
81
+                    $action = $protection->getAction();
82
+                    $this->throttler->sleepDelayOrThrowOnMax($remoteAddress, $action);
83
+                }
84
+            }
85
+        }
86
+    }
87
+
88
+    /**
89
+     * {@inheritDoc}
90
+     */
91
+    public function afterController($controller, $methodName, Response $response) {
92
+        if ($response->isThrottled()) {
93
+            if ($this->reflector->hasAnnotation('BruteForceProtection')) {
94
+                $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action');
95
+                $ip = $this->request->getRemoteAddress();
96
+                $this->throttler->sleepDelay($ip, $action);
97
+                $this->throttler->registerAttempt($action, $ip, $response->getThrottleMetadata());
98
+            } else {
99
+                $reflectionMethod = new ReflectionMethod($controller, $methodName);
100
+                $attributes = $reflectionMethod->getAttributes(BruteForceProtection::class);
101
+
102
+                if (!empty($attributes)) {
103
+                    $ip = $this->request->getRemoteAddress();
104
+                    $metaData = $response->getThrottleMetadata();
105
+
106
+                    foreach ($attributes as $attribute) {
107
+                        /** @var BruteForceProtection $protection */
108
+                        $protection = $attribute->newInstance();
109
+                        $action = $protection->getAction();
110
+
111
+                        if (!isset($metaData['action']) || $metaData['action'] === $action) {
112
+                            $this->throttler->sleepDelay($ip, $action);
113
+                            $this->throttler->registerAttempt($action, $ip, $metaData);
114
+                        }
115
+                    }
116
+                } else {
117
+                    $this->logger->debug('Response for ' . get_class($controller) . '::' . $methodName . ' got bruteforce throttled but has no annotation nor attribute defined.');
118
+                }
119
+            }
120
+        }
121
+
122
+        return parent::afterController($controller, $methodName, $response);
123
+    }
124
+
125
+    /**
126
+     * @param Controller $controller
127
+     * @param string $methodName
128
+     * @param \Exception $exception
129
+     * @throws \Exception
130
+     * @return Response
131
+     */
132
+    public function afterException($controller, $methodName, \Exception $exception): Response {
133
+        if ($exception instanceof MaxDelayReached) {
134
+            if ($controller instanceof OCSController) {
135
+                throw new OCSException($exception->getMessage(), Http::STATUS_TOO_MANY_REQUESTS);
136
+            }
137
+
138
+            return new TooManyRequestsResponse();
139
+        }
140
+
141
+        throw $exception;
142
+    }
143 143
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -114,7 +114,7 @@
 block discarded – undo
114 114
 						}
115 115
 					}
116 116
 				} else {
117
-					$this->logger->debug('Response for ' . get_class($controller) . '::' . $methodName . ' got bruteforce throttled but has no annotation nor attribute defined.');
117
+					$this->logger->debug('Response for '.get_class($controller).'::'.$methodName.' got bruteforce throttled but has no annotation nor attribute defined.');
118 118
 				}
119 119
 			}
120 120
 		}
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 1 patch
Indentation   +418 added lines, -418 removed lines patch added patch discarded remove patch
@@ -79,422 +79,422 @@
 block discarded – undo
79 79
  * @deprecated 20.0.0
80 80
  */
81 81
 class DIContainer extends SimpleContainer implements IAppContainer {
82
-	private string $appName;
83
-
84
-	/**
85
-	 * @var array
86
-	 */
87
-	private $middleWares = [];
88
-
89
-	/** @var ServerContainer */
90
-	private $server;
91
-
92
-	/**
93
-	 * Put your class dependencies in here
94
-	 * @param string $appName the name of the app
95
-	 * @param array $urlParams
96
-	 * @param ServerContainer|null $server
97
-	 */
98
-	public function __construct(string $appName, array $urlParams = [], ServerContainer $server = null) {
99
-		parent::__construct();
100
-		$this->appName = $appName;
101
-		$this['appName'] = $appName;
102
-		$this['urlParams'] = $urlParams;
103
-
104
-		$this->registerAlias('Request', IRequest::class);
105
-
106
-		/** @var \OC\ServerContainer $server */
107
-		if ($server === null) {
108
-			$server = \OC::$server;
109
-		}
110
-		$this->server = $server;
111
-		$this->server->registerAppContainer($appName, $this);
112
-
113
-		// aliases
114
-		/** @deprecated inject $appName */
115
-		$this->registerAlias('AppName', 'appName');
116
-		/** @deprecated inject $webRoot*/
117
-		$this->registerAlias('WebRoot', 'webRoot');
118
-		/** @deprecated inject $userId */
119
-		$this->registerAlias('UserId', 'userId');
120
-
121
-		/**
122
-		 * Core services
123
-		 */
124
-		$this->registerService(IOutput::class, function () {
125
-			return new Output($this->getServer()->getWebRoot());
126
-		});
127
-
128
-		$this->registerService(Folder::class, function () {
129
-			return $this->getServer()->getUserFolder();
130
-		});
131
-
132
-		$this->registerService(IAppData::class, function (ContainerInterface $c) {
133
-			return $this->getServer()->getAppDataDir($c->get('AppName'));
134
-		});
135
-
136
-		$this->registerService(IL10N::class, function (ContainerInterface $c) {
137
-			return $this->getServer()->getL10N($c->get('AppName'));
138
-		});
139
-
140
-		// Log wrappers
141
-		$this->registerService(LoggerInterface::class, function (ContainerInterface $c) {
142
-			return new ScopedPsrLogger(
143
-				$c->get(PsrLoggerAdapter::class),
144
-				$c->get('AppName')
145
-			);
146
-		});
147
-		$this->registerService(ILogger::class, function (ContainerInterface $c) {
148
-			return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->get('AppName'));
149
-		});
150
-
151
-		$this->registerService(IServerContainer::class, function () {
152
-			return $this->getServer();
153
-		});
154
-		$this->registerAlias('ServerContainer', IServerContainer::class);
155
-
156
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function (ContainerInterface $c) {
157
-			return $c->get(Manager::class);
158
-		});
159
-
160
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
161
-			return $c;
162
-		});
163
-		$this->registerAlias(IAppContainer::class, ContainerInterface::class);
164
-
165
-		// commonly used attributes
166
-		$this->registerService('userId', function (ContainerInterface $c) {
167
-			return $c->get(IUserSession::class)->getSession()->get('user_id');
168
-		});
169
-
170
-		$this->registerService('webRoot', function (ContainerInterface $c) {
171
-			return $c->get(IServerContainer::class)->getWebRoot();
172
-		});
173
-
174
-		$this->registerService('OC_Defaults', function (ContainerInterface $c) {
175
-			return $c->get(IServerContainer::class)->getThemingDefaults();
176
-		});
177
-
178
-		$this->registerService('Protocol', function (ContainerInterface $c) {
179
-			/** @var \OC\Server $server */
180
-			$server = $c->get(IServerContainer::class);
181
-			$protocol = $server->getRequest()->getHttpProtocol();
182
-			return new Http($_SERVER, $protocol);
183
-		});
184
-
185
-		$this->registerService('Dispatcher', function (ContainerInterface $c) {
186
-			return new Dispatcher(
187
-				$c->get('Protocol'),
188
-				$c->get(MiddlewareDispatcher::class),
189
-				$c->get(IControllerMethodReflector::class),
190
-				$c->get(IRequest::class),
191
-				$c->get(IConfig::class),
192
-				$c->get(IDBConnection::class),
193
-				$c->get(LoggerInterface::class),
194
-				$c->get(EventLogger::class),
195
-				$c,
196
-			);
197
-		});
198
-
199
-		/**
200
-		 * App Framework default arguments
201
-		 */
202
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
203
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
204
-		$this->registerParameter('corsMaxAge', 1728000);
205
-
206
-		/**
207
-		 * Middleware
208
-		 */
209
-		$this->registerAlias('MiddlewareDispatcher', MiddlewareDispatcher::class);
210
-		$this->registerService(MiddlewareDispatcher::class, function (ContainerInterface $c) {
211
-			$server = $this->getServer();
212
-
213
-			$dispatcher = new MiddlewareDispatcher();
214
-
215
-			$dispatcher->registerMiddleware(
216
-				$c->get(OC\AppFramework\Middleware\CompressionMiddleware::class)
217
-			);
218
-
219
-			$dispatcher->registerMiddleware($c->get(OC\AppFramework\Middleware\NotModifiedMiddleware::class));
220
-
221
-			$dispatcher->registerMiddleware(
222
-				$c->get(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
223
-			);
224
-
225
-			$dispatcher->registerMiddleware(
226
-				new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
227
-					$c->get(IRequest::class),
228
-					$c->get(IControllerMethodReflector::class)
229
-				)
230
-			);
231
-			$dispatcher->registerMiddleware(
232
-				new CORSMiddleware(
233
-					$c->get(IRequest::class),
234
-					$c->get(IControllerMethodReflector::class),
235
-					$c->get(IUserSession::class),
236
-					$c->get(OC\Security\Bruteforce\Throttler::class)
237
-				)
238
-			);
239
-			$dispatcher->registerMiddleware(
240
-				new OCSMiddleware(
241
-					$c->get(IRequest::class)
242
-				)
243
-			);
244
-
245
-
246
-
247
-			$securityMiddleware = new SecurityMiddleware(
248
-				$c->get(IRequest::class),
249
-				$c->get(IControllerMethodReflector::class),
250
-				$c->get(INavigationManager::class),
251
-				$c->get(IURLGenerator::class),
252
-				$server->get(LoggerInterface::class),
253
-				$c->get('AppName'),
254
-				$server->getUserSession()->isLoggedIn(),
255
-				$this->getUserId() !== null && $server->getGroupManager()->isAdmin($this->getUserId()),
256
-				$server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
257
-				$server->getAppManager(),
258
-				$server->getL10N('lib'),
259
-				$c->get(AuthorizedGroupMapper::class),
260
-				$server->get(IUserSession::class)
261
-			);
262
-			$dispatcher->registerMiddleware($securityMiddleware);
263
-			$dispatcher->registerMiddleware(
264
-				new OC\AppFramework\Middleware\Security\CSPMiddleware(
265
-					$server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
266
-					$server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
267
-					$server->query(OC\Security\CSRF\CsrfTokenManager::class)
268
-				)
269
-			);
270
-			$dispatcher->registerMiddleware(
271
-				$server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
272
-			);
273
-			$dispatcher->registerMiddleware(
274
-				new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
275
-					$c->get(IControllerMethodReflector::class),
276
-					$c->get(ISession::class),
277
-					$c->get(IUserSession::class),
278
-					$c->get(ITimeFactory::class)
279
-				)
280
-			);
281
-			$dispatcher->registerMiddleware(
282
-				new TwoFactorMiddleware(
283
-					$c->get(OC\Authentication\TwoFactorAuth\Manager::class),
284
-					$c->get(IUserSession::class),
285
-					$c->get(ISession::class),
286
-					$c->get(IURLGenerator::class),
287
-					$c->get(IControllerMethodReflector::class),
288
-					$c->get(IRequest::class)
289
-				)
290
-			);
291
-			$dispatcher->registerMiddleware(
292
-				new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
293
-					$c->get(IControllerMethodReflector::class),
294
-					$c->get(OC\Security\Bruteforce\Throttler::class),
295
-					$c->get(IRequest::class),
296
-					$c->get(LoggerInterface::class)
297
-				)
298
-			);
299
-			$dispatcher->registerMiddleware(
300
-				new RateLimitingMiddleware(
301
-					$c->get(IRequest::class),
302
-					$c->get(IUserSession::class),
303
-					$c->get(IControllerMethodReflector::class),
304
-					$c->get(OC\Security\RateLimiting\Limiter::class)
305
-				)
306
-			);
307
-			$dispatcher->registerMiddleware(
308
-				new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
309
-					$c->get(IRequest::class),
310
-					$c->get(ISession::class),
311
-					$c->get(\OCP\IConfig::class),
312
-					$c->get(OC\Security\Bruteforce\Throttler::class)
313
-				)
314
-			);
315
-			$dispatcher->registerMiddleware(
316
-				$c->get(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
317
-			);
318
-
319
-			/** @var \OC\AppFramework\Bootstrap\Coordinator $coordinator */
320
-			$coordinator = $c->get(\OC\AppFramework\Bootstrap\Coordinator::class);
321
-			$registrationContext = $coordinator->getRegistrationContext();
322
-			if ($registrationContext !== null) {
323
-				$appId = $this->getAppName();
324
-				foreach ($registrationContext->getMiddlewareRegistrations() as $middlewareRegistration) {
325
-					if ($middlewareRegistration->getAppId() === $appId
326
-						|| $middlewareRegistration->isGlobal()) {
327
-						$dispatcher->registerMiddleware($c->get($middlewareRegistration->getService()));
328
-					}
329
-				}
330
-			}
331
-			foreach ($this->middleWares as $middleWare) {
332
-				$dispatcher->registerMiddleware($c->get($middleWare));
333
-			}
334
-
335
-			$dispatcher->registerMiddleware(
336
-				new SessionMiddleware(
337
-					$c->get(IControllerMethodReflector::class),
338
-					$c->get(ISession::class)
339
-				)
340
-			);
341
-			return $dispatcher;
342
-		});
343
-
344
-		$this->registerService(IAppConfig::class, function (ContainerInterface $c) {
345
-			return new OC\AppFramework\Services\AppConfig(
346
-				$c->get(IConfig::class),
347
-				$c->get('AppName')
348
-			);
349
-		});
350
-		$this->registerService(IInitialState::class, function (ContainerInterface $c) {
351
-			return new OC\AppFramework\Services\InitialState(
352
-				$c->get(IInitialStateService::class),
353
-				$c->get('AppName')
354
-			);
355
-		});
356
-	}
357
-
358
-	/**
359
-	 * @return \OCP\IServerContainer
360
-	 */
361
-	public function getServer() {
362
-		return $this->server;
363
-	}
364
-
365
-	/**
366
-	 * @param string $middleWare
367
-	 * @return boolean|null
368
-	 */
369
-	public function registerMiddleWare($middleWare) {
370
-		if (in_array($middleWare, $this->middleWares, true) !== false) {
371
-			return false;
372
-		}
373
-		$this->middleWares[] = $middleWare;
374
-	}
375
-
376
-	/**
377
-	 * used to return the appname of the set application
378
-	 * @return string the name of your application
379
-	 */
380
-	public function getAppName() {
381
-		return $this->query('AppName');
382
-	}
383
-
384
-	/**
385
-	 * @deprecated use IUserSession->isLoggedIn()
386
-	 * @return boolean
387
-	 */
388
-	public function isLoggedIn() {
389
-		return \OC::$server->getUserSession()->isLoggedIn();
390
-	}
391
-
392
-	/**
393
-	 * @deprecated use IGroupManager->isAdmin($userId)
394
-	 * @return boolean
395
-	 */
396
-	public function isAdminUser() {
397
-		$uid = $this->getUserId();
398
-		return \OC_User::isAdminUser($uid);
399
-	}
400
-
401
-	private function getUserId() {
402
-		return $this->getServer()->getSession()->get('user_id');
403
-	}
404
-
405
-	/**
406
-	 * @deprecated use the ILogger instead
407
-	 * @param string $message
408
-	 * @param string $level
409
-	 * @return mixed
410
-	 */
411
-	public function log($message, $level) {
412
-		switch ($level) {
413
-			case 'debug':
414
-				$level = ILogger::DEBUG;
415
-				break;
416
-			case 'info':
417
-				$level = ILogger::INFO;
418
-				break;
419
-			case 'warn':
420
-				$level = ILogger::WARN;
421
-				break;
422
-			case 'fatal':
423
-				$level = ILogger::FATAL;
424
-				break;
425
-			default:
426
-				$level = ILogger::ERROR;
427
-				break;
428
-		}
429
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
430
-	}
431
-
432
-	/**
433
-	 * Register a capability
434
-	 *
435
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
436
-	 */
437
-	public function registerCapability($serviceName) {
438
-		$this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
439
-			return $this->query($serviceName);
440
-		});
441
-	}
442
-
443
-	public function has($id): bool {
444
-		if (parent::has($id)) {
445
-			return true;
446
-		}
447
-
448
-		if ($this->server->has($id, true)) {
449
-			return true;
450
-		}
451
-
452
-		return false;
453
-	}
454
-
455
-	public function query(string $name, bool $autoload = true) {
456
-		if ($name === 'AppName' || $name === 'appName') {
457
-			return $this->appName;
458
-		}
459
-
460
-		$isServerClass = str_starts_with($name, 'OCP\\') || str_starts_with($name, 'OC\\');
461
-		if ($isServerClass && !$this->has($name)) {
462
-			return $this->getServer()->query($name, $autoload);
463
-		}
464
-
465
-		try {
466
-			return $this->queryNoFallback($name);
467
-		} catch (QueryException $firstException) {
468
-			try {
469
-				return $this->getServer()->query($name, $autoload);
470
-			} catch (QueryException $secondException) {
471
-				if ($firstException->getCode() === 1) {
472
-					throw $secondException;
473
-				}
474
-				throw $firstException;
475
-			}
476
-		}
477
-	}
478
-
479
-	/**
480
-	 * @param string $name
481
-	 * @return mixed
482
-	 * @throws QueryException if the query could not be resolved
483
-	 */
484
-	public function queryNoFallback($name) {
485
-		$name = $this->sanitizeName($name);
486
-
487
-		if ($this->offsetExists($name)) {
488
-			return parent::query($name);
489
-		} elseif ($this->appName === 'settings' && str_starts_with($name, 'OC\\Settings\\')) {
490
-			return parent::query($name);
491
-		} elseif ($this->appName === 'core' && str_starts_with($name, 'OC\\Core\\')) {
492
-			return parent::query($name);
493
-		} elseif (str_starts_with($name, \OC\AppFramework\App::buildAppNamespace($this->appName) . '\\')) {
494
-			return parent::query($name);
495
-		}
496
-
497
-		throw new QueryException('Could not resolve ' . $name . '!' .
498
-			' Class can not be instantiated', 1);
499
-	}
82
+    private string $appName;
83
+
84
+    /**
85
+     * @var array
86
+     */
87
+    private $middleWares = [];
88
+
89
+    /** @var ServerContainer */
90
+    private $server;
91
+
92
+    /**
93
+     * Put your class dependencies in here
94
+     * @param string $appName the name of the app
95
+     * @param array $urlParams
96
+     * @param ServerContainer|null $server
97
+     */
98
+    public function __construct(string $appName, array $urlParams = [], ServerContainer $server = null) {
99
+        parent::__construct();
100
+        $this->appName = $appName;
101
+        $this['appName'] = $appName;
102
+        $this['urlParams'] = $urlParams;
103
+
104
+        $this->registerAlias('Request', IRequest::class);
105
+
106
+        /** @var \OC\ServerContainer $server */
107
+        if ($server === null) {
108
+            $server = \OC::$server;
109
+        }
110
+        $this->server = $server;
111
+        $this->server->registerAppContainer($appName, $this);
112
+
113
+        // aliases
114
+        /** @deprecated inject $appName */
115
+        $this->registerAlias('AppName', 'appName');
116
+        /** @deprecated inject $webRoot*/
117
+        $this->registerAlias('WebRoot', 'webRoot');
118
+        /** @deprecated inject $userId */
119
+        $this->registerAlias('UserId', 'userId');
120
+
121
+        /**
122
+         * Core services
123
+         */
124
+        $this->registerService(IOutput::class, function () {
125
+            return new Output($this->getServer()->getWebRoot());
126
+        });
127
+
128
+        $this->registerService(Folder::class, function () {
129
+            return $this->getServer()->getUserFolder();
130
+        });
131
+
132
+        $this->registerService(IAppData::class, function (ContainerInterface $c) {
133
+            return $this->getServer()->getAppDataDir($c->get('AppName'));
134
+        });
135
+
136
+        $this->registerService(IL10N::class, function (ContainerInterface $c) {
137
+            return $this->getServer()->getL10N($c->get('AppName'));
138
+        });
139
+
140
+        // Log wrappers
141
+        $this->registerService(LoggerInterface::class, function (ContainerInterface $c) {
142
+            return new ScopedPsrLogger(
143
+                $c->get(PsrLoggerAdapter::class),
144
+                $c->get('AppName')
145
+            );
146
+        });
147
+        $this->registerService(ILogger::class, function (ContainerInterface $c) {
148
+            return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->get('AppName'));
149
+        });
150
+
151
+        $this->registerService(IServerContainer::class, function () {
152
+            return $this->getServer();
153
+        });
154
+        $this->registerAlias('ServerContainer', IServerContainer::class);
155
+
156
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function (ContainerInterface $c) {
157
+            return $c->get(Manager::class);
158
+        });
159
+
160
+        $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
161
+            return $c;
162
+        });
163
+        $this->registerAlias(IAppContainer::class, ContainerInterface::class);
164
+
165
+        // commonly used attributes
166
+        $this->registerService('userId', function (ContainerInterface $c) {
167
+            return $c->get(IUserSession::class)->getSession()->get('user_id');
168
+        });
169
+
170
+        $this->registerService('webRoot', function (ContainerInterface $c) {
171
+            return $c->get(IServerContainer::class)->getWebRoot();
172
+        });
173
+
174
+        $this->registerService('OC_Defaults', function (ContainerInterface $c) {
175
+            return $c->get(IServerContainer::class)->getThemingDefaults();
176
+        });
177
+
178
+        $this->registerService('Protocol', function (ContainerInterface $c) {
179
+            /** @var \OC\Server $server */
180
+            $server = $c->get(IServerContainer::class);
181
+            $protocol = $server->getRequest()->getHttpProtocol();
182
+            return new Http($_SERVER, $protocol);
183
+        });
184
+
185
+        $this->registerService('Dispatcher', function (ContainerInterface $c) {
186
+            return new Dispatcher(
187
+                $c->get('Protocol'),
188
+                $c->get(MiddlewareDispatcher::class),
189
+                $c->get(IControllerMethodReflector::class),
190
+                $c->get(IRequest::class),
191
+                $c->get(IConfig::class),
192
+                $c->get(IDBConnection::class),
193
+                $c->get(LoggerInterface::class),
194
+                $c->get(EventLogger::class),
195
+                $c,
196
+            );
197
+        });
198
+
199
+        /**
200
+         * App Framework default arguments
201
+         */
202
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
203
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
204
+        $this->registerParameter('corsMaxAge', 1728000);
205
+
206
+        /**
207
+         * Middleware
208
+         */
209
+        $this->registerAlias('MiddlewareDispatcher', MiddlewareDispatcher::class);
210
+        $this->registerService(MiddlewareDispatcher::class, function (ContainerInterface $c) {
211
+            $server = $this->getServer();
212
+
213
+            $dispatcher = new MiddlewareDispatcher();
214
+
215
+            $dispatcher->registerMiddleware(
216
+                $c->get(OC\AppFramework\Middleware\CompressionMiddleware::class)
217
+            );
218
+
219
+            $dispatcher->registerMiddleware($c->get(OC\AppFramework\Middleware\NotModifiedMiddleware::class));
220
+
221
+            $dispatcher->registerMiddleware(
222
+                $c->get(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
223
+            );
224
+
225
+            $dispatcher->registerMiddleware(
226
+                new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
227
+                    $c->get(IRequest::class),
228
+                    $c->get(IControllerMethodReflector::class)
229
+                )
230
+            );
231
+            $dispatcher->registerMiddleware(
232
+                new CORSMiddleware(
233
+                    $c->get(IRequest::class),
234
+                    $c->get(IControllerMethodReflector::class),
235
+                    $c->get(IUserSession::class),
236
+                    $c->get(OC\Security\Bruteforce\Throttler::class)
237
+                )
238
+            );
239
+            $dispatcher->registerMiddleware(
240
+                new OCSMiddleware(
241
+                    $c->get(IRequest::class)
242
+                )
243
+            );
244
+
245
+
246
+
247
+            $securityMiddleware = new SecurityMiddleware(
248
+                $c->get(IRequest::class),
249
+                $c->get(IControllerMethodReflector::class),
250
+                $c->get(INavigationManager::class),
251
+                $c->get(IURLGenerator::class),
252
+                $server->get(LoggerInterface::class),
253
+                $c->get('AppName'),
254
+                $server->getUserSession()->isLoggedIn(),
255
+                $this->getUserId() !== null && $server->getGroupManager()->isAdmin($this->getUserId()),
256
+                $server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
257
+                $server->getAppManager(),
258
+                $server->getL10N('lib'),
259
+                $c->get(AuthorizedGroupMapper::class),
260
+                $server->get(IUserSession::class)
261
+            );
262
+            $dispatcher->registerMiddleware($securityMiddleware);
263
+            $dispatcher->registerMiddleware(
264
+                new OC\AppFramework\Middleware\Security\CSPMiddleware(
265
+                    $server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
266
+                    $server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
267
+                    $server->query(OC\Security\CSRF\CsrfTokenManager::class)
268
+                )
269
+            );
270
+            $dispatcher->registerMiddleware(
271
+                $server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
272
+            );
273
+            $dispatcher->registerMiddleware(
274
+                new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
275
+                    $c->get(IControllerMethodReflector::class),
276
+                    $c->get(ISession::class),
277
+                    $c->get(IUserSession::class),
278
+                    $c->get(ITimeFactory::class)
279
+                )
280
+            );
281
+            $dispatcher->registerMiddleware(
282
+                new TwoFactorMiddleware(
283
+                    $c->get(OC\Authentication\TwoFactorAuth\Manager::class),
284
+                    $c->get(IUserSession::class),
285
+                    $c->get(ISession::class),
286
+                    $c->get(IURLGenerator::class),
287
+                    $c->get(IControllerMethodReflector::class),
288
+                    $c->get(IRequest::class)
289
+                )
290
+            );
291
+            $dispatcher->registerMiddleware(
292
+                new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
293
+                    $c->get(IControllerMethodReflector::class),
294
+                    $c->get(OC\Security\Bruteforce\Throttler::class),
295
+                    $c->get(IRequest::class),
296
+                    $c->get(LoggerInterface::class)
297
+                )
298
+            );
299
+            $dispatcher->registerMiddleware(
300
+                new RateLimitingMiddleware(
301
+                    $c->get(IRequest::class),
302
+                    $c->get(IUserSession::class),
303
+                    $c->get(IControllerMethodReflector::class),
304
+                    $c->get(OC\Security\RateLimiting\Limiter::class)
305
+                )
306
+            );
307
+            $dispatcher->registerMiddleware(
308
+                new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
309
+                    $c->get(IRequest::class),
310
+                    $c->get(ISession::class),
311
+                    $c->get(\OCP\IConfig::class),
312
+                    $c->get(OC\Security\Bruteforce\Throttler::class)
313
+                )
314
+            );
315
+            $dispatcher->registerMiddleware(
316
+                $c->get(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
317
+            );
318
+
319
+            /** @var \OC\AppFramework\Bootstrap\Coordinator $coordinator */
320
+            $coordinator = $c->get(\OC\AppFramework\Bootstrap\Coordinator::class);
321
+            $registrationContext = $coordinator->getRegistrationContext();
322
+            if ($registrationContext !== null) {
323
+                $appId = $this->getAppName();
324
+                foreach ($registrationContext->getMiddlewareRegistrations() as $middlewareRegistration) {
325
+                    if ($middlewareRegistration->getAppId() === $appId
326
+                        || $middlewareRegistration->isGlobal()) {
327
+                        $dispatcher->registerMiddleware($c->get($middlewareRegistration->getService()));
328
+                    }
329
+                }
330
+            }
331
+            foreach ($this->middleWares as $middleWare) {
332
+                $dispatcher->registerMiddleware($c->get($middleWare));
333
+            }
334
+
335
+            $dispatcher->registerMiddleware(
336
+                new SessionMiddleware(
337
+                    $c->get(IControllerMethodReflector::class),
338
+                    $c->get(ISession::class)
339
+                )
340
+            );
341
+            return $dispatcher;
342
+        });
343
+
344
+        $this->registerService(IAppConfig::class, function (ContainerInterface $c) {
345
+            return new OC\AppFramework\Services\AppConfig(
346
+                $c->get(IConfig::class),
347
+                $c->get('AppName')
348
+            );
349
+        });
350
+        $this->registerService(IInitialState::class, function (ContainerInterface $c) {
351
+            return new OC\AppFramework\Services\InitialState(
352
+                $c->get(IInitialStateService::class),
353
+                $c->get('AppName')
354
+            );
355
+        });
356
+    }
357
+
358
+    /**
359
+     * @return \OCP\IServerContainer
360
+     */
361
+    public function getServer() {
362
+        return $this->server;
363
+    }
364
+
365
+    /**
366
+     * @param string $middleWare
367
+     * @return boolean|null
368
+     */
369
+    public function registerMiddleWare($middleWare) {
370
+        if (in_array($middleWare, $this->middleWares, true) !== false) {
371
+            return false;
372
+        }
373
+        $this->middleWares[] = $middleWare;
374
+    }
375
+
376
+    /**
377
+     * used to return the appname of the set application
378
+     * @return string the name of your application
379
+     */
380
+    public function getAppName() {
381
+        return $this->query('AppName');
382
+    }
383
+
384
+    /**
385
+     * @deprecated use IUserSession->isLoggedIn()
386
+     * @return boolean
387
+     */
388
+    public function isLoggedIn() {
389
+        return \OC::$server->getUserSession()->isLoggedIn();
390
+    }
391
+
392
+    /**
393
+     * @deprecated use IGroupManager->isAdmin($userId)
394
+     * @return boolean
395
+     */
396
+    public function isAdminUser() {
397
+        $uid = $this->getUserId();
398
+        return \OC_User::isAdminUser($uid);
399
+    }
400
+
401
+    private function getUserId() {
402
+        return $this->getServer()->getSession()->get('user_id');
403
+    }
404
+
405
+    /**
406
+     * @deprecated use the ILogger instead
407
+     * @param string $message
408
+     * @param string $level
409
+     * @return mixed
410
+     */
411
+    public function log($message, $level) {
412
+        switch ($level) {
413
+            case 'debug':
414
+                $level = ILogger::DEBUG;
415
+                break;
416
+            case 'info':
417
+                $level = ILogger::INFO;
418
+                break;
419
+            case 'warn':
420
+                $level = ILogger::WARN;
421
+                break;
422
+            case 'fatal':
423
+                $level = ILogger::FATAL;
424
+                break;
425
+            default:
426
+                $level = ILogger::ERROR;
427
+                break;
428
+        }
429
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
430
+    }
431
+
432
+    /**
433
+     * Register a capability
434
+     *
435
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
436
+     */
437
+    public function registerCapability($serviceName) {
438
+        $this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
439
+            return $this->query($serviceName);
440
+        });
441
+    }
442
+
443
+    public function has($id): bool {
444
+        if (parent::has($id)) {
445
+            return true;
446
+        }
447
+
448
+        if ($this->server->has($id, true)) {
449
+            return true;
450
+        }
451
+
452
+        return false;
453
+    }
454
+
455
+    public function query(string $name, bool $autoload = true) {
456
+        if ($name === 'AppName' || $name === 'appName') {
457
+            return $this->appName;
458
+        }
459
+
460
+        $isServerClass = str_starts_with($name, 'OCP\\') || str_starts_with($name, 'OC\\');
461
+        if ($isServerClass && !$this->has($name)) {
462
+            return $this->getServer()->query($name, $autoload);
463
+        }
464
+
465
+        try {
466
+            return $this->queryNoFallback($name);
467
+        } catch (QueryException $firstException) {
468
+            try {
469
+                return $this->getServer()->query($name, $autoload);
470
+            } catch (QueryException $secondException) {
471
+                if ($firstException->getCode() === 1) {
472
+                    throw $secondException;
473
+                }
474
+                throw $firstException;
475
+            }
476
+        }
477
+    }
478
+
479
+    /**
480
+     * @param string $name
481
+     * @return mixed
482
+     * @throws QueryException if the query could not be resolved
483
+     */
484
+    public function queryNoFallback($name) {
485
+        $name = $this->sanitizeName($name);
486
+
487
+        if ($this->offsetExists($name)) {
488
+            return parent::query($name);
489
+        } elseif ($this->appName === 'settings' && str_starts_with($name, 'OC\\Settings\\')) {
490
+            return parent::query($name);
491
+        } elseif ($this->appName === 'core' && str_starts_with($name, 'OC\\Core\\')) {
492
+            return parent::query($name);
493
+        } elseif (str_starts_with($name, \OC\AppFramework\App::buildAppNamespace($this->appName) . '\\')) {
494
+            return parent::query($name);
495
+        }
496
+
497
+        throw new QueryException('Could not resolve ' . $name . '!' .
498
+            ' Class can not be instantiated', 1);
499
+    }
500 500
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/Attribute/BruteForceProtection.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -35,18 +35,18 @@
 block discarded – undo
35 35
  */
36 36
 #[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
37 37
 class BruteForceProtection {
38
-	/**
39
-	 * @since 27.0.0
40
-	 */
41
-	public function __construct(
42
-		protected string $action
43
-	) {
44
-	}
38
+    /**
39
+     * @since 27.0.0
40
+     */
41
+    public function __construct(
42
+        protected string $action
43
+    ) {
44
+    }
45 45
 
46
-	/**
47
-	 * @since 27.0.0
48
-	 */
49
-	public function getAction(): string {
50
-		return $this->action;
51
-	}
46
+    /**
47
+     * @since 27.0.0
48
+     */
49
+    public function getAction(): string {
50
+        return $this->action;
51
+    }
52 52
 }
Please login to merge, or discard this patch.