Passed
Push — master ( 0df511...a1aa6e )
by Morris
13:44
created
lib/private/AppFramework/Middleware/Security/ReloadExecutionMiddleware.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -35,34 +35,34 @@
 block discarded – undo
35 35
  * a reload but if the session variable is set we properly redirect to the login page.
36 36
  */
37 37
 class ReloadExecutionMiddleware extends Middleware {
38
-	/** @var ISession */
39
-	private $session;
40
-	/** @var IURLGenerator */
41
-	private $urlGenerator;
38
+    /** @var ISession */
39
+    private $session;
40
+    /** @var IURLGenerator */
41
+    private $urlGenerator;
42 42
 
43
-	public function __construct(ISession $session, IURLGenerator $urlGenerator) {
44
-		$this->session = $session;
45
-		$this->urlGenerator = $urlGenerator;
46
-	}
43
+    public function __construct(ISession $session, IURLGenerator $urlGenerator) {
44
+        $this->session = $session;
45
+        $this->urlGenerator = $urlGenerator;
46
+    }
47 47
 
48
-	public function beforeController($controller, $methodName) {
49
-		if ($this->session->exists('clearingExecutionContexts')) {
50
-			throw new ReloadExecutionException();
51
-		}
52
-	}
48
+    public function beforeController($controller, $methodName) {
49
+        if ($this->session->exists('clearingExecutionContexts')) {
50
+            throw new ReloadExecutionException();
51
+        }
52
+    }
53 53
 
54
-	public function afterException($controller, $methodName, \Exception $exception) {
55
-		if ($exception instanceof ReloadExecutionException) {
56
-			$this->session->remove('clearingExecutionContexts');
54
+    public function afterException($controller, $methodName, \Exception $exception) {
55
+        if ($exception instanceof ReloadExecutionException) {
56
+            $this->session->remove('clearingExecutionContexts');
57 57
 
58
-			return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute(
59
-				'core.login.showLoginForm',
60
-				['clear' => true] // this param the the code in login.js may be removed when the "Clear-Site-Data" is working in the browsers
61
-			));
62
-		}
58
+            return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute(
59
+                'core.login.showLoginForm',
60
+                ['clear' => true] // this param the the code in login.js may be removed when the "Clear-Site-Data" is working in the browsers
61
+            ));
62
+        }
63 63
 
64
-		return parent::afterException($controller, $methodName, $exception);
65
-	}
64
+        return parent::afterException($controller, $methodName, $exception);
65
+    }
66 66
 
67 67
 
68 68
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 1 patch
Indentation   +343 added lines, -343 removed lines patch added patch discarded remove patch
@@ -68,347 +68,347 @@
 block discarded – undo
68 68
 
