Passed
Push — master ( b2959d...2124d1 )
by Morris
12:31 queued 12s
created
lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php 2 patches
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -67,103 +67,103 @@  discard block
 block discarded – undo
67 67
  * check fails
68 68
  */
69 69
 class SecurityMiddleware extends Middleware {
70
-	/** @var INavigationManager */
71
-	private $navigationManager;
72
-	/** @var IRequest */
73
-	private $request;
74
-	/** @var ControllerMethodReflector */
75
-	private $reflector;
76
-	/** @var string */
77
-	private $appName;
78
-	/** @var IURLGenerator */
79
-	private $urlGenerator;
80
-	/** @var ILogger */
81
-	private $logger;
82
-	/** @var bool */
83
-	private $isLoggedIn;
84
-	/** @var bool */
85
-	private $isAdminUser;
86
-	/** @var bool */
87
-	private $isSubAdmin;
88
-	/** @var IAppManager */
89
-	private $appManager;
90
-	/** @var IL10N */
91
-	private $l10n;
92
-
93
-	public function __construct(IRequest $request,
94
-								ControllerMethodReflector $reflector,
95
-								INavigationManager $navigationManager,
96
-								IURLGenerator $urlGenerator,
97
-								ILogger $logger,
98
-								string $appName,
99
-								bool $isLoggedIn,
100
-								bool $isAdminUser,
101
-								bool $isSubAdmin,
102
-								IAppManager $appManager,
103
-								IL10N $l10n
104
-	) {
105
-		$this->navigationManager = $navigationManager;
106
-		$this->request = $request;
107
-		$this->reflector = $reflector;
108
-		$this->appName = $appName;
109
-		$this->urlGenerator = $urlGenerator;
110
-		$this->logger = $logger;
111
-		$this->isLoggedIn = $isLoggedIn;
112
-		$this->isAdminUser = $isAdminUser;
113
-		$this->isSubAdmin = $isSubAdmin;
114
-		$this->appManager = $appManager;
115
-		$this->l10n = $l10n;
116
-	}
117
-
118
-	/**
119
-	 * This runs all the security checks before a method call. The
120
-	 * security checks are determined by inspecting the controller method
121
-	 * annotations
122
-	 * @param Controller $controller the controller
123
-	 * @param string $methodName the name of the method
124
-	 * @throws SecurityException when a security check fails
125
-	 *
126
-	 * @suppress PhanUndeclaredClassConstant
127
-	 */
128
-	public function beforeController($controller, $methodName) {
129
-
130
-		// this will set the current navigation entry of the app, use this only
131
-		// for normal HTML requests and not for AJAX requests
132
-		$this->navigationManager->setActiveEntry($this->appName);
133
-
134
-		if (get_class($controller) === \OCA\Talk\Controller\PageController::class && $methodName === 'showCall') {
135
-			$this->navigationManager->setActiveEntry('spreed');
136
-		}
137
-
138
-		// security checks
139
-		$isPublicPage = $this->reflector->hasAnnotation('PublicPage');
140
-		if (!$isPublicPage) {
141
-			if (!$this->isLoggedIn) {
142
-				throw new NotLoggedInException();
143
-			}
144
-
145
-			if ($this->reflector->hasAnnotation('SubAdminRequired')
146
-				&& !$this->isSubAdmin
147
-				&& !$this->isAdminUser) {
148
-				throw new NotAdminException($this->l10n->t('Logged in user must be an admin or sub admin'));
149
-			}
150
-			if (!$this->reflector->hasAnnotation('SubAdminRequired')
151
-				&& !$this->reflector->hasAnnotation('NoAdminRequired')
152
-				&& !$this->isAdminUser) {
153
-				throw new NotAdminException($this->l10n->t('Logged in user must be an admin'));
154
-			}
155
-		}
156
-
157
-		// Check for strict cookie requirement
158
-		if ($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
159
-			if (!$this->request->passesStrictCookieCheck()) {
160
-				throw new StrictCookieMissingException();
161
-			}
162
-		}
163
-		// CSRF check - also registers the CSRF token since the session may be closed later
164
-		Util::callRegister();
165
-		if (!$this->reflector->hasAnnotation('NoCSRFRequired')) {
166
-			/*
70
+    /** @var INavigationManager */
71
+    private $navigationManager;
72
+    /** @var IRequest */
73
+    private $request;
74
+    /** @var ControllerMethodReflector */
75
+    private $reflector;
76
+    /** @var string */
77
+    private $appName;
78
+    /** @var IURLGenerator */
79
+    private $urlGenerator;
80
+    /** @var ILogger */
81
+    private $logger;
82
+    /** @var bool */
83
+    private $isLoggedIn;
84
+    /** @var bool */
85
+    private $isAdminUser;
86
+    /** @var bool */
87
+    private $isSubAdmin;
88
+    /** @var IAppManager */
89
+    private $appManager;
90
+    /** @var IL10N */
91
+    private $l10n;
92
+
93
+    public function __construct(IRequest $request,
94
+                                ControllerMethodReflector $reflector,
95
+                                INavigationManager $navigationManager,
96
+                                IURLGenerator $urlGenerator,
97
+                                ILogger $logger,
98
+                                string $appName,
99
+                                bool $isLoggedIn,
100
+                                bool $isAdminUser,
101
+                                bool $isSubAdmin,
102
+                                IAppManager $appManager,
103
+                                IL10N $l10n
104
+    ) {
105
+        $this->navigationManager = $navigationManager;
106
+        $this->request = $request;
107
+        $this->reflector = $reflector;
108
+        $this->appName = $appName;
109
+        $this->urlGenerator = $urlGenerator;
110
+        $this->logger = $logger;
111
+        $this->isLoggedIn = $isLoggedIn;
112
+        $this->isAdminUser = $isAdminUser;
113
+        $this->isSubAdmin = $isSubAdmin;
114
+        $this->appManager = $appManager;
115
+        $this->l10n = $l10n;
116
+    }
117
+
118
+    /**
119
+     * This runs all the security checks before a method call. The
120
+     * security checks are determined by inspecting the controller method
121
+     * annotations
122
+     * @param Controller $controller the controller
123
+     * @param string $methodName the name of the method
124
+     * @throws SecurityException when a security check fails
125
+     *
126
+     * @suppress PhanUndeclaredClassConstant
127
+     */
128
+    public function beforeController($controller, $methodName) {
129
+
130
+        // this will set the current navigation entry of the app, use this only
131
+        // for normal HTML requests and not for AJAX requests
132
+        $this->navigationManager->setActiveEntry($this->appName);
133
+
134
+        if (get_class($controller) === \OCA\Talk\Controller\PageController::class && $methodName === 'showCall') {
135
+            $this->navigationManager->setActiveEntry('spreed');
136
+        }
137
+
138
+        // security checks
139
+        $isPublicPage = $this->reflector->hasAnnotation('PublicPage');
140
+        if (!$isPublicPage) {
141
+            if (!$this->isLoggedIn) {
142
+                throw new NotLoggedInException();
143
+            }
144
+
145
+            if ($this->reflector->hasAnnotation('SubAdminRequired')
146
+                && !$this->isSubAdmin
147
+                && !$this->isAdminUser) {
148
+                throw new NotAdminException($this->l10n->t('Logged in user must be an admin or sub admin'));
149
+            }
150
+            if (!$this->reflector->hasAnnotation('SubAdminRequired')
151
+                && !$this->reflector->hasAnnotation('NoAdminRequired')
152
+                && !$this->isAdminUser) {
153
+                throw new NotAdminException($this->l10n->t('Logged in user must be an admin'));
154
+            }
155
+        }
156
+
157
+        // Check for strict cookie requirement
158
+        if ($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
159
+            if (!$this->request->passesStrictCookieCheck()) {
160
+                throw new StrictCookieMissingException();
161
+            }
162
+        }
163
+        // CSRF check - also registers the CSRF token since the session may be closed later
164
+        Util::callRegister();
165
+        if (!$this->reflector->hasAnnotation('NoCSRFRequired')) {
166
+            /*
167 167
 			 * Only allow the CSRF check to fail on OCS Requests. This kind of
168 168
 			 * hacks around that we have no full token auth in place yet and we
169 169
 			 * do want to offer CSRF checks for web requests.
@@ -171,74 +171,74 @@  discard block
 block discarded – undo
171 171
 			 * Additionally we allow Bearer authenticated requests to pass on OCS routes.
172 172
 			 * This allows oauth apps (e.g. moodle) to use the OCS endpoints
173 173
 			 */
174
-			if (!$this->request->passesCSRFCheck() && !(
175
-					$controller instanceof OCSController && (
176
-						$this->request->getHeader('OCS-APIREQUEST') === 'true' ||
177
-						strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
178
-					)
179
-				)) {
180
-				throw new CrossSiteRequestForgeryException();
181
-			}
182
-		}
183
-
184
-		/**
185
-		 * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
186
-		 * The getAppPath() check is here since components such as settings also use the AppFramework and
187
-		 * therefore won't pass this check.
188
-		 * If page is public, app does not need to be enabled for current user/visitor
189
-		 */
190
-		try {
191
-			$appPath = $this->appManager->getAppPath($this->appName);
192
-		} catch (AppPathNotFoundException $e) {
193
-			$appPath = false;
194
-		}
195
-
196
-		if ($appPath !== false && !$isPublicPage && !$this->appManager->isEnabledForUser($this->appName)) {
197
-			throw new AppNotEnabledException();
198
-		}
199
-	}
200
-
201
-	/**
202
-	 * If an SecurityException is being caught, ajax requests return a JSON error
203
-	 * response and non ajax requests redirect to the index
204
-	 * @param Controller $controller the controller that is being called
205
-	 * @param string $methodName the name of the method that will be called on
206
-	 *                           the controller
207
-	 * @param \Exception $exception the thrown exception
208
-	 * @throws \Exception the passed in exception if it can't handle it
209
-	 * @return Response a Response object or null in case that the exception could not be handled
210
-	 */
211
-	public function afterException($controller, $methodName, \Exception $exception): Response {
212
-		if ($exception instanceof SecurityException) {
213
-			if ($exception instanceof StrictCookieMissingException) {
214
-				return new RedirectResponse(\OC::$WEBROOT . '/');
215
-			}
216
-			if (stripos($this->request->getHeader('Accept'),'html') === false) {
217
-				$response = new JSONResponse(
218
-					['message' => $exception->getMessage()],
219
-					$exception->getCode()
220
-				);
221
-			} else {
222
-				if ($exception instanceof NotLoggedInException) {
223
-					$params = [];
224
-					if (isset($this->request->server['REQUEST_URI'])) {
225
-						$params['redirect_url'] = $this->request->server['REQUEST_URI'];
226
-					}
227
-					$url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
228
-					$response = new RedirectResponse($url);
229
-				} else {
230
-					$response = new TemplateResponse('core', '403', ['message' => $exception->getMessage()], 'guest');
231
-					$response->setStatus($exception->getCode());
232
-				}
233
-			}
234
-
235
-			$this->logger->logException($exception, [
236
-				'level' => ILogger::DEBUG,
237
-				'app' => 'core',
238
-			]);
239
-			return $response;
240
-		}
241
-
242
-		throw $exception;
243
-	}
174
+            if (!$this->request->passesCSRFCheck() && !(
175
+                    $controller instanceof OCSController && (
176
+                        $this->request->getHeader('OCS-APIREQUEST') === 'true' ||
177
+                        strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
178
+                    )
179
+                )) {
180
+                throw new CrossSiteRequestForgeryException();
181
+            }
182
+        }
183
+
184
+        /**
185
+         * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
186
+         * The getAppPath() check is here since components such as settings also use the AppFramework and
187
+         * therefore won't pass this check.
188
+         * If page is public, app does not need to be enabled for current user/visitor
189
+         */
190
+        try {
191
+            $appPath = $this->appManager->getAppPath($this->appName);
192
+        } catch (AppPathNotFoundException $e) {
193
+            $appPath = false;
194
+        }
195
+
196
+        if ($appPath !== false && !$isPublicPage && !$this->appManager->isEnabledForUser($this->appName)) {
197
+            throw new AppNotEnabledException();
198
+        }
199
+    }
200
+
201
+    /**
202
+     * If an SecurityException is being caught, ajax requests return a JSON error
203
+     * response and non ajax requests redirect to the index
204
+     * @param Controller $controller the controller that is being called
205
+     * @param string $methodName the name of the method that will be called on
206
+     *                           the controller
207
+     * @param \Exception $exception the thrown exception
208
+     * @throws \Exception the passed in exception if it can't handle it
209
+     * @return Response a Response object or null in case that the exception could not be handled
210
+     */
211
+    public function afterException($controller, $methodName, \Exception $exception): Response {
212
+        if ($exception instanceof SecurityException) {
213
+            if ($exception instanceof StrictCookieMissingException) {
214
+                return new RedirectResponse(\OC::$WEBROOT . '/');
215
+            }
216
+            if (stripos($this->request->getHeader('Accept'),'html') === false) {
217
+                $response = new JSONResponse(
218
+                    ['message' => $exception->getMessage()],
219
+                    $exception->getCode()
220
+                );
221
+            } else {
222
+                if ($exception instanceof NotLoggedInException) {
223
+                    $params = [];
224
+                    if (isset($this->request->server['REQUEST_URI'])) {
225
+                        $params['redirect_url'] = $this->request->server['REQUEST_URI'];
226
+                    }
227
+                    $url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
228
+                    $response = new RedirectResponse($url);
229
+                } else {
230
+                    $response = new TemplateResponse('core', '403', ['message' => $exception->getMessage()], 'guest');
231
+                    $response->setStatus($exception->getCode());
232
+                }
233
+            }
234
+
235
+            $this->logger->logException($exception, [
236
+                'level' => ILogger::DEBUG,
237
+                'app' => 'core',
238
+            ]);
239
+            return $response;
240
+        }
241
+
242
+        throw $exception;
243
+    }
244 244
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -211,9 +211,9 @@
 block discarded – undo
211 211
 	public function afterException($controller, $methodName, \Exception $exception): Response {
212 212
 		if ($exception instanceof SecurityException) {
213 213
 			if ($exception instanceof StrictCookieMissingException) {
214
-				return new RedirectResponse(\OC::$WEBROOT . '/');
214
+				return new RedirectResponse(\OC::$WEBROOT.'/');
215 215
 			}
216
-			if (stripos($this->request->getHeader('Accept'),'html') === false) {
216
+			if (stripos($this->request->getHeader('Accept'), 'html') === false) {
217 217
 				$response = new JSONResponse(
218 218
 					['message' => $exception->getMessage()],
219 219
 					$exception->getCode()
Please login to merge, or discard this patch.