69 69
 class DIContainer extends SimpleContainer implements IAppContainer {
70 70
 
71
-	/**
72
-	 * @var array
73
-	 */
74
-	private $middleWares = [];
75
-
76
-	/** @var ServerContainer */
77
-	private $server;
78
-
79
-	/**
80
-	 * Put your class dependencies in here
81
-	 * @param string $appName the name of the app
82
-	 * @param array $urlParams
83
-	 * @param ServerContainer|null $server
84
-	 */
85
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
86
-		parent::__construct();
87
-		$this['AppName'] = $appName;
88
-		$this['urlParams'] = $urlParams;
89
-
90
-		$this->registerAlias('Request', IRequest::class);
91
-
92
-		/** @var \OC\ServerContainer $server */
93
-		if ($server === null) {
94
-			$server = \OC::$server;
95
-		}
96
-		$this->server = $server;
97
-		$this->server->registerAppContainer($appName, $this);
98
-
99
-		// aliases
100
-		$this->registerAlias('appName', 'AppName');
101
-		$this->registerAlias('webRoot', 'WebRoot');
102
-		$this->registerAlias('userId', 'UserId');
103
-
104
-		/**
105
-		 * Core services
106
-		 */
107
-		$this->registerService(IOutput::class, function(){
108
-			return new Output($this->getServer()->getWebRoot());
109
-		});
110
-
111
-		$this->registerService(Folder::class, function() {
112
-			return $this->getServer()->getUserFolder();
113
-		});
114
-
115
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
116
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
117
-		});
118
-
119
-		$this->registerService(IL10N::class, function($c) {
120
-			return $this->getServer()->getL10N($c->query('AppName'));
121
-		});
122
-
123
-		// Log wrapper
124
-		$this->registerService(ILogger::class, function ($c) {
125
-			return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->query('AppName'));
126
-		});
127
-
128
-		$this->registerService(IServerContainer::class, function () {
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(Manager::class);
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(IUserSession::class)->getSession()->get('user_id');
144
-		});
145
-
146
-		$this->registerService('WebRoot', function ($c) {
147
-			return $c->query('ServerContainer')->getWebRoot();
148
-		});
149
-
150
-		$this->registerService('OC_Defaults', function ($c) {
151
-			return $c->getServer()->getThemingDefaults();
152
-		});
153
-
154
-		$this->registerService(IConfig::class, function ($c) {
155
-			return $c->query(OC\GlobalScale\Config::class);
156
-		});
157
-
158
-		$this->registerService('Protocol', function($c){
159
-			/** @var \OC\Server $server */
160
-			$server = $c->query('ServerContainer');
161
-			$protocol = $server->getRequest()->getHttpProtocol();
162
-			return new Http($_SERVER, $protocol);
163
-		});
164
-
165
-		$this->registerService('Dispatcher', function($c) {
166
-			return new Dispatcher(
167
-				$c['Protocol'],
168
-				$c['MiddlewareDispatcher'],
169
-				$c->query(IControllerMethodReflector::class),
170
-				$c['Request']
171
-			);
172
-		});
173
-
174
-		/**
175
-		 * App Framework default arguments
176
-		 */
177
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
178
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
179
-		$this->registerParameter('corsMaxAge', 1728000);
180
-
181
-		/**
182
-		 * Middleware
183
-		 */
184
-		$this->registerService('MiddlewareDispatcher', function(SimpleContainer $c) {
185
-			$server =  $this->getServer();
186
-
187
-			$dispatcher = new MiddlewareDispatcher();
188
-			$dispatcher->registerMiddleware(
189
-				$c->query(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
190
-			);
191
-
192
-			$dispatcher->registerMiddleware(
193
-				new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
194
-					$c->query(IRequest::class),
195
-					$c->query(IControllerMethodReflector::class)
196
-				)
197
-			);
198
-			$dispatcher->registerMiddleware(
199
-				new CORSMiddleware(
200
-					$c->query(IRequest::class),
201
-					$c->query(IControllerMethodReflector::class),
202
-					$c->query(IUserSession::class),
203
-					$c->query(OC\Security\Bruteforce\Throttler::class)
204
-				)
205
-			);
206
-			$dispatcher->registerMiddleware(
207
-				new OCSMiddleware(
208
-					$c->query(IRequest::class)
209
-				)
210
-			);
211
-
212
-			$securityMiddleware = new SecurityMiddleware(
213
-				$c->query(IRequest::class),
214
-				$c->query(IControllerMethodReflector::class),
215
-				$c->query(INavigationManager::class),
216
-				$c->query(IURLGenerator::class),
217
-				$server->getLogger(),
218
-				$c['AppName'],
219
-				$server->getUserSession()->isLoggedIn(),
220
-				$server->getGroupManager()->isAdmin($this->getUserId()),
221
-				$server->getContentSecurityPolicyManager(),
222
-				$server->getCsrfTokenManager(),
223
-				$server->getContentSecurityPolicyNonceManager(),
224
-				$server->getAppManager(),
225
-				$server->getL10N('lib')
226
-			);
227
-			$dispatcher->registerMiddleware($securityMiddleware);
228
-			$dispatcher->registerMiddleware(
229
-				new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
230
-					$c->query(IControllerMethodReflector::class),
231
-					$c->query(ISession::class),
232
-					$c->query(IUserSession::class),
233
-					$c->query(ITimeFactory::class)
234
-				)
235
-			);
236
-			$dispatcher->registerMiddleware(
237
-				new TwoFactorMiddleware(
238
-					$c->query(OC\Authentication\TwoFactorAuth\Manager::class),
239
-					$c->query(IUserSession::class),
240
-					$c->query(ISession::class),
241
-					$c->query(IURLGenerator::class),
242
-					$c->query(IControllerMethodReflector::class),
243
-					$c->query(IRequest::class)
244
-				)
245
-			);
246
-			$dispatcher->registerMiddleware(
247
-				new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
248
-					$c->query(IControllerMethodReflector::class),
249
-					$c->query(OC\Security\Bruteforce\Throttler::class),
250
-					$c->query(IRequest::class)
251
-				)
252
-			);
253
-			$dispatcher->registerMiddleware(
254
-				new RateLimitingMiddleware(
255
-					$c->query(IRequest::class),
256
-					$c->query(IUserSession::class),
257
-					$c->query(IControllerMethodReflector::class),
258
-					$c->query(OC\Security\RateLimiting\Limiter::class)
259
-				)
260
-			);
261
-			$dispatcher->registerMiddleware(
262
-				new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
263
-					$c->query(IRequest::class),
264
-					$c->query(ISession::class),
265
-					$c->query(\OCP\IConfig::class)
266
-				)
267
-			);
268
-			$dispatcher->registerMiddleware(
269
-				$c->query(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
270
-			);
271
-
272
-			foreach($this->middleWares as $middleWare) {
273
-				$dispatcher->registerMiddleware($c[$middleWare]);
274
-			}
275
-
276
-			$dispatcher->registerMiddleware(
277
-				new SessionMiddleware(
278
-					$c->query(IRequest::class),
279
-					$c->query(IControllerMethodReflector::class),
280
-					$c->query(ISession::class)
281
-				)
282
-			);
283
-			return $dispatcher;
284
-		});
285
-
286
-	}
287
-
288
-	/**
289
-	 * @return \OCP\IServerContainer
290
-	 */
291
-	public function getServer()
292
-	{
293
-		return $this->server;
294
-	}
295
-
296
-	/**
297
-	 * @param string $middleWare
298
-	 * @return boolean|null
299
-	 */
300
-	public function registerMiddleWare($middleWare) {
301
-		$this->middleWares[] = $middleWare;
302
-	}
303
-
304
-	/**
305
-	 * used to return the appname of the set application
306
-	 * @return string the name of your application
307
-	 */
308
-	public function getAppName() {
309
-		return $this->query('AppName');
310
-	}
311
-
312
-	/**
313
-	 * @deprecated use IUserSession->isLoggedIn()
314
-	 * @return boolean
315
-	 */
316
-	public function isLoggedIn() {
317
-		return \OC::$server->getUserSession()->isLoggedIn();
318
-	}
319
-
320
-	/**
321
-	 * @deprecated use IGroupManager->isAdmin($userId)
322
-	 * @return boolean
323
-	 */
324
-	public function isAdminUser() {
325
-		$uid = $this->getUserId();
326
-		return \OC_User::isAdminUser($uid);
327
-	}
328
-
329
-	private function getUserId() {
330
-		return $this->getServer()->getSession()->get('user_id');
331
-	}
332
-
333
-	/**
334
-	 * @deprecated use the ILogger instead
335
-	 * @param string $message
336
-	 * @param string $level
337
-	 * @return mixed
338
-	 */
339
-	public function log($message, $level) {
340
-		switch($level){
341
-			case 'debug':
342
-				$level = ILogger::DEBUG;
343
-				break;
344
-			case 'info':
345
-				$level = ILogger::INFO;
346
-				break;
347
-			case 'warn':
348
-				$level = ILogger::WARN;
349
-				break;
350
-			case 'fatal':
351
-				$level = ILogger::FATAL;
352
-				break;
353
-			default:
354
-				$level = ILogger::ERROR;
355
-				break;
356
-		}
357
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
358
-	}
359
-
360
-	/**
361
-	 * Register a capability
362
-	 *
363
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
364
-	 */
365
-	public function registerCapability($serviceName) {
366
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
367
-			return $this->query($serviceName);
368
-		});
369
-	}
370
-
371
-	/**
372
-	 * @param string $name
373
-	 * @return mixed
374
-	 * @throws QueryException if the query could not be resolved
375
-	 */
376
-	public function query($name) {
377
-		try {
378
-			return $this->queryNoFallback($name);
379
-		} catch (QueryException $firstException) {
380
-			try {
381
-				return $this->getServer()->query($name);
382
-			} catch (QueryException $secondException) {
383
-				if ($firstException->getCode() === 1) {
384
-					throw $secondException;
385
-				}
386
-				throw $firstException;
387
-			}
388
-		}
389
-	}
390
-
391
-	/**
392
-	 * @param string $name
393
-	 * @return mixed
394
-	 * @throws QueryException if the query could not be resolved
395
-	 */
396
-	public function queryNoFallback($name) {
397
-		$name = $this->sanitizeName($name);
398
-
399
-		if ($this->offsetExists($name)) {
400
-			return parent::query($name);
401
-		} else {
402
-			if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
403
-				return parent::query($name);
404
-			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
405
-				return parent::query($name);
406
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
407
-				return parent::query($name);
408
-			}
409
-		}
410
-
411
-		throw new QueryException('Could not resolve ' . $name . '!' .
412
-			' Class can not be instantiated', 1);
413
-	}
71
+    /**
72
+     * @var array
73
+     */
74
+    private $middleWares = [];
75
+
76
+    /** @var ServerContainer */
77
+    private $server;
78
+
79
+    /**
80
+     * Put your class dependencies in here
81
+     * @param string $appName the name of the app
82
+     * @param array $urlParams
83
+     * @param ServerContainer|null $server
84
+     */
85
+    public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
86
+        parent::__construct();
87
+        $this['AppName'] = $appName;
88
+        $this['urlParams'] = $urlParams;
89
+
90
+        $this->registerAlias('Request', IRequest::class);
91
+
92
+        /** @var \OC\ServerContainer $server */
93
+        if ($server === null) {
94
+            $server = \OC::$server;
95
+        }
96
+        $this->server = $server;
97
+        $this->server->registerAppContainer($appName, $this);
98
+
99
+        // aliases
100
+        $this->registerAlias('appName', 'AppName');
101
+        $this->registerAlias('webRoot', 'WebRoot');
102
+        $this->registerAlias('userId', 'UserId');
103
+
104
+        /**
105
+         * Core services
106
+         */
107
+        $this->registerService(IOutput::class, function(){
108
+            return new Output($this->getServer()->getWebRoot());
109
+        });
110
+
111
+        $this->registerService(Folder::class, function() {
112
+            return $this->getServer()->getUserFolder();
113
+        });
114
+
115
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
116
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
117
+        });
118
+
119
+        $this->registerService(IL10N::class, function($c) {
120
+            return $this->getServer()->getL10N($c->query('AppName'));
121
+        });
122
+
123
+        // Log wrapper
124
+        $this->registerService(ILogger::class, function ($c) {
125
+            return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->query('AppName'));
126
+        });
127
+
128
+        $this->registerService(IServerContainer::class, function () {
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(Manager::class);
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(IUserSession::class)->getSession()->get('user_id');
144
+        });
145
+
146
+        $this->registerService('WebRoot', function ($c) {
147
+            return $c->query('ServerContainer')->getWebRoot();
148
+        });
149
+
150
+        $this->registerService('OC_Defaults', function ($c) {
151
+            return $c->getServer()->getThemingDefaults();
152
+        });
153
+
154
+        $this->registerService(IConfig::class, function ($c) {
155
+            return $c->query(OC\GlobalScale\Config::class);
156
+        });
157
+
158
+        $this->registerService('Protocol', function($c){
159
+            /** @var \OC\Server $server */
160
+            $server = $c->query('ServerContainer');
161
+            $protocol = $server->getRequest()->getHttpProtocol();
162
+            return new Http($_SERVER, $protocol);
163
+        });
164
+
165
+        $this->registerService('Dispatcher', function($c) {
166
+            return new Dispatcher(
167
+                $c['Protocol'],
168
+                $c['MiddlewareDispatcher'],
169
+                $c->query(IControllerMethodReflector::class),
170
+                $c['Request']
171
+            );
172
+        });
173
+
174
+        /**
175
+         * App Framework default arguments
176
+         */
177
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
178
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
179
+        $this->registerParameter('corsMaxAge', 1728000);
180
+
181
+        /**
182
+         * Middleware
183
+         */
184
+        $this->registerService('MiddlewareDispatcher', function(SimpleContainer $c) {
185
+            $server =  $this->getServer();
186
+
187
+            $dispatcher = new MiddlewareDispatcher();
188
+            $dispatcher->registerMiddleware(
189
+                $c->query(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
190
+            );
191
+
192
+            $dispatcher->registerMiddleware(
193
+                new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
194
+                    $c->query(IRequest::class),
195
+                    $c->query(IControllerMethodReflector::class)
196
+                )
197
+            );
198
+            $dispatcher->registerMiddleware(
199
+                new CORSMiddleware(
200
+                    $c->query(IRequest::class),
201
+                    $c->query(IControllerMethodReflector::class),
202
+                    $c->query(IUserSession::class),
203
+                    $c->query(OC\Security\Bruteforce\Throttler::class)
204
+                )
205
+            );
206
+            $dispatcher->registerMiddleware(
207
+                new OCSMiddleware(
208
+                    $c->query(IRequest::class)
209
+                )
210
+            );
211
+
212
+            $securityMiddleware = new SecurityMiddleware(
213
+                $c->query(IRequest::class),
214
+                $c->query(IControllerMethodReflector::class),
215
+                $c->query(INavigationManager::class),
216
+                $c->query(IURLGenerator::class),
217
+                $server->getLogger(),
218
+                $c['AppName'],
219
+                $server->getUserSession()->isLoggedIn(),
220
+                $server->getGroupManager()->isAdmin($this->getUserId()),
221
+                $server->getContentSecurityPolicyManager(),
222
+                $server->getCsrfTokenManager(),
223
+                $server->getContentSecurityPolicyNonceManager(),
224
+                $server->getAppManager(),
225
+                $server->getL10N('lib')
226
+            );
227
+            $dispatcher->registerMiddleware($securityMiddleware);
228
+            $dispatcher->registerMiddleware(
229
+                new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
230
+                    $c->query(IControllerMethodReflector::class),
231
+                    $c->query(ISession::class),
232
+                    $c->query(IUserSession::class),
233
+                    $c->query(ITimeFactory::class)
234
+                )
235
+            );
236
+            $dispatcher->registerMiddleware(
237
+                new TwoFactorMiddleware(
238
+                    $c->query(OC\Authentication\TwoFactorAuth\Manager::class),
239
+                    $c->query(IUserSession::class),
240
+                    $c->query(ISession::class),
241
+                    $c->query(IURLGenerator::class),
242
+                    $c->query(IControllerMethodReflector::class),
243
+                    $c->query(IRequest::class)
244
+                )
245
+            );
246
+            $dispatcher->registerMiddleware(
247
+                new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
248
+                    $c->query(IControllerMethodReflector::class),
249
+                    $c->query(OC\Security\Bruteforce\Throttler::class),
250
+                    $c->query(IRequest::class)
251
+                )
252
+            );
253
+            $dispatcher->registerMiddleware(
254
+                new RateLimitingMiddleware(
255
+                    $c->query(IRequest::class),
256
+                    $c->query(IUserSession::class),
257
+                    $c->query(IControllerMethodReflector::class),
258
+                    $c->query(OC\Security\RateLimiting\Limiter::class)
259
+                )
260
+            );
261
+            $dispatcher->registerMiddleware(
262
+                new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
263
+                    $c->query(IRequest::class),
264
+                    $c->query(ISession::class),
265
+                    $c->query(\OCP\IConfig::class)
266
+                )
267
+            );
268
+            $dispatcher->registerMiddleware(
269
+                $c->query(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
270
+            );
271
+
272
+            foreach($this->middleWares as $middleWare) {
273
+                $dispatcher->registerMiddleware($c[$middleWare]);
274
+            }
275
+
276
+            $dispatcher->registerMiddleware(
277
+                new SessionMiddleware(
278
+                    $c->query(IRequest::class),
279
+                    $c->query(IControllerMethodReflector::class),
280
+                    $c->query(ISession::class)
281
+                )
282
+            );
283
+            return $dispatcher;
284
+        });
285
+
286
+    }
287
+
288
+    /**
289
+     * @return \OCP\IServerContainer
290
+     */
291
+    public function getServer()
292
+    {
293
+        return $this->server;
294
+    }
295
+
296
+    /**
297
+     * @param string $middleWare
298
+     * @return boolean|null
299
+     */
300
+    public function registerMiddleWare($middleWare) {
301
+        $this->middleWares[] = $middleWare;
302
+    }
303
+
304
+    /**
305
+     * used to return the appname of the set application
306
+     * @return string the name of your application
307
+     */
308
+    public function getAppName() {
309
+        return $this->query('AppName');
310
+    }
311
+
312
+    /**
313
+     * @deprecated use IUserSession->isLoggedIn()
314
+     * @return boolean
315
+     */
316
+    public function isLoggedIn() {
317
+        return \OC::$server->getUserSession()->isLoggedIn();
318
+    }
319
+
320
+    /**
321
+     * @deprecated use IGroupManager->isAdmin($userId)
322
+     * @return boolean
323
+     */
324
+    public function isAdminUser() {
325
+        $uid = $this->getUserId();
326
+        return \OC_User::isAdminUser($uid);
327
+    }
328
+
329
+    private function getUserId() {
330
+        return $this->getServer()->getSession()->get('user_id');
331
+    }
332
+
333
+    /**
334
+     * @deprecated use the ILogger instead
335
+     * @param string $message
336
+     * @param string $level
337
+     * @return mixed
338
+     */
339
+    public function log($message, $level) {
340
+        switch($level){
341
+            case 'debug':
342
+                $level = ILogger::DEBUG;
343
+                break;
344
+            case 'info':
345
+                $level = ILogger::INFO;
346
+                break;
347
+            case 'warn':
348
+                $level = ILogger::WARN;
349
+                break;
350
+            case 'fatal':
351
+                $level = ILogger::FATAL;
352
+                break;
353
+            default:
354
+                $level = ILogger::ERROR;
355
+                break;
356
+        }
357
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
358
+    }
359
+
360
+    /**
361
+     * Register a capability
362
+     *
363
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
364
+     */
365
+    public function registerCapability($serviceName) {
366
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
367
+            return $this->query($serviceName);
368
+        });
369
+    }
370
+
371
+    /**
372
+     * @param string $name
373
+     * @return mixed
374
+     * @throws QueryException if the query could not be resolved
375
+     */
376
+    public function query($name) {
377
+        try {
378
+            return $this->queryNoFallback($name);
379
+        } catch (QueryException $firstException) {
380
+            try {
381
+                return $this->getServer()->query($name);
382
+            } catch (QueryException $secondException) {
383
+                if ($firstException->getCode() === 1) {
384
+                    throw $secondException;
385
+                }
386
+                throw $firstException;
387
+            }
388
+        }
389
+    }
390
+
391
+    /**
392
+     * @param string $name
393
+     * @return mixed
394
+     * @throws QueryException if the query could not be resolved
395
+     */
396
+    public function queryNoFallback($name) {
397
+        $name = $this->sanitizeName($name);
398
+
399
+        if ($this->offsetExists($name)) {
400
+            return parent::query($name);
401
+        } else {
402
+            if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
403
+                return parent::query($name);
404
+            } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
405
+                return parent::query($name);
406
+            } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
407
+                return parent::query($name);
408
+            }
409
+        }
410
+
411
+        throw new QueryException('Could not resolve ' . $name . '!' .
412
+            ' Class can not be instantiated', 1);
413
+    }
414 414
 }
Please login to merge, or discard this patch.
core/Controller/LoginController.php 1 patch
Indentation   +376 added lines, -376 removed lines patch added patch discarded remove patch
@@ -59,380 +59,380 @@
 block discarded – undo
59 59
 
60 60
 class LoginController extends Controller {
61 61
 
62
-	const LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword';
63
-	const LOGIN_MSG_USERDISABLED = 'userdisabled';
64
-
65
-	/** @var IUserManager */
66
-	private $userManager;
67
-	/** @var IConfig */
68
-	private $config;
69
-	/** @var ISession */
70
-	private $session;
71
-	/** @var IUserSession|Session */
72
-	private $userSession;
73
-	/** @var IURLGenerator */
74
-	private $urlGenerator;
75
-	/** @var ILogger */
76
-	private $logger;
77
-	/** @var Manager */
78
-	private $twoFactorManager;
79
-	/** @var Defaults */
80
-	private $defaults;
81
-	/** @var Throttler */
82
-	private $throttler;
83
-
84
-	/**
85
-	 * @param string $appName
86
-	 * @param IRequest $request
87
-	 * @param IUserManager $userManager
88
-	 * @param IConfig $config
89
-	 * @param ISession $session
90
-	 * @param IUserSession $userSession
91
-	 * @param IURLGenerator $urlGenerator
92
-	 * @param ILogger $logger
93
-	 * @param Manager $twoFactorManager
94
-	 * @param Defaults $defaults
95
-	 * @param Throttler $throttler
96
-	 */
97
-	public function __construct($appName,
98
-								IRequest $request,
99
-								IUserManager $userManager,
100
-								IConfig $config,
101
-								ISession $session,
102
-								IUserSession $userSession,
103
-								IURLGenerator $urlGenerator,
104
-								ILogger $logger,
105
-								Manager $twoFactorManager,
106
-								Defaults $defaults,
107
-								Throttler $throttler) {
108
-		parent::__construct($appName, $request);
109
-		$this->userManager = $userManager;
110
-		$this->config = $config;
111
-		$this->session = $session;
112
-		$this->userSession = $userSession;
113
-		$this->urlGenerator = $urlGenerator;
114
-		$this->logger = $logger;
115
-		$this->twoFactorManager = $twoFactorManager;
116
-		$this->defaults = $defaults;
117
-		$this->throttler = $throttler;
118
-	}
119
-
120
-	/**
121
-	 * @NoAdminRequired
122
-	 * @UseSession
123
-	 *
124
-	 * @return RedirectResponse
125
-	 */
126
-	public function logout() {
127
-		$loginToken = $this->request->getCookie('nc_token');
128
-		if (!is_null($loginToken)) {
129
-			$this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
130
-		}
131
-		$this->userSession->logout();
132
-
133
-		$response = new RedirectResponse($this->urlGenerator->linkToRouteAbsolute(
134
-			'core.login.showLoginForm',
135
-			['clear' => true] // this param the the code in login.js may be removed when the "Clear-Site-Data" is working in the browsers
136
-		));
137
-
138
-		$this->session->set('clearingExecutionContexts', '1');
139
-		$this->session->close();
140
-		$response->addHeader('Clear-Site-Data', '"cache", "storage", "executionContexts"');
141
-		return $response;
142
-	}
143
-
144
-	/**
145
-	 * @PublicPage
146
-	 * @NoCSRFRequired
147
-	 * @UseSession
148
-	 *
149
-	 * @param string $user
150
-	 * @param string $redirect_url
151
-	 *
152
-	 * @return TemplateResponse|RedirectResponse
153
-	 */
154
-	public function showLoginForm(string $user = null, string $redirect_url = null): Http\Response {
155
-		if ($this->userSession->isLoggedIn()) {
156
-			return new RedirectResponse(OC_Util::getDefaultPageUrl());
157
-		}
158
-
159
-		$parameters = array();
160
-		$loginMessages = $this->session->get('loginMessages');
161
-		$errors = [];
162
-		$messages = [];
163
-		if (is_array($loginMessages)) {
164
-			list($errors, $messages) = $loginMessages;
165
-		}
166
-		$this->session->remove('loginMessages');
167
-		foreach ($errors as $value) {
168
-			$parameters[$value] = true;
169
-		}
170
-
171
-		$parameters['messages'] = $messages;
172
-		if ($user !== null && $user !== '') {
173
-			$parameters['loginName'] = $user;
174
-			$parameters['user_autofocus'] = false;
175
-		} else {
176
-			$parameters['loginName'] = '';
177
-			$parameters['user_autofocus'] = true;
178
-		}
179
-
180
-		$autocomplete = $this->config->getSystemValue('login_form_autocomplete', true);
181
-		if ($autocomplete){
182
-			$parameters['login_form_autocomplete'] = 'on';
183
-		} else {
184
-			$parameters['login_form_autocomplete'] = 'off';
185
-		}
186
-
187
-		if (!empty($redirect_url)) {
188
-			$parameters['redirect_url'] = $redirect_url;
189
-		}
190
-
191
-		$parameters = $this->setPasswordResetParameters($user, $parameters);
192
-		$parameters['alt_login'] = OC_App::getAlternativeLogIns();
193
-
194
-		if ($user !== null && $user !== '') {
195
-			$parameters['loginName'] = $user;
196
-			$parameters['user_autofocus'] = false;
197
-		} else {
198
-			$parameters['loginName'] = '';
199
-			$parameters['user_autofocus'] = true;
200
-		}
201
-
202
-		$parameters['throttle_delay'] = $this->throttler->getDelay($this->request->getRemoteAddress());
203
-
204
-		// OpenGraph Support: http://ogp.me/
205
-		Util::addHeader('meta', ['property' => 'og:title', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
206
-		Util::addHeader('meta', ['property' => 'og:description', 'content' => Util::sanitizeHTML($this->defaults->getSlogan())]);
207
-		Util::addHeader('meta', ['property' => 'og:site_name', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
208
-		Util::addHeader('meta', ['property' => 'og:url', 'content' => $this->urlGenerator->getAbsoluteURL('/')]);
209
-		Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
210
-		Util::addHeader('meta', ['property' => 'og:image', 'content' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-touch.png'))]);
211
-
212
-		return new TemplateResponse(
213
-			$this->appName, 'login', $parameters, 'guest'
214
-		);
215
-	}
216
-
217
-	/**
218
-	 * Sets the password reset params.
219
-	 *
220
-	 * Users may not change their passwords if:
221
-	 * - The account is disabled
222
-	 * - The backend doesn't support password resets
223
-	 * - The password reset function is disabled
224
-	 *
225
-	 * @param string $user
226
-	 * @param array $parameters
227
-	 * @return array
228
-	 */
229
-	private function setPasswordResetParameters(
230
-		string $user = null, array $parameters): array {
231
-		if ($user !== null && $user !== '') {
232
-			$userObj = $this->userManager->get($user);
233
-		} else {
234
-			$userObj = null;
235
-		}
236
-
237
-		$parameters['resetPasswordLink'] = $this->config
238
-			->getSystemValue('lost_password_link', '');
239
-
240
-		if ($parameters['resetPasswordLink'] === 'disabled') {
241
-			$parameters['canResetPassword'] = false;
242
-		} else if (!$parameters['resetPasswordLink'] && $userObj !== null) {
243
-			$parameters['canResetPassword'] = $userObj->canChangePassword();
244
-		} else if ($userObj !== null && $userObj->isEnabled() === false) {
245
-			$parameters['canResetPassword'] = false;
246
-		} else {
247
-			$parameters['canResetPassword'] = true;
248
-		}
249
-
250
-		return $parameters;
251
-	}
252
-
253
-	/**
254
-	 * @param string $redirectUrl
255
-	 * @return RedirectResponse
256
-	 */
257
-	private function generateRedirect($redirectUrl) {
258
-		if (!is_null($redirectUrl) && $this->userSession->isLoggedIn()) {
259
-			$location = $this->urlGenerator->getAbsoluteURL(urldecode($redirectUrl));
260
-			// Deny the redirect if the URL contains a @
261
-			// This prevents unvalidated redirects like ?redirect_url=:[email protected]
262
-			if (strpos($location, '@') === false) {
263
-				return new RedirectResponse($location);
264
-			}
265
-		}
266
-		return new RedirectResponse(OC_Util::getDefaultPageUrl());
267
-	}
268
-
269
-	/**
270
-	 * @PublicPage
271
-	 * @UseSession
272
-	 * @NoCSRFRequired
273
-	 * @BruteForceProtection(action=login)
274
-	 *
275
-	 * @param string $user
276
-	 * @param string $password
277
-	 * @param string $redirect_url
278
-	 * @param boolean $remember_login
279
-	 * @param string $timezone
280
-	 * @param string $timezone_offset
281
-	 * @return RedirectResponse
282
-	 */
283
-	public function tryLogin($user, $password, $redirect_url, $remember_login = true, $timezone = '', $timezone_offset = '') {
284
-		if(!is_string($user)) {
285
-			throw new \InvalidArgumentException('Username must be string');
286
-		}
287
-
288
-		// If the user is already logged in and the CSRF check does not pass then
289
-		// simply redirect the user to the correct page as required. This is the
290
-		// case when an user has already logged-in, in another tab.
291
-		if(!$this->request->passesCSRFCheck()) {
292
-			return $this->generateRedirect($redirect_url);
293
-		}
294
-
295
-		if ($this->userManager instanceof PublicEmitter) {
296
-			$this->userManager->emit('\OC\User', 'preLogin', array($user, $password));
297
-		}
298
-
299
-		$originalUser = $user;
300
-
301
-		$userObj = $this->userManager->get($user);
302
-
303
-		if ($userObj !== null && $userObj->isEnabled() === false) {
304
-			$this->logger->warning('Login failed: \''. $user . '\' disabled' .
305
-				' (Remote IP: \''. $this->request->getRemoteAddress(). '\')',
306
-				['app' => 'core']);
307
-			return $this->createLoginFailedResponse($user, $originalUser,
308
-				$redirect_url, self::LOGIN_MSG_USERDISABLED);
309
-		}
310
-
311
-		// TODO: Add all the insane error handling
312
-		/* @var $loginResult IUser */
313
-		$loginResult = $this->userManager->checkPasswordNoLogging($user, $password);
314
-		if ($loginResult === false) {
315
-			$users = $this->userManager->getByEmail($user);
316
-			// we only allow login by email if unique
317
-			if (count($users) === 1) {
318
-				$previousUser = $user;
319
-				$user = $users[0]->getUID();
320
-				if($user !== $previousUser) {
321
-					$loginResult = $this->userManager->checkPassword($user, $password);
322
-				}
323
-			}
324
-		}
325
-
326
-		if ($loginResult === false) {
327
-			$this->logger->warning('Login failed: \''. $user .
328
-				'\' (Remote IP: \''. $this->request->getRemoteAddress(). '\')',
329
-				['app' => 'core']);
330
-			return $this->createLoginFailedResponse($user, $originalUser,
331
-				$redirect_url, self::LOGIN_MSG_INVALIDPASSWORD);
332
-		}
333
-
334
-		// TODO: remove password checks from above and let the user session handle failures
335
-		// requires https://github.com/owncloud/core/pull/24616
336
-		$this->userSession->completeLogin($loginResult, ['loginName' => $user, 'password' => $password]);
337
-
338
-		$tokenType = IToken::REMEMBER;
339
-		if ((int)$this->config->getSystemValue('remember_login_cookie_lifetime', 60*60*24*15) === 0) {
340
-			$remember_login = false;
341
-			$tokenType = IToken::DO_NOT_REMEMBER;
342
-		}
343
-
344
-		$this->userSession->createSessionToken($this->request, $loginResult->getUID(), $user, $password, $tokenType);
345
-		$this->userSession->updateTokens($loginResult->getUID(), $password);
346
-
347
-		// User has successfully logged in, now remove the password reset link, when it is available
348
-		$this->config->deleteUserValue($loginResult->getUID(), 'core', 'lostpassword');
349
-
350
-		$this->session->set('last-password-confirm', $loginResult->getLastLogin());
351
-
352
-		if ($timezone_offset !== '') {
353
-			$this->config->setUserValue($loginResult->getUID(), 'core', 'timezone', $timezone);
354
-			$this->session->set('timezone', $timezone_offset);
355
-		}
356
-
357
-		if ($this->twoFactorManager->isTwoFactorAuthenticated($loginResult)) {
358
-			$this->twoFactorManager->prepareTwoFactorLogin($loginResult, $remember_login);
359
-
360
-			$providers = $this->twoFactorManager->getProviderSet($loginResult)->getPrimaryProviders();
361
-			if (count($providers) === 1) {
362
-				// Single provider, hence we can redirect to that provider's challenge page directly
363
-				/* @var $provider IProvider */
364
-				$provider = array_pop($providers);
365
-				$url = 'core.TwoFactorChallenge.showChallenge';
366
-				$urlParams = [
367
-					'challengeProviderId' => $provider->getId(),
368
-				];
369
-			} else {
370
-				$url = 'core.TwoFactorChallenge.selectChallenge';
371
-				$urlParams = [];
372
-			}
373
-
374
-			if (!is_null($redirect_url)) {
375
-				$urlParams['redirect_url'] = $redirect_url;
376
-			}
377
-
378
-			return new RedirectResponse($this->urlGenerator->linkToRoute($url, $urlParams));
379
-		}
380
-
381
-		if ($remember_login) {
382
-			$this->userSession->createRememberMeToken($loginResult);
383
-		}
384
-
385
-		return $this->generateRedirect($redirect_url);
386
-	}
387
-
388
-	/**
389
-	 * Creates a login failed response.
390
-	 *
391
-	 * @param string $user
392
-	 * @param string $originalUser
393
-	 * @param string $redirect_url
394
-	 * @param string $loginMessage
395
-	 * @return RedirectResponse
396
-	 */
397
-	private function createLoginFailedResponse(
398
-		$user, $originalUser, $redirect_url, string $loginMessage) {
399
-		// Read current user and append if possible we need to
400
-		// return the unmodified user otherwise we will leak the login name
401
-		$args = !is_null($user) ? ['user' => $originalUser] : [];
402
-		if (!is_null($redirect_url)) {
403
-			$args['redirect_url'] = $redirect_url;
404
-		}
405
-		$response = new RedirectResponse(
406
-			$this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)
407
-		);
408
-		$response->throttle(['user' => substr($user, 0, 64)]);
409
-		$this->session->set('loginMessages', [
410
-			[$loginMessage], []
411
-		]);
412
-		return $response;
413
-	}
414
-
415
-	/**
416
-	 * @NoAdminRequired
417
-	 * @UseSession
418
-	 * @BruteForceProtection(action=sudo)
419
-	 *
420
-	 * @license GNU AGPL version 3 or any later version
421
-	 *
422
-	 * @param string $password
423
-	 * @return DataResponse
424
-	 */
425
-	public function confirmPassword($password) {
426
-		$loginName = $this->userSession->getLoginName();
427
-		$loginResult = $this->userManager->checkPassword($loginName, $password);
428
-		if ($loginResult === false) {
429
-			$response = new DataResponse([], Http::STATUS_FORBIDDEN);
430
-			$response->throttle();
431
-			return $response;
432
-		}
433
-
434
-		$confirmTimestamp = time();
435
-		$this->session->set('last-password-confirm', $confirmTimestamp);
436
-		return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
437
-	}
62
+    const LOGIN_MSG_INVALIDPASSWORD = 'invalidpassword';
63
+    const LOGIN_MSG_USERDISABLED = 'userdisabled';
64
+
65
+    /** @var IUserManager */
66
+    private $userManager;
67
+    /** @var IConfig */
68
+    private $config;
69
+    /** @var ISession */
70
+    private $session;
71
+    /** @var IUserSession|Session */
72
+    private $userSession;
73
+    /** @var IURLGenerator */
74
+    private $urlGenerator;
75
+    /** @var ILogger */
76
+    private $logger;
77
+    /** @var Manager */
78
+    private $twoFactorManager;
79
+    /** @var Defaults */
80
+    private $defaults;
81
+    /** @var Throttler */
82
+    private $throttler;
83
+
84
+    /**
85
+     * @param string $appName
86
+     * @param IRequest $request
87
+     * @param IUserManager $userManager
88
+     * @param IConfig $config
89
+     * @param ISession $session
90
+     * @param IUserSession $userSession
91
+     * @param IURLGenerator $urlGenerator
92
+     * @param ILogger $logger
93
+     * @param Manager $twoFactorManager
94
+     * @param Defaults $defaults
95
+     * @param Throttler $throttler
96
+     */
97
+    public function __construct($appName,
98
+                                IRequest $request,
99
+                                IUserManager $userManager,
100
+                                IConfig $config,
101
+                                ISession $session,
102
+                                IUserSession $userSession,
103
+                                IURLGenerator $urlGenerator,
104
+                                ILogger $logger,
105
+                                Manager $twoFactorManager,
106
+                                Defaults $defaults,
107
+                                Throttler $throttler) {
108
+        parent::__construct($appName, $request);
109
+        $this->userManager = $userManager;
110
+        $this->config = $config;
111
+        $this->session = $session;
112
+        $this->userSession = $userSession;
113
+        $this->urlGenerator = $urlGenerator;
114
+        $this->logger = $logger;
115
+        $this->twoFactorManager = $twoFactorManager;
116
+        $this->defaults = $defaults;
117
+        $this->throttler = $throttler;
118
+    }
119
+
120
+    /**
121
+     * @NoAdminRequired
122
+     * @UseSession
123
+     *
124
+     * @return RedirectResponse
125
+     */
126
+    public function logout() {
127
+        $loginToken = $this->request->getCookie('nc_token');
128
+        if (!is_null($loginToken)) {
129
+            $this->config->deleteUserValue($this->userSession->getUser()->getUID(), 'login_token', $loginToken);
130
+        }
131
+        $this->userSession->logout();
132
+
133
+        $response = new RedirectResponse($this->urlGenerator->linkToRouteAbsolute(
134
+            'core.login.showLoginForm',
135
+            ['clear' => true] // this param the the code in login.js may be removed when the "Clear-Site-Data" is working in the browsers
136
+        ));
137
+
138
+        $this->session->set('clearingExecutionContexts', '1');
139
+        $this->session->close();
140
+        $response->addHeader('Clear-Site-Data', '"cache", "storage", "executionContexts"');
141
+        return $response;
142
+    }
143
+
144
+    /**
145
+     * @PublicPage
146
+     * @NoCSRFRequired
147
+     * @UseSession
148
+     *
149
+     * @param string $user
150
+     * @param string $redirect_url
151
+     *
152
+     * @return TemplateResponse|RedirectResponse
153
+     */
154
+    public function showLoginForm(string $user = null, string $redirect_url = null): Http\Response {
155
+        if ($this->userSession->isLoggedIn()) {
156
+            return new RedirectResponse(OC_Util::getDefaultPageUrl());
157
+        }
158
+
159
+        $parameters = array();
160
+        $loginMessages = $this->session->get('loginMessages');
161
+        $errors = [];
162
+        $messages = [];
163
+        if (is_array($loginMessages)) {
164
+            list($errors, $messages) = $loginMessages;
165
+        }
166
+        $this->session->remove('loginMessages');
167
+        foreach ($errors as $value) {
168
+            $parameters[$value] = true;
169
+        }
170
+
171
+        $parameters['messages'] = $messages;
172
+        if ($user !== null && $user !== '') {
173
+            $parameters['loginName'] = $user;
174
+            $parameters['user_autofocus'] = false;
175
+        } else {
176
+            $parameters['loginName'] = '';
177
+            $parameters['user_autofocus'] = true;
178
+        }
179
+
180
+        $autocomplete = $this->config->getSystemValue('login_form_autocomplete', true);
181
+        if ($autocomplete){
182
+            $parameters['login_form_autocomplete'] = 'on';
183
+        } else {
184
+            $parameters['login_form_autocomplete'] = 'off';
185
+        }
186
+
187
+        if (!empty($redirect_url)) {
188
+            $parameters['redirect_url'] = $redirect_url;
189
+        }
190
+
191
+        $parameters = $this->setPasswordResetParameters($user, $parameters);
192
+        $parameters['alt_login'] = OC_App::getAlternativeLogIns();
193
+
194
+        if ($user !== null && $user !== '') {
195
+            $parameters['loginName'] = $user;
196
+            $parameters['user_autofocus'] = false;
197
+        } else {
198
+            $parameters['loginName'] = '';
199
+            $parameters['user_autofocus'] = true;
200
+        }
201
+
202
+        $parameters['throttle_delay'] = $this->throttler->getDelay($this->request->getRemoteAddress());
203
+
204
+        // OpenGraph Support: http://ogp.me/
205
+        Util::addHeader('meta', ['property' => 'og:title', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
206
+        Util::addHeader('meta', ['property' => 'og:description', 'content' => Util::sanitizeHTML($this->defaults->getSlogan())]);
207
+        Util::addHeader('meta', ['property' => 'og:site_name', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
208
+        Util::addHeader('meta', ['property' => 'og:url', 'content' => $this->urlGenerator->getAbsoluteURL('/')]);
209
+        Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
210
+        Util::addHeader('meta', ['property' => 'og:image', 'content' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-touch.png'))]);
211
+
212
+        return new TemplateResponse(
213
+            $this->appName, 'login', $parameters, 'guest'
214
+        );
215
+    }
216
+
217
+    /**
218
+     * Sets the password reset params.
219
+     *
220
+     * Users may not change their passwords if:
221
+     * - The account is disabled
222
+     * - The backend doesn't support password resets
223
+     * - The password reset function is disabled
224
+     *
225
+     * @param string $user
226
+     * @param array $parameters
227
+     * @return array
228
+     */
229
+    private function setPasswordResetParameters(
230
+        string $user = null, array $parameters): array {
231
+        if ($user !== null && $user !== '') {
232
+            $userObj = $this->userManager->get($user);
233
+        } else {
234
+            $userObj = null;
235
+        }
236
+
237
+        $parameters['resetPasswordLink'] = $this->config
238
+            ->getSystemValue('lost_password_link', '');
239
+
240
+        if ($parameters['resetPasswordLink'] === 'disabled') {
241
+            $parameters['canResetPassword'] = false;
242
+        } else if (!$parameters['resetPasswordLink'] && $userObj !== null) {
243
+            $parameters['canResetPassword'] = $userObj->canChangePassword();
244
+        } else if ($userObj !== null && $userObj->isEnabled() === false) {
245
+            $parameters['canResetPassword'] = false;
246
+        } else {
247
+            $parameters['canResetPassword'] = true;
248
+        }
249
+
250
+        return $parameters;
251
+    }
252
+
253
+    /**
254
+     * @param string $redirectUrl
255
+     * @return RedirectResponse
256
+     */
257
+    private function generateRedirect($redirectUrl) {
258
+        if (!is_null($redirectUrl) && $this->userSession->isLoggedIn()) {
259
+            $location = $this->urlGenerator->getAbsoluteURL(urldecode($redirectUrl));
260
+            // Deny the redirect if the URL contains a @
261
+            // This prevents unvalidated redirects like ?redirect_url=:[email protected]
262
+            if (strpos($location, '@') === false) {
263
+                return new RedirectResponse($location);
264
+            }
265
+        }
266
+        return new RedirectResponse(OC_Util::getDefaultPageUrl());
267
+    }
268
+
269
+    /**
270
+     * @PublicPage
271
+     * @UseSession
272
+     * @NoCSRFRequired
273
+     * @BruteForceProtection(action=login)
274
+     *
275
+     * @param string $user
276
+     * @param string $password
277
+     * @param string $redirect_url
278
+     * @param boolean $remember_login
279
+     * @param string $timezone
280
+     * @param string $timezone_offset
281
+     * @return RedirectResponse
282
+     */
283
+    public function tryLogin($user, $password, $redirect_url, $remember_login = true, $timezone = '', $timezone_offset = '') {
284
+        if(!is_string($user)) {
285
+            throw new \InvalidArgumentException('Username must be string');
286
+        }
287
+
288
+        // If the user is already logged in and the CSRF check does not pass then
289
+        // simply redirect the user to the correct page as required. This is the
290
+        // case when an user has already logged-in, in another tab.
291
+        if(!$this->request->passesCSRFCheck()) {
292
+            return $this->generateRedirect($redirect_url);
293
+        }
294
+
295
+        if ($this->userManager instanceof PublicEmitter) {
296
+            $this->userManager->emit('\OC\User', 'preLogin', array($user, $password));
297
+        }
298
+
299
+        $originalUser = $user;
300
+
301
+        $userObj = $this->userManager->get($user);
302
+
303
+        if ($userObj !== null && $userObj->isEnabled() === false) {
304
+            $this->logger->warning('Login failed: \''. $user . '\' disabled' .
305
+                ' (Remote IP: \''. $this->request->getRemoteAddress(). '\')',
306
+                ['app' => 'core']);
307
+            return $this->createLoginFailedResponse($user, $originalUser,
308
+                $redirect_url, self::LOGIN_MSG_USERDISABLED);
309
+        }
310
+
311
+        // TODO: Add all the insane error handling
312
+        /* @var $loginResult IUser */
313
+        $loginResult = $this->userManager->checkPasswordNoLogging($user, $password);
314
+        if ($loginResult === false) {
315
+            $users = $this->userManager->getByEmail($user);
316
+            // we only allow login by email if unique
317
+            if (count($users) === 1) {
318
+                $previousUser = $user;
319
+                $user = $users[0]->getUID();
320
+                if($user !== $previousUser) {
321
+                    $loginResult = $this->userManager->checkPassword($user, $password);
322
+                }
323
+            }
324
+        }
325
+
326
+        if ($loginResult === false) {
327
+            $this->logger->warning('Login failed: \''. $user .
328
+                '\' (Remote IP: \''. $this->request->getRemoteAddress(). '\')',
329
+                ['app' => 'core']);
330
+            return $this->createLoginFailedResponse($user, $originalUser,
331
+                $redirect_url, self::LOGIN_MSG_INVALIDPASSWORD);
332
+        }
333
+
334
+        // TODO: remove password checks from above and let the user session handle failures
335
+        // requires https://github.com/owncloud/core/pull/24616
336
+        $this->userSession->completeLogin($loginResult, ['loginName' => $user, 'password' => $password]);
337
+
338
+        $tokenType = IToken::REMEMBER;
339
+        if ((int)$this->config->getSystemValue('remember_login_cookie_lifetime', 60*60*24*15) === 0) {
340
+            $remember_login = false;
341
+            $tokenType = IToken::DO_NOT_REMEMBER;
342
+        }
343
+
344
+        $this->userSession->createSessionToken($this->request, $loginResult->getUID(), $user, $password, $tokenType);
345
+        $this->userSession->updateTokens($loginResult->getUID(), $password);
346
+
347
+        // User has successfully logged in, now remove the password reset link, when it is available
348
+        $this->config->deleteUserValue($loginResult->getUID(), 'core', 'lostpassword');
349
+
350
+        $this->session->set('last-password-confirm', $loginResult->getLastLogin());
351
+
352
+        if ($timezone_offset !== '') {
353
+            $this->config->setUserValue($loginResult->getUID(), 'core', 'timezone', $timezone);
354
+            $this->session->set('timezone', $timezone_offset);
355
+        }
356
+
357
+        if ($this->twoFactorManager->isTwoFactorAuthenticated($loginResult)) {
358
+            $this->twoFactorManager->prepareTwoFactorLogin($loginResult, $remember_login);
359
+
360
+            $providers = $this->twoFactorManager->getProviderSet($loginResult)->getPrimaryProviders();
361
+            if (count($providers) === 1) {
362
+                // Single provider, hence we can redirect to that provider's challenge page directly
363
+                /* @var $provider IProvider */
364
+                $provider = array_pop($providers);
365
+                $url = 'core.TwoFactorChallenge.showChallenge';
366
+                $urlParams = [
367
+                    'challengeProviderId' => $provider->getId(),
368
+                ];
369
+            } else {
370
+                $url = 'core.TwoFactorChallenge.selectChallenge';
371
+                $urlParams = [];
372
+            }
373
+
374
+            if (!is_null($redirect_url)) {
375
+                $urlParams['redirect_url'] = $redirect_url;
376
+            }
377
+
378
+            return new RedirectResponse($this->urlGenerator->linkToRoute($url, $urlParams));
379
+        }
380
+
381
+        if ($remember_login) {
382
+            $this->userSession->createRememberMeToken($loginResult);
383
+        }
384
+
385
+        return $this->generateRedirect($redirect_url);
386
+    }
387
+
388
+    /**
389
+     * Creates a login failed response.
390
+     *
391
+     * @param string $user
392
+     * @param string $originalUser
393
+     * @param string $redirect_url
394
+     * @param string $loginMessage
395
+     * @return RedirectResponse
396
+     */
397
+    private function createLoginFailedResponse(
398
+        $user, $originalUser, $redirect_url, string $loginMessage) {
399
+        // Read current user and append if possible we need to
400
+        // return the unmodified user otherwise we will leak the login name
401
+        $args = !is_null($user) ? ['user' => $originalUser] : [];
402
+        if (!is_null($redirect_url)) {
403
+            $args['redirect_url'] = $redirect_url;
404
+        }
405
+        $response = new RedirectResponse(
406
+            $this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)
407
+        );
408
+        $response->throttle(['user' => substr($user, 0, 64)]);
409
+        $this->session->set('loginMessages', [
410
+            [$loginMessage], []
411
+        ]);
412
+        return $response;
413
+    }
414
+
415
+    /**
416
+     * @NoAdminRequired
417
+     * @UseSession
418
+     * @BruteForceProtection(action=sudo)
419
+     *
420
+     * @license GNU AGPL version 3 or any later version
421
+     *
422
+     * @param string $password
423
+     * @return DataResponse
424
+     */
425
+    public function confirmPassword($password) {
426
+        $loginName = $this->userSession->getLoginName();
427
+        $loginResult = $this->userManager->checkPassword($loginName, $password);
428
+        if ($loginResult === false) {
429
+            $response = new DataResponse([], Http::STATUS_FORBIDDEN);
430
+            $response->throttle();
431
+            return $response;
432
+        }
433
+
434
+        $confirmTimestamp = time();
435
+        $this->session->set('last-password-confirm', $confirmTimestamp);
436
+        return new DataResponse(['lastLogin' => $confirmTimestamp], Http::STATUS_OK);
437
+    }
438 438
 }
Please login to merge, or discard this patch.