Test Failed
Push — dependabot/composer/newinterna... ( fef629 )
by
unknown
16:20 queued 10:15
created
includes/Pages/UserAuth/Login/LoginCredentialPageBase.php 2 patches
Indentation   +311 added lines, -311 removed lines patch added patch discarded remove patch
@@ -21,315 +21,315 @@
 block discarded – undo
21 21
 
22 22
 abstract class LoginCredentialPageBase extends InternalPageBase
23 23
 {
24
-    /** @var User */
25
-    protected $partialUser = null;
26
-    protected $nextPageMap = array(
27
-        'yubikeyotp' => 'otp',
28
-        'totp'       => 'otp',
29
-        'scratch'    => 'otp',
30
-        'u2f'        => 'u2f',
31
-    );
32
-    protected $names = array(
33
-        'yubikeyotp' => 'Yubikey OTP',
34
-        'totp'       => 'TOTP (phone code generator)',
35
-        'scratch'    => 'scratch token',
36
-        'u2f'        => 'U2F security token',
37
-    );
38
-
39
-    /**
40
-     * Main function for this page, when no specific actions are called.
41
-     * @return void
42
-     */
43
-    protected function main()
44
-    {
45
-        if (!$this->enforceHttps()) {
46
-            return;
47
-        }
48
-
49
-        if (WebRequest::wasPosted()) {
50
-            $this->validateCSRFToken();
51
-
52
-            $database = $this->getDatabase();
53
-            try {
54
-                list($partialId, $partialStage) = WebRequest::getAuthPartialLogin();
55
-
56
-                if ($partialStage === null) {
57
-                    $partialStage = 1;
58
-                }
59
-
60
-                if ($partialId === null) {
61
-                    $username = WebRequest::postString('username');
62
-
63
-                    if ($username === null || trim($username) === '') {
64
-                        throw new ApplicationLogicException('No username specified.');
65
-                    }
66
-
67
-                    $user = User::getByUsername($username, $database);
68
-                }
69
-                else {
70
-                    $user = User::getById($partialId, $database);
71
-                }
72
-
73
-                if ($user === false) {
74
-                    throw new ApplicationLogicException("Authentication failed");
75
-                }
76
-
77
-                $authMan = new AuthenticationManager($database, $this->getSiteConfiguration(),
78
-                    $this->getHttpHelper());
79
-
80
-                $credential = $this->getProviderCredentials();
81
-
82
-                $authResult = $authMan->authenticate($user, $credential, $partialStage);
83
-
84
-                if ($authResult === AuthenticationManager::AUTH_FAIL) {
85
-                    throw new ApplicationLogicException("Authentication failed");
86
-                }
87
-
88
-                if ($authResult === AuthenticationManager::AUTH_REQUIRE_NEXT_STAGE) {
89
-                    $this->processJumpNextStage($user, $partialStage, $database);
90
-
91
-                    return;
92
-                }
93
-
94
-                if ($authResult === AuthenticationManager::AUTH_OK) {
95
-                    $this->processLoginSuccess($user);
96
-
97
-                    return;
98
-                }
99
-            }
100
-            catch (ApplicationLogicException $ex) {
101
-                WebRequest::clearAuthPartialLogin();
102
-
103
-                SessionAlert::error($ex->getMessage());
104
-                $this->redirect('login');
105
-
106
-                return;
107
-            }
108
-        }
109
-        else {
110
-            $this->assign('showSignIn', true);
111
-
112
-            $this->setupPartial();
113
-            $this->assignCSRFToken();
114
-            $this->providerSpecificSetup();
115
-        }
116
-    }
117
-
118
-    protected function isProtectedPage()
119
-    {
120
-        return false;
121
-    }
122
-
123
-    /**
124
-     * Enforces HTTPS on the login form
125
-     *
126
-     * @return bool
127
-     */
128
-    private function enforceHttps()
129
-    {
130
-        if ($this->getSiteConfiguration()->getUseStrictTransportSecurity() !== false) {
131
-            if (WebRequest::isHttps()) {
132
-                // Client can clearly use HTTPS, so let's enforce it for all connections.
133
-                $this->headerQueue[] = "Strict-Transport-Security: max-age=15768000";
134
-            }
135
-            else {
136
-                // This is the login form, not the request form. We need protection here.
137
-                $this->redirectUrl('https://' . WebRequest::serverName() . WebRequest::requestUri());
138
-
139
-                return false;
140
-            }
141
-        }
142
-
143
-        return true;
144
-    }
145
-
146
-    protected abstract function providerSpecificSetup();
147
-
148
-    protected function setupPartial()
149
-    {
150
-        $database = $this->getDatabase();
151
-
152
-        // default stuff
153
-        $this->assign('alternatives', array()); // 'u2f' => array('U2F token'), 'otp' => array('TOTP', 'scratch', 'yubiotp')));
154
-
155
-        // is this stage one?
156
-        list($partialId, $partialStage) = WebRequest::getAuthPartialLogin();
157
-        if ($partialStage === null || $partialId === null) {
158
-            WebRequest::clearAuthPartialLogin();
159
-        }
160
-
161
-        // Check to see if we have a partial login in progress
162
-        $username = null;
163
-        if ($partialId !== null) {
164
-            // Yes, enforce this username
165
-            $this->partialUser = User::getById($partialId, $database);
166
-            $username = $this->partialUser->getUsername();
167
-
168
-            $this->setupAlternates($this->partialUser, $partialStage, $database);
169
-        }
170
-        else {
171
-            // No, see if we've preloaded a username
172
-            $preloadUsername = WebRequest::getString('tplUsername');
173
-            if ($preloadUsername !== null) {
174
-                $username = $preloadUsername;
175
-            }
176
-        }
177
-
178
-        if ($partialStage === null) {
179
-            $partialStage = 1;
180
-        }
181
-
182
-        $this->assign('partialStage', $partialStage);
183
-        $this->assign('username', $username);
184
-    }
185
-
186
-    /**
187
-     * Redirect the user back to wherever they came from after a successful login
188
-     *
189
-     * @param User $user
190
-     */
191
-    protected function goBackWhenceYouCame(User $user)
192
-    {
193
-        // Redirect to wherever the user came from
194
-        $redirectDestination = WebRequest::clearPostLoginRedirect();
195
-        if ($redirectDestination !== null) {
196
-            $this->redirectUrl($redirectDestination);
197
-        }
198
-        else {
199
-            if ($user->isNewUser()) {
200
-                // home page isn't allowed, go to preferences instead
201
-                $this->redirect('preferences');
202
-            }
203
-            else {
204
-                // go to the home page
205
-                $this->redirect('');
206
-            }
207
-        }
208
-    }
209
-
210
-    private function processLoginSuccess(User $user)
211
-    {
212
-        // Touch force logout
213
-        $user->setForceLogout(false);
214
-        $user->save();
215
-
216
-        $oauth = new OAuthUserHelper($user, $this->getDatabase(), $this->getOAuthProtocolHelper(),
217
-            $this->getSiteConfiguration());
218
-
219
-        if ($oauth->isFullyLinked()) {
220
-            try {
221
-                // Reload the user's identity ticket.
222
-                $oauth->refreshIdentity();
223
-
224
-                // Check for blocks
225
-                if ($oauth->getIdentity()->getBlocked()) {
226
-                    // blocked!
227
-                    SessionAlert::error("You are currently blocked on-wiki. You will not be able to log in until you are unblocked.");
228
-                    $this->redirect('login');
229
-
230
-                    return;
231
-                }
232
-            }
233
-            catch (OAuthException $ex) {
234
-                // Oops. Refreshing ticket failed. Force a re-auth.
235
-                $authoriseUrl = $oauth->getRequestToken();
236
-                WebRequest::setOAuthPartialLogin($user);
237
-                $this->redirectUrl($authoriseUrl);
238
-
239
-                return;
240
-            }
241
-        }
242
-
243
-        if (($this->getSiteConfiguration()->getEnforceOAuth() && !$oauth->isFullyLinked())
244
-            || $oauth->isPartiallyLinked()
245
-        ) {
246
-            $authoriseUrl = $oauth->getRequestToken();
247
-            WebRequest::setOAuthPartialLogin($user);
248
-            $this->redirectUrl($authoriseUrl);
249
-
250
-            return;
251
-        }
252
-
253
-        WebRequest::setLoggedInUser($user);
254
-
255
-        $this->goBackWhenceYouCame($user);
256
-    }
257
-
258
-    protected abstract function getProviderCredentials();
259
-
260
-    /**
261
-     * @param User        $user
262
-     * @param int         $partialStage
263
-     * @param PdoDatabase $database
264
-     *
265
-     * @throws ApplicationLogicException
266
-     */
267
-    private function processJumpNextStage(User $user, $partialStage, PdoDatabase $database)
268
-    {
269
-        WebRequest::setAuthPartialLogin($user->getId(), $partialStage + 1);
270
-
271
-        $sql = 'SELECT type FROM credential WHERE user = :user AND factor = :stage AND disabled = 0 ORDER BY priority';
272
-        $statement = $database->prepare($sql);
273
-        $statement->execute(array(':user' => $user->getId(), ':stage' => $partialStage + 1));
274
-        $nextStage = $statement->fetchColumn();
275
-        $statement->closeCursor();
276
-
277
-        if (!isset($this->nextPageMap[$nextStage])) {
278
-            throw new ApplicationLogicException('Unknown page handler for next authentication stage.');
279
-        }
280
-
281
-        $this->redirect("login/" . $this->nextPageMap[$nextStage]);
282
-    }
283
-
284
-    private function setupAlternates(User $user, $partialStage, PdoDatabase $database)
285
-    {
286
-        // get the providers available
287
-        $sql = 'SELECT type FROM credential WHERE user = :user AND factor = :stage AND disabled = 0';
288
-        $statement = $database->prepare($sql);
289
-        $statement->execute(array(':user' => $user->getId(), ':stage' => $partialStage));
290
-        $alternates = $statement->fetchAll(PDO::FETCH_COLUMN);
291
-
292
-        $types = array();
293
-        foreach ($alternates as $item) {
294
-            $type = $this->nextPageMap[$item];
295
-            if (!isset($types[$type])) {
296
-                $types[$type] = array();
297
-            }
298
-
299
-            $types[$type][] = $item;
300
-        }
301
-
302
-        $userOptions = array();
303
-        if (get_called_class() === PageOtpLogin::class) {
304
-            $userOptions = $this->setupUserOptionsForType($types, 'u2f', $userOptions);
305
-        }
306
-
307
-        if (get_called_class() === PageU2FLogin::class) {
308
-            $userOptions = $this->setupUserOptionsForType($types, 'otp', $userOptions);
309
-        }
310
-
311
-        $this->assign('alternatives', $userOptions);
312
-    }
313
-
314
-    /**
315
-     * @param $types
316
-     * @param $type
317
-     * @param $userOptions
318
-     *
319
-     * @return mixed
320
-     */
321
-    private function setupUserOptionsForType($types, $type, $userOptions)
322
-    {
323
-        if (isset($types[$type])) {
324
-            $options = $types[$type];
325
-
326
-            array_walk($options, function(&$val) {
327
-                $val = $this->names[$val];
328
-            });
329
-
330
-            $userOptions[$type] = $options;
331
-        }
332
-
333
-        return $userOptions;
334
-    }
24
+	/** @var User */
25
+	protected $partialUser = null;
26
+	protected $nextPageMap = array(
27
+		'yubikeyotp' => 'otp',
28
+		'totp'       => 'otp',
29
+		'scratch'    => 'otp',
30
+		'u2f'        => 'u2f',
31
+	);
32
+	protected $names = array(
33
+		'yubikeyotp' => 'Yubikey OTP',
34
+		'totp'       => 'TOTP (phone code generator)',
35
+		'scratch'    => 'scratch token',
36
+		'u2f'        => 'U2F security token',
37
+	);
38
+
39
+	/**
40
+	 * Main function for this page, when no specific actions are called.
41
+	 * @return void
42
+	 */
43
+	protected function main()
44
+	{
45
+		if (!$this->enforceHttps()) {
46
+			return;
47
+		}
48
+
49
+		if (WebRequest::wasPosted()) {
50
+			$this->validateCSRFToken();
51
+
52
+			$database = $this->getDatabase();
53
+			try {
54
+				list($partialId, $partialStage) = WebRequest::getAuthPartialLogin();
55
+
56
+				if ($partialStage === null) {
57
+					$partialStage = 1;
58
+				}
59
+
60
+				if ($partialId === null) {
61
+					$username = WebRequest::postString('username');
62
+
63
+					if ($username === null || trim($username) === '') {
64
+						throw new ApplicationLogicException('No username specified.');
65
+					}
66
+
67
+					$user = User::getByUsername($username, $database);
68
+				}
69
+				else {
70
+					$user = User::getById($partialId, $database);
71
+				}
72
+
73
+				if ($user === false) {
74
+					throw new ApplicationLogicException("Authentication failed");
75
+				}
76
+
77
+				$authMan = new AuthenticationManager($database, $this->getSiteConfiguration(),
78
+					$this->getHttpHelper());
79
+
80
+				$credential = $this->getProviderCredentials();
81
+
82
+				$authResult = $authMan->authenticate($user, $credential, $partialStage);
83
+
84
+				if ($authResult === AuthenticationManager::AUTH_FAIL) {
85
+					throw new ApplicationLogicException("Authentication failed");
86
+				}
87
+
88
+				if ($authResult === AuthenticationManager::AUTH_REQUIRE_NEXT_STAGE) {
89
+					$this->processJumpNextStage($user, $partialStage, $database);
90
+
91
+					return;
92
+				}
93
+
94
+				if ($authResult === AuthenticationManager::AUTH_OK) {
95
+					$this->processLoginSuccess($user);
96
+
97
+					return;
98
+				}
99
+			}
100
+			catch (ApplicationLogicException $ex) {
101
+				WebRequest::clearAuthPartialLogin();
102
+
103
+				SessionAlert::error($ex->getMessage());
104
+				$this->redirect('login');
105
+
106
+				return;
107
+			}
108
+		}
109
+		else {
110
+			$this->assign('showSignIn', true);
111
+
112
+			$this->setupPartial();
113
+			$this->assignCSRFToken();
114
+			$this->providerSpecificSetup();
115
+		}
116
+	}
117
+
118
+	protected function isProtectedPage()
119
+	{
120
+		return false;
121
+	}
122
+
123
+	/**
124
+	 * Enforces HTTPS on the login form
125
+	 *
126
+	 * @return bool
127
+	 */
128
+	private function enforceHttps()
129
+	{
130
+		if ($this->getSiteConfiguration()->getUseStrictTransportSecurity() !== false) {
131
+			if (WebRequest::isHttps()) {
132
+				// Client can clearly use HTTPS, so let's enforce it for all connections.
133
+				$this->headerQueue[] = "Strict-Transport-Security: max-age=15768000";
134
+			}
135
+			else {
136
+				// This is the login form, not the request form. We need protection here.
137
+				$this->redirectUrl('https://' . WebRequest::serverName() . WebRequest::requestUri());
138
+
139
+				return false;
140
+			}
141
+		}
142
+
143
+		return true;
144
+	}
145
+
146
+	protected abstract function providerSpecificSetup();
147
+
148
+	protected function setupPartial()
149
+	{
150
+		$database = $this->getDatabase();
151
+
152
+		// default stuff
153
+		$this->assign('alternatives', array()); // 'u2f' => array('U2F token'), 'otp' => array('TOTP', 'scratch', 'yubiotp')));
154
+
155
+		// is this stage one?
156
+		list($partialId, $partialStage) = WebRequest::getAuthPartialLogin();
157
+		if ($partialStage === null || $partialId === null) {
158
+			WebRequest::clearAuthPartialLogin();
159
+		}
160
+
161
+		// Check to see if we have a partial login in progress
162
+		$username = null;
163
+		if ($partialId !== null) {
164
+			// Yes, enforce this username
165
+			$this->partialUser = User::getById($partialId, $database);
166
+			$username = $this->partialUser->getUsername();
167
+
168
+			$this->setupAlternates($this->partialUser, $partialStage, $database);
169
+		}
170
+		else {
171
+			// No, see if we've preloaded a username
172
+			$preloadUsername = WebRequest::getString('tplUsername');
173
+			if ($preloadUsername !== null) {
174
+				$username = $preloadUsername;
175
+			}
176
+		}
177
+
178
+		if ($partialStage === null) {
179
+			$partialStage = 1;
180
+		}
181
+
182
+		$this->assign('partialStage', $partialStage);
183
+		$this->assign('username', $username);
184
+	}
185
+
186
+	/**
187
+	 * Redirect the user back to wherever they came from after a successful login
188
+	 *
189
+	 * @param User $user
190
+	 */
191
+	protected function goBackWhenceYouCame(User $user)
192
+	{
193
+		// Redirect to wherever the user came from
194
+		$redirectDestination = WebRequest::clearPostLoginRedirect();
195
+		if ($redirectDestination !== null) {
196
+			$this->redirectUrl($redirectDestination);
197
+		}
198
+		else {
199
+			if ($user->isNewUser()) {
200
+				// home page isn't allowed, go to preferences instead
201
+				$this->redirect('preferences');
202
+			}
203
+			else {
204
+				// go to the home page
205
+				$this->redirect('');
206
+			}
207
+		}
208
+	}
209
+
210
+	private function processLoginSuccess(User $user)
211
+	{
212
+		// Touch force logout
213
+		$user->setForceLogout(false);
214
+		$user->save();
215
+
216
+		$oauth = new OAuthUserHelper($user, $this->getDatabase(), $this->getOAuthProtocolHelper(),
217
+			$this->getSiteConfiguration());
218
+
219
+		if ($oauth->isFullyLinked()) {
220
+			try {
221
+				// Reload the user's identity ticket.
222
+				$oauth->refreshIdentity();
223
+
224
+				// Check for blocks
225
+				if ($oauth->getIdentity()->getBlocked()) {
226
+					// blocked!
227
+					SessionAlert::error("You are currently blocked on-wiki. You will not be able to log in until you are unblocked.");
228
+					$this->redirect('login');
229
+
230
+					return;
231
+				}
232
+			}
233
+			catch (OAuthException $ex) {
234
+				// Oops. Refreshing ticket failed. Force a re-auth.
235
+				$authoriseUrl = $oauth->getRequestToken();
236
+				WebRequest::setOAuthPartialLogin($user);
237
+				$this->redirectUrl($authoriseUrl);
238
+
239
+				return;
240
+			}
241
+		}
242
+
243
+		if (($this->getSiteConfiguration()->getEnforceOAuth() && !$oauth->isFullyLinked())
244
+			|| $oauth->isPartiallyLinked()
245
+		) {
246
+			$authoriseUrl = $oauth->getRequestToken();
247
+			WebRequest::setOAuthPartialLogin($user);
248
+			$this->redirectUrl($authoriseUrl);
249
+
250
+			return;
251
+		}
252
+
253
+		WebRequest::setLoggedInUser($user);
254
+
255
+		$this->goBackWhenceYouCame($user);
256
+	}
257
+
258
+	protected abstract function getProviderCredentials();
259
+
260
+	/**
261
+	 * @param User        $user
262
+	 * @param int         $partialStage
263
+	 * @param PdoDatabase $database
264
+	 *
265
+	 * @throws ApplicationLogicException
266
+	 */
267
+	private function processJumpNextStage(User $user, $partialStage, PdoDatabase $database)
268
+	{
269
+		WebRequest::setAuthPartialLogin($user->getId(), $partialStage + 1);
270
+
271
+		$sql = 'SELECT type FROM credential WHERE user = :user AND factor = :stage AND disabled = 0 ORDER BY priority';
272
+		$statement = $database->prepare($sql);
273
+		$statement->execute(array(':user' => $user->getId(), ':stage' => $partialStage + 1));
274
+		$nextStage = $statement->fetchColumn();
275
+		$statement->closeCursor();
276
+
277
+		if (!isset($this->nextPageMap[$nextStage])) {
278
+			throw new ApplicationLogicException('Unknown page handler for next authentication stage.');
279
+		}
280
+
281
+		$this->redirect("login/" . $this->nextPageMap[$nextStage]);
282
+	}
283
+
284
+	private function setupAlternates(User $user, $partialStage, PdoDatabase $database)
285
+	{
286
+		// get the providers available
287
+		$sql = 'SELECT type FROM credential WHERE user = :user AND factor = :stage AND disabled = 0';
288
+		$statement = $database->prepare($sql);
289
+		$statement->execute(array(':user' => $user->getId(), ':stage' => $partialStage));
290
+		$alternates = $statement->fetchAll(PDO::FETCH_COLUMN);
291
+
292
+		$types = array();
293
+		foreach ($alternates as $item) {
294
+			$type = $this->nextPageMap[$item];
295
+			if (!isset($types[$type])) {
296
+				$types[$type] = array();
297
+			}
298
+
299
+			$types[$type][] = $item;
300
+		}
301
+
302
+		$userOptions = array();
303
+		if (get_called_class() === PageOtpLogin::class) {
304
+			$userOptions = $this->setupUserOptionsForType($types, 'u2f', $userOptions);
305
+		}
306
+
307
+		if (get_called_class() === PageU2FLogin::class) {
308
+			$userOptions = $this->setupUserOptionsForType($types, 'otp', $userOptions);
309
+		}
310
+
311
+		$this->assign('alternatives', $userOptions);
312
+	}
313
+
314
+	/**
315
+	 * @param $types
316
+	 * @param $type
317
+	 * @param $userOptions
318
+	 *
319
+	 * @return mixed
320
+	 */
321
+	private function setupUserOptionsForType($types, $type, $userOptions)
322
+	{
323
+		if (isset($types[$type])) {
324
+			$options = $types[$type];
325
+
326
+			array_walk($options, function(&$val) {
327
+				$val = $this->names[$val];
328
+			});
329
+
330
+			$userOptions[$type] = $options;
331
+		}
332
+
333
+		return $userOptions;
334
+	}
335 335
 }
Please login to merge, or discard this patch.
Braces   +8 added lines, -13 removed lines patch added patch discarded remove patch
@@ -65,8 +65,7 @@  discard block
 block discarded – undo
65 65
                     }
66 66
 
67 67
                     $user = User::getByUsername($username, $database);
68
-                }
69
-                else {
68
+                } else {
70 69
                     $user = User::getById($partialId, $database);
71 70
                 }
72 71
 
@@ -105,8 +104,7 @@  discard block
 block discarded – undo
105 104
 
106 105
                 return;
107 106
             }
108
-        }
109
-        else {
107
+        } else {
110 108
             $this->assign('showSignIn', true);
111 109
 
112 110
             $this->setupPartial();
@@ -131,8 +129,7 @@  discard block
 block discarded – undo
131 129
             if (WebRequest::isHttps()) {
132 130
                 // Client can clearly use HTTPS, so let's enforce it for all connections.
133 131
                 $this->headerQueue[] = "Strict-Transport-Security: max-age=15768000";
134
-            }
135
-            else {
132
+            } else {
136 133
                 // This is the login form, not the request form. We need protection here.
137 134
                 $this->redirectUrl('https://' . WebRequest::serverName() . WebRequest::requestUri());
138 135
 
@@ -166,8 +163,7 @@  discard block
 block discarded – undo
166 163
             $username = $this->partialUser->getUsername();
167 164
 
168 165
             $this->setupAlternates($this->partialUser, $partialStage, $database);
169
-        }
170
-        else {
166
+        } else {
171 167
             // No, see if we've preloaded a username
172 168
             $preloadUsername = WebRequest::getString('tplUsername');
173 169
             if ($preloadUsername !== null) {
@@ -194,13 +190,11 @@  discard block
 block discarded – undo
194 190
         $redirectDestination = WebRequest::clearPostLoginRedirect();
195 191
         if ($redirectDestination !== null) {
196 192
             $this->redirectUrl($redirectDestination);
197
-        }
198
-        else {
193
+        } else {
199 194
             if ($user->isNewUser()) {
200 195
                 // home page isn't allowed, go to preferences instead
201 196
                 $this->redirect('preferences');
202
-            }
203
-            else {
197
+            } else {
204 198
                 // go to the home page
205 199
                 $this->redirect('');
206 200
             }
@@ -323,7 +317,8 @@  discard block
 block discarded – undo
323 317
         if (isset($types[$type])) {
324 318
             $options = $types[$type];
325 319
 
326
-            array_walk($options, function(&$val) {
320
+            array_walk($options, function(&$val)
321
+            {
327 322
                 $val = $this->names[$val];
328 323
             });
329 324
 
Please login to merge, or discard this patch.
includes/Pages/UserAuth/Login/PageOtpLogin.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -13,18 +13,18 @@
 block discarded – undo
13 13
 
14 14
 class PageOtpLogin extends LoginCredentialPageBase
15 15
 {
16
-    protected function providerSpecificSetup()
17
-    {
18
-        $this->setTemplate('login/otp.tpl');
19
-    }
16
+	protected function providerSpecificSetup()
17
+	{
18
+		$this->setTemplate('login/otp.tpl');
19
+	}
20 20
 
21
-    protected function getProviderCredentials()
22
-    {
23
-        $otp = WebRequest::postString("otp");
24
-        if ($otp === null || $otp === "") {
25
-            throw new ApplicationLogicException("No one-time code specified");
26
-        }
21
+	protected function getProviderCredentials()
22
+	{
23
+		$otp = WebRequest::postString("otp");
24
+		if ($otp === null || $otp === "") {
25
+			throw new ApplicationLogicException("No one-time code specified");
26
+		}
27 27
 
28
-        return $otp;
29
-    }
28
+		return $otp;
29
+	}
30 30
 }
31 31
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Pages/UserAuth/Login/PageU2FLogin.php 1 patch
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -14,20 +14,20 @@  discard block
 block discarded – undo
14 14
 
15 15
 class PageU2FLogin extends LoginCredentialPageBase
16 16
 {
17
-    protected function providerSpecificSetup()
18
-    {
19
-        $this->assign('showSignIn', false);
20
-        $this->setTemplate('login/u2f.tpl');
17
+	protected function providerSpecificSetup()
18
+	{
19
+		$this->assign('showSignIn', false);
20
+		$this->setTemplate('login/u2f.tpl');
21 21
 
22
-        if ($this->partialUser === null) {
23
-            throw new ApplicationLogicException("U2F cannot be first-stage authentication");
24
-        }
22
+		if ($this->partialUser === null) {
23
+			throw new ApplicationLogicException("U2F cannot be first-stage authentication");
24
+		}
25 25
 
26
-        $u2f = new U2FCredentialProvider($this->getDatabase(), $this->getSiteConfiguration());
27
-        $authData = json_encode($u2f->getAuthenticationData($this->partialUser));
26
+		$u2f = new U2FCredentialProvider($this->getDatabase(), $this->getSiteConfiguration());
27
+		$authData = json_encode($u2f->getAuthenticationData($this->partialUser));
28 28
 
29
-        $this->addJs('/vendor/yubico/u2flib-server/examples/assets/u2f-api.js');
30
-        $this->setTailScript($this->getCspManager()->getNonce(), <<<JS
29
+		$this->addJs('/vendor/yubico/u2flib-server/examples/assets/u2f-api.js');
30
+		$this->setTailScript($this->getCspManager()->getNonce(), <<<JS
31 31
 var request = {$authData};
32 32
 u2f.sign(request, function(data) {
33 33
     document.getElementById('authenticate').value=JSON.stringify(data);
@@ -35,19 +35,19 @@  discard block
 block discarded – undo
35 35
     document.getElementById('loginForm').submit();
36 36
 });
37 37
 JS
38
-        );
38
+		);
39 39
 
40
-    }
40
+	}
41 41
 
42
-    protected function getProviderCredentials()
43
-    {
44
-        $authenticate = WebRequest::postString("authenticate");
45
-        $request = WebRequest::postString("request");
42
+	protected function getProviderCredentials()
43
+	{
44
+		$authenticate = WebRequest::postString("authenticate");
45
+		$request = WebRequest::postString("request");
46 46
 
47
-        if ($authenticate === null || $authenticate === "" || $request === null || $request === "") {
48
-              throw new ApplicationLogicException("No authentication specified");
49
-        }
47
+		if ($authenticate === null || $authenticate === "" || $request === null || $request === "") {
48
+			  throw new ApplicationLogicException("No authentication specified");
49
+		}
50 50
 
51
-        return array(json_decode($authenticate), json_decode($request), 'u2f');
52
-    }
51
+		return array(json_decode($authenticate), json_decode($request), 'u2f');
52
+	}
53 53
 }
Please login to merge, or discard this patch.
includes/Pages/UserAuth/PageOAuthCallback.php 2 patches
Indentation   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -18,92 +18,92 @@
 block discarded – undo
18 18
 
19 19
 class PageOAuthCallback extends InternalPageBase
20 20
 {
21
-    /**
22
-     * @return bool
23
-     */
24
-    protected function isProtectedPage()
25
-    {
26
-        // This page is critical to ensuring OAuth functionality is operational.
27
-        return false;
28
-    }
21
+	/**
22
+	 * @return bool
23
+	 */
24
+	protected function isProtectedPage()
25
+	{
26
+		// This page is critical to ensuring OAuth functionality is operational.
27
+		return false;
28
+	}
29 29
 
30
-    /**
31
-     * Main function for this page, when no specific actions are called.
32
-     * @return void
33
-     */
34
-    protected function main()
35
-    {
36
-        // This should never get hit except by URL manipulation.
37
-        $this->redirect('');
38
-    }
30
+	/**
31
+	 * Main function for this page, when no specific actions are called.
32
+	 * @return void
33
+	 */
34
+	protected function main()
35
+	{
36
+		// This should never get hit except by URL manipulation.
37
+		$this->redirect('');
38
+	}
39 39
 
40
-    /**
41
-     * Registered endpoint for the account creation callback.
42
-     *
43
-     * If this ever gets hit, something is wrong somewhere.
44
-     */
45
-    protected function create()
46
-    {
47
-        throw new Exception('OAuth account creation endpoint triggered.');
48
-    }
40
+	/**
41
+	 * Registered endpoint for the account creation callback.
42
+	 *
43
+	 * If this ever gets hit, something is wrong somewhere.
44
+	 */
45
+	protected function create()
46
+	{
47
+		throw new Exception('OAuth account creation endpoint triggered.');
48
+	}
49 49
 
50
-    /**
51
-     * Callback entry point
52
-     * @throws ApplicationLogicException
53
-     * @throws OptimisticLockFailedException
54
-     */
55
-    protected function authorise()
56
-    {
57
-        $oauthToken = WebRequest::getString('oauth_token');
58
-        $oauthVerifier = WebRequest::getString('oauth_verifier');
50
+	/**
51
+	 * Callback entry point
52
+	 * @throws ApplicationLogicException
53
+	 * @throws OptimisticLockFailedException
54
+	 */
55
+	protected function authorise()
56
+	{
57
+		$oauthToken = WebRequest::getString('oauth_token');
58
+		$oauthVerifier = WebRequest::getString('oauth_verifier');
59 59
 
60
-        $this->doCallbackValidation($oauthToken, $oauthVerifier);
60
+		$this->doCallbackValidation($oauthToken, $oauthVerifier);
61 61
 
62
-        $database = $this->getDatabase();
62
+		$database = $this->getDatabase();
63 63
 
64
-        $user = OAuthUserHelper::findUserByRequestToken($oauthToken, $database);
65
-        $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
64
+		$user = OAuthUserHelper::findUserByRequestToken($oauthToken, $database);
65
+		$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
66 66
 
67
-        try {
68
-            $oauth->completeHandshake($oauthVerifier);
69
-        }
70
-        catch (CurlException $ex) {
71
-            throw new ApplicationLogicException($ex->getMessage(), 0, $ex);
72
-        }
67
+		try {
68
+			$oauth->completeHandshake($oauthVerifier);
69
+		}
70
+		catch (CurlException $ex) {
71
+			throw new ApplicationLogicException($ex->getMessage(), 0, $ex);
72
+		}
73 73
 
74
-        // OK, we're the same session that just did a partial login that was redirected to OAuth. Let's upgrade the
75
-        // login to a full login
76
-        if (WebRequest::getOAuthPartialLogin() === $user->getId()) {
77
-            WebRequest::setLoggedInUser($user);
78
-        }
74
+		// OK, we're the same session that just did a partial login that was redirected to OAuth. Let's upgrade the
75
+		// login to a full login
76
+		if (WebRequest::getOAuthPartialLogin() === $user->getId()) {
77
+			WebRequest::setLoggedInUser($user);
78
+		}
79 79
 
80
-        // My thinking is there are three cases here:
81
-        //   a) new user => redirect to prefs - it's the only thing they can access other than stats
82
-        //   b) existing user hit the connect button in prefs => redirect to prefs since it's where they were
83
-        //   c) existing user logging in => redirect to wherever they came from
84
-        $redirectDestination = WebRequest::clearPostLoginRedirect();
85
-        if ($redirectDestination !== null && !$user->isNewUser()) {
86
-            $this->redirectUrl($redirectDestination);
87
-        }
88
-        else {
89
-            $this->redirect('preferences', null, null, 'internal.php');
90
-        }
91
-    }
80
+		// My thinking is there are three cases here:
81
+		//   a) new user => redirect to prefs - it's the only thing they can access other than stats
82
+		//   b) existing user hit the connect button in prefs => redirect to prefs since it's where they were
83
+		//   c) existing user logging in => redirect to wherever they came from
84
+		$redirectDestination = WebRequest::clearPostLoginRedirect();
85
+		if ($redirectDestination !== null && !$user->isNewUser()) {
86
+			$this->redirectUrl($redirectDestination);
87
+		}
88
+		else {
89
+			$this->redirect('preferences', null, null, 'internal.php');
90
+		}
91
+	}
92 92
 
93
-    /**
94
-     * @param string $oauthToken
95
-     * @param string $oauthVerifier
96
-     *
97
-     * @throws ApplicationLogicException
98
-     */
99
-    private function doCallbackValidation($oauthToken, $oauthVerifier)
100
-    {
101
-        if ($oauthToken === null) {
102
-            throw new ApplicationLogicException('No token provided');
103
-        }
93
+	/**
94
+	 * @param string $oauthToken
95
+	 * @param string $oauthVerifier
96
+	 *
97
+	 * @throws ApplicationLogicException
98
+	 */
99
+	private function doCallbackValidation($oauthToken, $oauthVerifier)
100
+	{
101
+		if ($oauthToken === null) {
102
+			throw new ApplicationLogicException('No token provided');
103
+		}
104 104
 
105
-        if ($oauthVerifier === null) {
106
-            throw new ApplicationLogicException('No oauth verifier provided.');
107
-        }
108
-    }
105
+		if ($oauthVerifier === null) {
106
+			throw new ApplicationLogicException('No oauth verifier provided.');
107
+		}
108
+	}
109 109
 }
110 110
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -116,8 +116,7 @@
 block discarded – undo
116 116
         $redirectDestination = WebRequest::clearPostLoginRedirect();
117 117
         if ($redirectDestination !== null && !$user->isNewUser()) {
118 118
             $this->redirectUrl($redirectDestination);
119
-        }
120
-        else {
119
+        } else {
121 120
             $this->redirect('preferences', null, null, 'internal.php');
122 121
         }
123 122
     }
Please login to merge, or discard this patch.
includes/Pages/UserAuth/PageChangePassword.php 2 patches
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -17,71 +17,71 @@
 block discarded – undo
17 17
 
18 18
 class PageChangePassword extends InternalPageBase
19 19
 {
20
-    /**
21
-     * Main function for this page, when no specific actions are called.
22
-     * @return void
23
-     */
24
-    protected function main()
25
-    {
26
-        $this->setHtmlTitle('Change Password');
20
+	/**
21
+	 * Main function for this page, when no specific actions are called.
22
+	 * @return void
23
+	 */
24
+	protected function main()
25
+	{
26
+		$this->setHtmlTitle('Change Password');
27 27
 
28
-        if (WebRequest::wasPosted()) {
29
-            $this->validateCSRFToken();
30
-            try {
31
-                $oldPassword = WebRequest::postString('oldpassword');
32
-                $newPassword = WebRequest::postString('newpassword');
33
-                $newPasswordConfirmation = WebRequest::postString('newpasswordconfirm');
28
+		if (WebRequest::wasPosted()) {
29
+			$this->validateCSRFToken();
30
+			try {
31
+				$oldPassword = WebRequest::postString('oldpassword');
32
+				$newPassword = WebRequest::postString('newpassword');
33
+				$newPasswordConfirmation = WebRequest::postString('newpasswordconfirm');
34 34
 
35
-                $user = User::getCurrent($this->getDatabase());
36
-                if (!$user instanceof User) {
37
-                    throw new ApplicationLogicException('User not found');
38
-                }
35
+				$user = User::getCurrent($this->getDatabase());
36
+				if (!$user instanceof User) {
37
+					throw new ApplicationLogicException('User not found');
38
+				}
39 39
 
40
-                $this->validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, $user);
40
+				$this->validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, $user);
41 41
 
42
-                $passwordProvider = new PasswordCredentialProvider($this->getDatabase(), $this->getSiteConfiguration());
43
-                $passwordProvider->setCredential($user, 1, $newPassword);
44
-            }
45
-            catch (ApplicationLogicException $ex) {
46
-                SessionAlert::error($ex->getMessage());
47
-                $this->redirect('changePassword');
42
+				$passwordProvider = new PasswordCredentialProvider($this->getDatabase(), $this->getSiteConfiguration());
43
+				$passwordProvider->setCredential($user, 1, $newPassword);
44
+			}
45
+			catch (ApplicationLogicException $ex) {
46
+				SessionAlert::error($ex->getMessage());
47
+				$this->redirect('changePassword');
48 48
 
49
-                return;
50
-            }
49
+				return;
50
+			}
51 51
 
52
-            SessionAlert::success('Password changed successfully!');
52
+			SessionAlert::success('Password changed successfully!');
53 53
 
54
-            $this->redirect('preferences');
55
-        }
56
-        else {
57
-            $this->assignCSRFToken();
58
-            $this->setTemplate('preferences/changePassword.tpl');
59
-            $this->addJs("/vendor/dropbox/zxcvbn/dist/zxcvbn.js");
60
-        }
61
-    }
54
+			$this->redirect('preferences');
55
+		}
56
+		else {
57
+			$this->assignCSRFToken();
58
+			$this->setTemplate('preferences/changePassword.tpl');
59
+			$this->addJs("/vendor/dropbox/zxcvbn/dist/zxcvbn.js");
60
+		}
61
+	}
62 62
 
63
-    /**
64
-     * @param string $oldPassword
65
-     * @param string $newPassword
66
-     * @param string $newPasswordConfirmation
67
-     * @param User   $user
68
-     *
69
-     * @throws ApplicationLogicException
70
-     */
71
-    protected function validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, User $user)
72
-    {
73
-        if ($oldPassword === null || $newPassword === null || $newPasswordConfirmation === null) {
74
-            throw new ApplicationLogicException('All three fields must be completed to change your password');
75
-        }
63
+	/**
64
+	 * @param string $oldPassword
65
+	 * @param string $newPassword
66
+	 * @param string $newPasswordConfirmation
67
+	 * @param User   $user
68
+	 *
69
+	 * @throws ApplicationLogicException
70
+	 */
71
+	protected function validateNewPassword($oldPassword, $newPassword, $newPasswordConfirmation, User $user)
72
+	{
73
+		if ($oldPassword === null || $newPassword === null || $newPasswordConfirmation === null) {
74
+			throw new ApplicationLogicException('All three fields must be completed to change your password');
75
+		}
76 76
 
77
-        if ($newPassword !== $newPasswordConfirmation) {
78
-            throw new ApplicationLogicException('Your new passwords did not match!');
79
-        }
77
+		if ($newPassword !== $newPasswordConfirmation) {
78
+			throw new ApplicationLogicException('Your new passwords did not match!');
79
+		}
80 80
 
81
-        // TODO: adapt for MFA support
82
-        $passwordProvider = new PasswordCredentialProvider($this->getDatabase(), $this->getSiteConfiguration());
83
-        if (!$passwordProvider->authenticate($user, $oldPassword)) {
84
-            throw new ApplicationLogicException('The password you entered was incorrect.');
85
-        }
86
-    }
81
+		// TODO: adapt for MFA support
82
+		$passwordProvider = new PasswordCredentialProvider($this->getDatabase(), $this->getSiteConfiguration());
83
+		if (!$passwordProvider->authenticate($user, $oldPassword)) {
84
+			throw new ApplicationLogicException('The password you entered was incorrect.');
85
+		}
86
+	}
87 87
 }
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -52,8 +52,7 @@
 block discarded – undo
52 52
             SessionAlert::success('Password changed successfully!');
53 53
 
54 54
             $this->redirect('preferences');
55
-        }
56
-        else {
55
+        } else {
57 56
             $this->assignCSRFToken();
58 57
             $this->setTemplate('preferences/changePassword.tpl');
59 58
             $this->addJs("/vendor/dropbox/zxcvbn/dist/zxcvbn.js");
Please login to merge, or discard this patch.
includes/Pages/UserAuth/PageForgotPassword.php 3 patches
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -22,209 +22,209 @@
 block discarded – undo
22 22
 
23 23
 class PageForgotPassword extends InternalPageBase
24 24
 {
25
-    /**
26
-     * Main function for this page, when no specific actions are called.
27
-     *
28
-     * This is the forgotten password reset form
29
-     * @category Security-Critical
30
-     */
31
-    protected function main()
32
-    {
33
-        if (WebRequest::wasPosted()) {
34
-            $this->validateCSRFToken();
35
-            $username = WebRequest::postString('username');
36
-            $email = WebRequest::postEmail('email');
37
-            $database = $this->getDatabase();
38
-
39
-            if ($username === null || trim($username) === "" || $email === null || trim($email) === "") {
40
-                throw new ApplicationLogicException("Both username and email address must be specified!");
41
-            }
42
-
43
-            $user = User::getByUsername($username, $database);
44
-            $this->sendResetMail($user, $email);
45
-
46
-            SessionAlert::success('<strong>Your password reset request has been completed.</strong> If the details you have provided match our records, you should receive an email shortly.');
47
-
48
-            $this->redirect('login');
49
-        }
50
-        else {
51
-            $this->assignCSRFToken();
52
-            $this->setTemplate('forgot-password/forgotpw.tpl');
53
-        }
54
-    }
55
-
56
-    /**
57
-     * Sends a reset email if the user is authenticated
58
-     *
59
-     * @param User|boolean $user  The user located from the database, or false. Doesn't really matter, since we do the
60
-     *                            check anyway within this method and silently skip if we don't have a user.
61
-     * @param string       $email The provided email address
62
-     */
63
-    private function sendResetMail($user, $email)
64
-    {
65
-        // If the user isn't found, or the email address is wrong, skip sending the details silently.
66
-        if (!$user instanceof User) {
67
-            return;
68
-        }
69
-
70
-        if (strtolower($user->getEmail()) === strtolower($email)) {
71
-            $clientIp = $this->getXffTrustProvider()
72
-                ->getTrustedClientIp(WebRequest::remoteAddress(), WebRequest::forwardedAddress());
73
-
74
-            $this->cleanExistingTokens($user);
75
-
76
-            $hash = Base32::encodeUpper(openssl_random_pseudo_bytes(30));
77
-
78
-            $encryptionHelper = new EncryptionHelper($this->getSiteConfiguration());
79
-
80
-            $cred = new Credential();
81
-            $cred->setDatabase($this->getDatabase());
82
-            $cred->setFactor(-1);
83
-            $cred->setUserId($user->getId());
84
-            $cred->setType('reset');
85
-            $cred->setData($encryptionHelper->encryptData($hash));
86
-            $cred->setVersion(0);
87
-            $cred->setDisabled(0);
88
-            $cred->setTimeout(new DateTimeImmutable('+ 1 hour'));
89
-            $cred->setPriority(9);
90
-            $cred->save();
91
-
92
-            $this->assign("user", $user);
93
-            $this->assign("hash", $hash);
94
-            $this->assign("remoteAddress", $clientIp);
95
-
96
-            $emailContent = $this->fetchTemplate('forgot-password/reset-mail.tpl');
97
-
98
-            $this->getEmailHelper()->sendMail($user->getEmail(), "WP:ACC password reset", $emailContent);
99
-        }
100
-    }
101
-
102
-    /**
103
-     * Entry point for the reset action
104
-     *
105
-     * This is the reset password part of the form.
106
-     * @category Security-Critical
107
-     */
108
-    protected function reset()
109
-    {
110
-        $si = WebRequest::getString('si');
111
-        $id = WebRequest::getString('id');
112
-
113
-        if ($si === null || trim($si) === "" || $id === null || trim($id) === "") {
114
-            throw new ApplicationLogicException("Link not valid, please ensure it has copied correctly");
115
-        }
116
-
117
-        $database = $this->getDatabase();
118
-        $user = $this->getResettingUser($id, $database, $si);
119
-
120
-        // Dual mode
121
-        if (WebRequest::wasPosted()) {
122
-            $this->validateCSRFToken();
123
-            try {
124
-                $this->doReset($user);
125
-                $this->cleanExistingTokens($user);
126
-            }
127
-            catch (ApplicationLogicException $ex) {
128
-                SessionAlert::error($ex->getMessage());
129
-                $this->redirect('forgotPassword', 'reset', array('si' => $si, 'id' => $id));
130
-
131
-                return;
132
-            }
133
-        }
134
-        else {
135
-            $this->assignCSRFToken();
136
-            $this->assign('user', $user);
137
-            $this->setTemplate('forgot-password/forgotpwreset.tpl');
138
-            $this->addJs("/vendor/dropbox/zxcvbn/dist/zxcvbn.js");
139
-        }
140
-    }
141
-
142
-    /**
143
-     * Gets the user resetting their password from the database, or throwing an exception if that is not possible.
144
-     *
145
-     * @param integer     $id       The ID of the user to retrieve
146
-     * @param PdoDatabase $database The database object to use
147
-     * @param string      $si       The reset hash provided
148
-     *
149
-     * @return User
150
-     * @throws ApplicationLogicException
151
-     */
152
-    private function getResettingUser($id, $database, $si)
153
-    {
154
-        $user = User::getById($id, $database);
155
-
156
-        if ($user === false ||  $user->isCommunityUser()) {
157
-            throw new ApplicationLogicException("Password reset failed. Please try again.");
158
-        }
159
-
160
-        $statement = $database->prepare("SELECT * FROM credential WHERE type = 'reset' AND user = :user;");
161
-        $statement->execute([':user' => $user->getId()]);
162
-
163
-        /** @var Credential $credential */
164
-        $credential = $statement->fetchObject(Credential::class);
165
-
166
-        $statement->closeCursor();
167
-
168
-        if ($credential === false) {
169
-            throw new ApplicationLogicException("Password reset failed. Please try again.");
170
-        }
171
-
172
-        $credential->setDatabase($database);
173
-
174
-        $encryptionHelper = new EncryptionHelper($this->getSiteConfiguration());
175
-        if ($encryptionHelper->decryptData($credential->getData()) != $si) {
176
-            throw new ApplicationLogicException("Password reset failed. Please try again.");
177
-        }
178
-
179
-        if ($credential->getTimeout() < new DateTimeImmutable()) {
180
-            $credential->delete();
181
-            throw new ApplicationLogicException("Password reset token expired. Please try again.");
182
-        }
183
-
184
-        return $user;
185
-    }
186
-
187
-    /**
188
-     * Performs the setting of the new password
189
-     *
190
-     * @param User $user The user to set the password for
191
-     *
192
-     * @throws ApplicationLogicException
193
-     */
194
-    private function doReset(User $user)
195
-    {
196
-        $pw = WebRequest::postString('pw');
197
-        $pw2 = WebRequest::postString('pw2');
198
-
199
-        if ($pw !== $pw2) {
200
-            throw new ApplicationLogicException('Passwords do not match!');
201
-        }
202
-
203
-        $passwordCredentialProvider = new PasswordCredentialProvider($user->getDatabase(), $this->getSiteConfiguration());
204
-        $passwordCredentialProvider->setCredential($user, 1, $pw);
205
-
206
-        SessionAlert::success('You may now log in!');
207
-        $this->redirect('login');
208
-    }
209
-
210
-    protected function isProtectedPage()
211
-    {
212
-        return false;
213
-    }
214
-
215
-    /**
216
-     * @param $user
217
-     */
218
-    private function cleanExistingTokens($user): void
219
-    {
220
-        // clean out existing reset tokens
221
-        $statement = $this->getDatabase()->prepare("SELECT * FROM credential WHERE type = 'reset' AND user = :user;");
222
-        $statement->execute([':user' => $user->getId()]);
223
-        $existing = $statement->fetchAll(PdoDatabase::FETCH_CLASS, Credential::class);
224
-
225
-        foreach ($existing as $c) {
226
-            $c->setDatabase($this->getDatabase());
227
-            $c->delete();
228
-        }
229
-    }
25
+	/**
26
+	 * Main function for this page, when no specific actions are called.
27
+	 *
28
+	 * This is the forgotten password reset form
29
+	 * @category Security-Critical
30
+	 */
31
+	protected function main()
32
+	{
33
+		if (WebRequest::wasPosted()) {
34
+			$this->validateCSRFToken();
35
+			$username = WebRequest::postString('username');
36
+			$email = WebRequest::postEmail('email');
37
+			$database = $this->getDatabase();
38
+
39
+			if ($username === null || trim($username) === "" || $email === null || trim($email) === "") {
40
+				throw new ApplicationLogicException("Both username and email address must be specified!");
41
+			}
42
+
43
+			$user = User::getByUsername($username, $database);
44
+			$this->sendResetMail($user, $email);
45
+
46
+			SessionAlert::success('<strong>Your password reset request has been completed.</strong> If the details you have provided match our records, you should receive an email shortly.');
47
+
48
+			$this->redirect('login');
49
+		}
50
+		else {
51
+			$this->assignCSRFToken();
52
+			$this->setTemplate('forgot-password/forgotpw.tpl');
53
+		}
54
+	}
55
+
56
+	/**
57
+	 * Sends a reset email if the user is authenticated
58
+	 *
59
+	 * @param User|boolean $user  The user located from the database, or false. Doesn't really matter, since we do the
60
+	 *                            check anyway within this method and silently skip if we don't have a user.
61
+	 * @param string       $email The provided email address
62
+	 */
63
+	private function sendResetMail($user, $email)
64
+	{
65
+		// If the user isn't found, or the email address is wrong, skip sending the details silently.
66
+		if (!$user instanceof User) {
67
+			return;
68
+		}
69
+
70
+		if (strtolower($user->getEmail()) === strtolower($email)) {
71
+			$clientIp = $this->getXffTrustProvider()
72
+				->getTrustedClientIp(WebRequest::remoteAddress(), WebRequest::forwardedAddress());
73
+
74
+			$this->cleanExistingTokens($user);
75
+
76
+			$hash = Base32::encodeUpper(openssl_random_pseudo_bytes(30));
77
+
78
+			$encryptionHelper = new EncryptionHelper($this->getSiteConfiguration());
79
+
80
+			$cred = new Credential();
81
+			$cred->setDatabase($this->getDatabase());
82
+			$cred->setFactor(-1);
83
+			$cred->setUserId($user->getId());
84
+			$cred->setType('reset');
85
+			$cred->setData($encryptionHelper->encryptData($hash));
86
+			$cred->setVersion(0);
87
+			$cred->setDisabled(0);
88
+			$cred->setTimeout(new DateTimeImmutable('+ 1 hour'));
89
+			$cred->setPriority(9);
90
+			$cred->save();
91
+
92
+			$this->assign("user", $user);
93
+			$this->assign("hash", $hash);
94
+			$this->assign("remoteAddress", $clientIp);
95
+
96
+			$emailContent = $this->fetchTemplate('forgot-password/reset-mail.tpl');
97
+
98
+			$this->getEmailHelper()->sendMail($user->getEmail(), "WP:ACC password reset", $emailContent);
99
+		}
100
+	}
101
+
102
+	/**
103
+	 * Entry point for the reset action
104
+	 *
105
+	 * This is the reset password part of the form.
106
+	 * @category Security-Critical
107
+	 */
108
+	protected function reset()
109
+	{
110
+		$si = WebRequest::getString('si');
111
+		$id = WebRequest::getString('id');
112
+
113
+		if ($si === null || trim($si) === "" || $id === null || trim($id) === "") {
114
+			throw new ApplicationLogicException("Link not valid, please ensure it has copied correctly");
115
+		}
116
+
117
+		$database = $this->getDatabase();
118
+		$user = $this->getResettingUser($id, $database, $si);
119
+
120
+		// Dual mode
121
+		if (WebRequest::wasPosted()) {
122
+			$this->validateCSRFToken();
123
+			try {
124
+				$this->doReset($user);
125
+				$this->cleanExistingTokens($user);
126
+			}
127
+			catch (ApplicationLogicException $ex) {
128
+				SessionAlert::error($ex->getMessage());
129
+				$this->redirect('forgotPassword', 'reset', array('si' => $si, 'id' => $id));
130
+
131
+				return;
132
+			}
133
+		}
134
+		else {
135
+			$this->assignCSRFToken();
136
+			$this->assign('user', $user);
137
+			$this->setTemplate('forgot-password/forgotpwreset.tpl');
138
+			$this->addJs("/vendor/dropbox/zxcvbn/dist/zxcvbn.js");
139
+		}
140
+	}
141
+
142
+	/**
143
+	 * Gets the user resetting their password from the database, or throwing an exception if that is not possible.
144
+	 *
145
+	 * @param integer     $id       The ID of the user to retrieve
146
+	 * @param PdoDatabase $database The database object to use
147
+	 * @param string      $si       The reset hash provided
148
+	 *
149
+	 * @return User
150
+	 * @throws ApplicationLogicException
151
+	 */
152
+	private function getResettingUser($id, $database, $si)
153
+	{
154
+		$user = User::getById($id, $database);
155
+
156
+		if ($user === false ||  $user->isCommunityUser()) {
157
+			throw new ApplicationLogicException("Password reset failed. Please try again.");
158
+		}
159
+
160
+		$statement = $database->prepare("SELECT * FROM credential WHERE type = 'reset' AND user = :user;");
161
+		$statement->execute([':user' => $user->getId()]);
162
+
163
+		/** @var Credential $credential */
164
+		$credential = $statement->fetchObject(Credential::class);
165
+
166
+		$statement->closeCursor();
167
+
168
+		if ($credential === false) {
169
+			throw new ApplicationLogicException("Password reset failed. Please try again.");
170
+		}
171
+
172
+		$credential->setDatabase($database);
173
+
174
+		$encryptionHelper = new EncryptionHelper($this->getSiteConfiguration());
175
+		if ($encryptionHelper->decryptData($credential->getData()) != $si) {
176
+			throw new ApplicationLogicException("Password reset failed. Please try again.");
177
+		}
178
+
179
+		if ($credential->getTimeout() < new DateTimeImmutable()) {
180
+			$credential->delete();
181
+			throw new ApplicationLogicException("Password reset token expired. Please try again.");
182
+		}
183
+
184
+		return $user;
185
+	}
186
+
187
+	/**
188
+	 * Performs the setting of the new password
189
+	 *
190
+	 * @param User $user The user to set the password for
191
+	 *
192
+	 * @throws ApplicationLogicException
193
+	 */
194
+	private function doReset(User $user)
195
+	{
196
+		$pw = WebRequest::postString('pw');
197
+		$pw2 = WebRequest::postString('pw2');
198
+
199
+		if ($pw !== $pw2) {
200
+			throw new ApplicationLogicException('Passwords do not match!');
201
+		}
202
+
203
+		$passwordCredentialProvider = new PasswordCredentialProvider($user->getDatabase(), $this->getSiteConfiguration());
204
+		$passwordCredentialProvider->setCredential($user, 1, $pw);
205
+
206
+		SessionAlert::success('You may now log in!');
207
+		$this->redirect('login');
208
+	}
209
+
210
+	protected function isProtectedPage()
211
+	{
212
+		return false;
213
+	}
214
+
215
+	/**
216
+	 * @param $user
217
+	 */
218
+	private function cleanExistingTokens($user): void
219
+	{
220
+		// clean out existing reset tokens
221
+		$statement = $this->getDatabase()->prepare("SELECT * FROM credential WHERE type = 'reset' AND user = :user;");
222
+		$statement->execute([':user' => $user->getId()]);
223
+		$existing = $statement->fetchAll(PdoDatabase::FETCH_CLASS, Credential::class);
224
+
225
+		foreach ($existing as $c) {
226
+			$c->setDatabase($this->getDatabase());
227
+			$c->delete();
228
+		}
229
+	}
230 230
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -153,7 +153,7 @@
 block discarded – undo
153 153
     {
154 154
         $user = User::getById($id, $database);
155 155
 
156
-        if ($user === false ||  $user->isCommunityUser()) {
156
+        if ($user === false || $user->isCommunityUser()) {
157 157
             throw new ApplicationLogicException("Password reset failed. Please try again.");
158 158
         }
159 159
 
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -46,8 +46,7 @@  discard block
 block discarded – undo
46 46
             SessionAlert::success('<strong>Your password reset request has been completed.</strong> If the details you have provided match our records, you should receive an email shortly.');
47 47
 
48 48
             $this->redirect('login');
49
-        }
50
-        else {
49
+        } else {
51 50
             $this->assignCSRFToken();
52 51
             $this->setTemplate('forgot-password/forgotpw.tpl');
53 52
         }
@@ -130,8 +129,7 @@  discard block
 block discarded – undo
130 129
 
131 130
                 return;
132 131
             }
133
-        }
134
-        else {
132
+        } else {
135 133
             $this->assignCSRFToken();
136 134
             $this->assign('user', $user);
137 135
             $this->setTemplate('forgot-password/forgotpwreset.tpl');
Please login to merge, or discard this patch.
includes/Pages/UserAuth/PagePreferences.php 2 patches
Indentation   +90 added lines, -90 removed lines patch added patch discarded remove patch
@@ -16,94 +16,94 @@
 block discarded – undo
16 16
 
17 17
 class PagePreferences extends InternalPageBase
18 18
 {
19
-    /**
20
-     * Main function for this page, when no specific actions are called.
21
-     * @return void
22
-     */
23
-    protected function main()
24
-    {
25
-        $this->setHtmlTitle('Preferences');
26
-
27
-        $enforceOAuth = $this->getSiteConfiguration()->getEnforceOAuth();
28
-        $database = $this->getDatabase();
29
-        $user = User::getCurrent($database);
30
-
31
-        // Dual mode
32
-        if (WebRequest::wasPosted()) {
33
-            $this->validateCSRFToken();
34
-            $user->setWelcomeSig(WebRequest::postString('sig'));
35
-            $user->setEmailSig(WebRequest::postString('emailsig'));
36
-            $user->setAbortPref(WebRequest::postBoolean('abortpref') ? 1 : 0);
37
-            $this->setCreationMode($user);
38
-            $user->setSkin(WebRequest::postBoolean('skintype') ? 'alt' : 'main');
39
-
40
-            $email = WebRequest::postEmail('email');
41
-            if ($email !== null) {
42
-                $user->setEmail($email);
43
-            }
44
-
45
-            $user->save();
46
-            SessionAlert::success("Preferences updated!");
47
-
48
-            $this->redirect('');
49
-        }
50
-        else {
51
-            $this->assignCSRFToken();
52
-            $this->setTemplate('preferences/prefs.tpl');
53
-            $this->assign("enforceOAuth", $enforceOAuth);
54
-
55
-            $this->assign('canManualCreate',
56
-                $this->barrierTest(User::CREATION_MANUAL, $user, 'RequestCreation'));
57
-            $this->assign('canOauthCreate',
58
-                $this->barrierTest(User::CREATION_OAUTH, $user, 'RequestCreation'));
59
-            $this->assign('canBotCreate',
60
-                $this->barrierTest(User::CREATION_BOT, $user, 'RequestCreation'));
61
-
62
-            $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(),
63
-                $this->getSiteConfiguration());
64
-            $this->assign('oauth', $oauth);
65
-
66
-            $identity = null;
67
-            if ($oauth->isFullyLinked()) {
68
-                $identity = $oauth->getIdentity();
69
-            }
70
-
71
-            $this->assign('identity', $identity);
72
-            $this->assign('graceTime', $this->getSiteConfiguration()->getOauthIdentityGraceTime());
73
-        }
74
-    }
75
-
76
-    protected function refreshOAuth()
77
-    {
78
-        if (!WebRequest::wasPosted()) {
79
-            $this->redirect('preferences');
80
-
81
-            return;
82
-        }
83
-
84
-        $database = $this->getDatabase();
85
-        $oauth = new OAuthUserHelper(User::getCurrent($database), $database, $this->getOAuthProtocolHelper(),
86
-            $this->getSiteConfiguration());
87
-        if ($oauth->isFullyLinked()) {
88
-            $oauth->refreshIdentity();
89
-        }
90
-
91
-        $this->redirect('preferences');
92
-
93
-        return;
94
-    }
95
-
96
-    /**
97
-     * @param User $user
98
-     */
99
-    protected function setCreationMode(User $user)
100
-    {
101
-        // if the user is selecting a creation mode that they are not allowed, do nothing.
102
-        // this has the side effect of allowing them to keep a selected mode that either has been changed for them,
103
-        // or that they have kept from when they previously had certain access.
104
-        $creationMode = WebRequest::postInt('creationmode');
105
-        if ($this->barrierTest($creationMode, $user, 'RequestCreation')) {
106
-            $user->setCreationMode($creationMode);
107
-        }
108
-    }
19
+	/**
20
+	 * Main function for this page, when no specific actions are called.
21
+	 * @return void
22
+	 */
23
+	protected function main()
24
+	{
25
+		$this->setHtmlTitle('Preferences');
26
+
27
+		$enforceOAuth = $this->getSiteConfiguration()->getEnforceOAuth();
28
+		$database = $this->getDatabase();
29
+		$user = User::getCurrent($database);
30
+
31
+		// Dual mode
32
+		if (WebRequest::wasPosted()) {
33
+			$this->validateCSRFToken();
34
+			$user->setWelcomeSig(WebRequest::postString('sig'));
35
+			$user->setEmailSig(WebRequest::postString('emailsig'));
36
+			$user->setAbortPref(WebRequest::postBoolean('abortpref') ? 1 : 0);
37
+			$this->setCreationMode($user);
38
+			$user->setSkin(WebRequest::postBoolean('skintype') ? 'alt' : 'main');
39
+
40
+			$email = WebRequest::postEmail('email');
41
+			if ($email !== null) {
42
+				$user->setEmail($email);
43
+			}
44
+
45
+			$user->save();
46
+			SessionAlert::success("Preferences updated!");
47
+
48
+			$this->redirect('');
49
+		}
50
+		else {
51
+			$this->assignCSRFToken();
52
+			$this->setTemplate('preferences/prefs.tpl');
53
+			$this->assign("enforceOAuth", $enforceOAuth);
54
+
55
+			$this->assign('canManualCreate',
56
+				$this->barrierTest(User::CREATION_MANUAL, $user, 'RequestCreation'));
57
+			$this->assign('canOauthCreate',
58
+				$this->barrierTest(User::CREATION_OAUTH, $user, 'RequestCreation'));
59
+			$this->assign('canBotCreate',
60
+				$this->barrierTest(User::CREATION_BOT, $user, 'RequestCreation'));
61
+
62
+			$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(),
63
+				$this->getSiteConfiguration());
64
+			$this->assign('oauth', $oauth);
65
+
66
+			$identity = null;
67
+			if ($oauth->isFullyLinked()) {
68
+				$identity = $oauth->getIdentity();
69
+			}
70
+
71
+			$this->assign('identity', $identity);
72
+			$this->assign('graceTime', $this->getSiteConfiguration()->getOauthIdentityGraceTime());
73
+		}
74
+	}
75
+
76
+	protected function refreshOAuth()
77
+	{
78
+		if (!WebRequest::wasPosted()) {
79
+			$this->redirect('preferences');
80
+
81
+			return;
82
+		}
83
+
84
+		$database = $this->getDatabase();
85
+		$oauth = new OAuthUserHelper(User::getCurrent($database), $database, $this->getOAuthProtocolHelper(),
86
+			$this->getSiteConfiguration());
87
+		if ($oauth->isFullyLinked()) {
88
+			$oauth->refreshIdentity();
89
+		}
90
+
91
+		$this->redirect('preferences');
92
+
93
+		return;
94
+	}
95
+
96
+	/**
97
+	 * @param User $user
98
+	 */
99
+	protected function setCreationMode(User $user)
100
+	{
101
+		// if the user is selecting a creation mode that they are not allowed, do nothing.
102
+		// this has the side effect of allowing them to keep a selected mode that either has been changed for them,
103
+		// or that they have kept from when they previously had certain access.
104
+		$creationMode = WebRequest::postInt('creationmode');
105
+		if ($this->barrierTest($creationMode, $user, 'RequestCreation')) {
106
+			$user->setCreationMode($creationMode);
107
+		}
108
+	}
109 109
 }
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -46,8 +46,7 @@
 block discarded – undo
46 46
             SessionAlert::success("Preferences updated!");
47 47
 
48 48
             $this->redirect('');
49
-        }
50
-        else {
49
+        } else {
51 50
             $this->assignCSRFToken();
52 51
             $this->setTemplate('preferences/prefs.tpl');
53 52
             $this->assign("enforceOAuth", $enforceOAuth);
Please login to merge, or discard this patch.
includes/Pages/UserAuth/MultiFactor/PageMultiFactor.php 3 patches
Indentation   +389 added lines, -389 removed lines patch added patch discarded remove patch
@@ -25,247 +25,247 @@  discard block
 block discarded – undo
25 25
 
26 26
 class PageMultiFactor extends InternalPageBase
27 27
 {
28
-    /**
29
-     * Main function for this page, when no specific actions are called.
30
-     * @return void
31
-     */
32
-    protected function main()
33
-    {
34
-        $database = $this->getDatabase();
35
-        $currentUser = User::getCurrent($database);
36
-
37
-        $yubikeyOtpCredentialProvider = new YubikeyOtpCredentialProvider($database, $this->getSiteConfiguration(),
38
-            $this->getHttpHelper());
39
-        $this->assign('yubikeyOtpIdentity', $yubikeyOtpCredentialProvider->getYubikeyData($currentUser->getId()));
40
-        $this->assign('yubikeyOtpEnrolled', $yubikeyOtpCredentialProvider->userIsEnrolled($currentUser->getId()));
41
-
42
-        $totpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
43
-        $this->assign('totpEnrolled', $totpCredentialProvider->userIsEnrolled($currentUser->getId()));
44
-
45
-        $u2fCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
46
-        $this->assign('u2fEnrolled', $u2fCredentialProvider->userIsEnrolled($currentUser->getId()));
47
-
48
-        $scratchCredentialProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
49
-        $this->assign('scratchEnrolled', $scratchCredentialProvider->userIsEnrolled($currentUser->getId()));
50
-        $this->assign('scratchRemaining', $scratchCredentialProvider->getRemaining($currentUser->getId()));
51
-
52
-        $this->assign('allowedTotp', $this->barrierTest('enableTotp', $currentUser));
53
-        $this->assign('allowedYubikey', $this->barrierTest('enableYubikeyOtp', $currentUser));
54
-        $this->assign('allowedU2f', $this->barrierTest('enableU2F', $currentUser));
55
-
56
-        $this->setTemplate('mfa/mfa.tpl');
57
-    }
58
-
59
-    protected function enableYubikeyOtp()
60
-    {
61
-        $database = $this->getDatabase();
62
-        $currentUser = User::getCurrent($database);
63
-
64
-        $otpCredentialProvider = new YubikeyOtpCredentialProvider($database,
65
-            $this->getSiteConfiguration(), $this->getHttpHelper());
66
-
67
-        if (WebRequest::wasPosted()) {
68
-            $this->validateCSRFToken();
69
-
70
-            $passwordCredentialProvider = new PasswordCredentialProvider($database,
71
-                $this->getSiteConfiguration());
72
-
73
-            $password = WebRequest::postString('password');
74
-            $otp = WebRequest::postString('otp');
75
-
76
-            $result = $passwordCredentialProvider->authenticate($currentUser, $password);
77
-
78
-            if ($result) {
79
-                try {
80
-                    $otpCredentialProvider->setCredential($currentUser, 2, $otp);
81
-                    SessionAlert::success('Enabled YubiKey OTP.');
82
-
83
-                    $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
84
-                    if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
85
-                        $scratchProvider->setCredential($currentUser, 2, null);
86
-                        $tokens = $scratchProvider->getTokens();
87
-                        $this->assign('tokens', $tokens);
88
-                        $this->setTemplate('mfa/regenScratchTokens.tpl');
89
-                        return;
90
-                    }
91
-                }
92
-                catch (ApplicationLogicException $ex) {
93
-                    SessionAlert::error('Error enabling YubiKey OTP: ' . $ex->getMessage());
94
-                }
95
-
96
-                $this->redirect('multiFactor');
97
-            }
98
-            else {
99
-                SessionAlert::error('Error enabling YubiKey OTP - invalid credentials.');
100
-                $this->redirect('multiFactor');
101
-            }
102
-        }
103
-        else {
104
-            if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
105
-                // user is not enrolled, we shouldn't have got here.
106
-                throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
107
-            }
108
-
109
-            $this->assignCSRFToken();
110
-            $this->setTemplate('mfa/enableYubikey.tpl');
111
-        }
112
-    }
113
-
114
-    protected function disableYubikeyOtp()
115
-    {
116
-        $database = $this->getDatabase();
117
-        $currentUser = User::getCurrent($database);
118
-
119
-        $otpCredentialProvider = new YubikeyOtpCredentialProvider($database,
120
-            $this->getSiteConfiguration(), $this->getHttpHelper());
121
-
122
-        $factorType = 'YubiKey OTP';
123
-
124
-        $this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
125
-    }
126
-
127
-    protected function enableTotp()
128
-    {
129
-        $database = $this->getDatabase();
130
-        $currentUser = User::getCurrent($database);
131
-
132
-        $otpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
133
-
134
-        if (WebRequest::wasPosted()) {
135
-            $this->validateCSRFToken();
136
-
137
-            // used for routing only, not security
138
-            $stage = WebRequest::postString('stage');
139
-
140
-            if ($stage === "auth") {
141
-                $password = WebRequest::postString('password');
142
-
143
-                $passwordCredentialProvider = new PasswordCredentialProvider($database,
144
-                    $this->getSiteConfiguration());
145
-                $result = $passwordCredentialProvider->authenticate($currentUser, $password);
146
-
147
-                if ($result) {
148
-                    $otpCredentialProvider->setCredential($currentUser, 2, null);
149
-
150
-                    $provisioningUrl = $otpCredentialProvider->getProvisioningUrl($currentUser);
151
-
152
-                    $renderer = new Svg();
153
-                    $renderer->setHeight(256);
154
-                    $renderer->setWidth(256);
155
-                    $writer = new Writer($renderer);
156
-                    $svg = $writer->writeString($provisioningUrl);
157
-
158
-                    $this->assign('svg', $svg);
159
-                    $this->assign('secret', $otpCredentialProvider->getSecret($currentUser));
160
-
161
-                    $this->assignCSRFToken();
162
-                    $this->setTemplate('mfa/enableTotpEnroll.tpl');
163
-
164
-                    return;
165
-                }
166
-                else {
167
-                    SessionAlert::error('Error enabling TOTP - invalid credentials.');
168
-                    $this->redirect('multiFactor');
169
-
170
-                    return;
171
-                }
172
-            }
173
-
174
-            if ($stage === "enroll") {
175
-                // we *must* have a defined credential already here,
176
-                if ($otpCredentialProvider->isPartiallyEnrolled($currentUser)) {
177
-                    $otp = WebRequest::postString('otp');
178
-                    $result = $otpCredentialProvider->verifyEnable($currentUser, $otp);
179
-
180
-                    if ($result) {
181
-                        SessionAlert::success('Enabled TOTP.');
182
-
183
-                        $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
184
-                        if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
185
-                            $scratchProvider->setCredential($currentUser, 2, null);
186
-                            $tokens = $scratchProvider->getTokens();
187
-                            $this->assign('tokens', $tokens);
188
-                            $this->setTemplate('mfa/regenScratchTokens.tpl');
189
-                            return;
190
-                        }
191
-                    }
192
-                    else {
193
-                        $otpCredentialProvider->deleteCredential($currentUser);
194
-                        SessionAlert::error('Error enabling TOTP: invalid token provided');
195
-                    }
196
-
197
-
198
-                    $this->redirect('multiFactor');
199
-                    return;
200
-                }
201
-                else {
202
-                    SessionAlert::error('Error enabling TOTP - no enrollment found or enrollment expired.');
203
-                    $this->redirect('multiFactor');
28
+	/**
29
+	 * Main function for this page, when no specific actions are called.
30
+	 * @return void
31
+	 */
32
+	protected function main()
33
+	{
34
+		$database = $this->getDatabase();
35
+		$currentUser = User::getCurrent($database);
36
+
37
+		$yubikeyOtpCredentialProvider = new YubikeyOtpCredentialProvider($database, $this->getSiteConfiguration(),
38
+			$this->getHttpHelper());
39
+		$this->assign('yubikeyOtpIdentity', $yubikeyOtpCredentialProvider->getYubikeyData($currentUser->getId()));
40
+		$this->assign('yubikeyOtpEnrolled', $yubikeyOtpCredentialProvider->userIsEnrolled($currentUser->getId()));
41
+
42
+		$totpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
43
+		$this->assign('totpEnrolled', $totpCredentialProvider->userIsEnrolled($currentUser->getId()));
44
+
45
+		$u2fCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
46
+		$this->assign('u2fEnrolled', $u2fCredentialProvider->userIsEnrolled($currentUser->getId()));
47
+
48
+		$scratchCredentialProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
49
+		$this->assign('scratchEnrolled', $scratchCredentialProvider->userIsEnrolled($currentUser->getId()));
50
+		$this->assign('scratchRemaining', $scratchCredentialProvider->getRemaining($currentUser->getId()));
51
+
52
+		$this->assign('allowedTotp', $this->barrierTest('enableTotp', $currentUser));
53
+		$this->assign('allowedYubikey', $this->barrierTest('enableYubikeyOtp', $currentUser));
54
+		$this->assign('allowedU2f', $this->barrierTest('enableU2F', $currentUser));
55
+
56
+		$this->setTemplate('mfa/mfa.tpl');
57
+	}
204 58
 
205
-                    return;
206
-                }
207
-            }
59
+	protected function enableYubikeyOtp()
60
+	{
61
+		$database = $this->getDatabase();
62
+		$currentUser = User::getCurrent($database);
63
+
64
+		$otpCredentialProvider = new YubikeyOtpCredentialProvider($database,
65
+			$this->getSiteConfiguration(), $this->getHttpHelper());
66
+
67
+		if (WebRequest::wasPosted()) {
68
+			$this->validateCSRFToken();
69
+
70
+			$passwordCredentialProvider = new PasswordCredentialProvider($database,
71
+				$this->getSiteConfiguration());
72
+
73
+			$password = WebRequest::postString('password');
74
+			$otp = WebRequest::postString('otp');
75
+
76
+			$result = $passwordCredentialProvider->authenticate($currentUser, $password);
77
+
78
+			if ($result) {
79
+				try {
80
+					$otpCredentialProvider->setCredential($currentUser, 2, $otp);
81
+					SessionAlert::success('Enabled YubiKey OTP.');
82
+
83
+					$scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
84
+					if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
85
+						$scratchProvider->setCredential($currentUser, 2, null);
86
+						$tokens = $scratchProvider->getTokens();
87
+						$this->assign('tokens', $tokens);
88
+						$this->setTemplate('mfa/regenScratchTokens.tpl');
89
+						return;
90
+					}
91
+				}
92
+				catch (ApplicationLogicException $ex) {
93
+					SessionAlert::error('Error enabling YubiKey OTP: ' . $ex->getMessage());
94
+				}
95
+
96
+				$this->redirect('multiFactor');
97
+			}
98
+			else {
99
+				SessionAlert::error('Error enabling YubiKey OTP - invalid credentials.');
100
+				$this->redirect('multiFactor');
101
+			}
102
+		}
103
+		else {
104
+			if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
105
+				// user is not enrolled, we shouldn't have got here.
106
+				throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
107
+			}
108
+
109
+			$this->assignCSRFToken();
110
+			$this->setTemplate('mfa/enableYubikey.tpl');
111
+		}
112
+	}
208 113
 
209
-            // urgh, dunno what happened, but it's not something expected.
210
-            throw new ApplicationLogicException();
211
-        }
212
-        else {
213
-            if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
214
-                // user is not enrolled, we shouldn't have got here.
215
-                throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
216
-            }
114
+	protected function disableYubikeyOtp()
115
+	{
116
+		$database = $this->getDatabase();
117
+		$currentUser = User::getCurrent($database);
217 118
 
218
-            $this->assignCSRFToken();
119
+		$otpCredentialProvider = new YubikeyOtpCredentialProvider($database,
120
+			$this->getSiteConfiguration(), $this->getHttpHelper());
219 121
 
220
-            $this->assign('alertmessage', 'To enable your multi-factor credentials, please prove you are who you say you are by providing the information below.');
221
-            $this->assign('alertheader', 'Provide credentials');
222
-            $this->assign('continueText', 'Verify password');
223
-            $this->setTemplate('mfa/enableAuth.tpl');
224
-        }
225
-    }
122
+		$factorType = 'YubiKey OTP';
226 123
 
227
-    protected function disableTotp()
228
-    {
229
-        $database = $this->getDatabase();
230
-        $currentUser = User::getCurrent($database);
124
+		$this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
125
+	}
126
+
127
+	protected function enableTotp()
128
+	{
129
+		$database = $this->getDatabase();
130
+		$currentUser = User::getCurrent($database);
131
+
132
+		$otpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
133
+
134
+		if (WebRequest::wasPosted()) {
135
+			$this->validateCSRFToken();
136
+
137
+			// used for routing only, not security
138
+			$stage = WebRequest::postString('stage');
139
+
140
+			if ($stage === "auth") {
141
+				$password = WebRequest::postString('password');
142
+
143
+				$passwordCredentialProvider = new PasswordCredentialProvider($database,
144
+					$this->getSiteConfiguration());
145
+				$result = $passwordCredentialProvider->authenticate($currentUser, $password);
146
+
147
+				if ($result) {
148
+					$otpCredentialProvider->setCredential($currentUser, 2, null);
149
+
150
+					$provisioningUrl = $otpCredentialProvider->getProvisioningUrl($currentUser);
151
+
152
+					$renderer = new Svg();
153
+					$renderer->setHeight(256);
154
+					$renderer->setWidth(256);
155
+					$writer = new Writer($renderer);
156
+					$svg = $writer->writeString($provisioningUrl);
157
+
158
+					$this->assign('svg', $svg);
159
+					$this->assign('secret', $otpCredentialProvider->getSecret($currentUser));
160
+
161
+					$this->assignCSRFToken();
162
+					$this->setTemplate('mfa/enableTotpEnroll.tpl');
163
+
164
+					return;
165
+				}
166
+				else {
167
+					SessionAlert::error('Error enabling TOTP - invalid credentials.');
168
+					$this->redirect('multiFactor');
169
+
170
+					return;
171
+				}
172
+			}
173
+
174
+			if ($stage === "enroll") {
175
+				// we *must* have a defined credential already here,
176
+				if ($otpCredentialProvider->isPartiallyEnrolled($currentUser)) {
177
+					$otp = WebRequest::postString('otp');
178
+					$result = $otpCredentialProvider->verifyEnable($currentUser, $otp);
179
+
180
+					if ($result) {
181
+						SessionAlert::success('Enabled TOTP.');
182
+
183
+						$scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
184
+						if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
185
+							$scratchProvider->setCredential($currentUser, 2, null);
186
+							$tokens = $scratchProvider->getTokens();
187
+							$this->assign('tokens', $tokens);
188
+							$this->setTemplate('mfa/regenScratchTokens.tpl');
189
+							return;
190
+						}
191
+					}
192
+					else {
193
+						$otpCredentialProvider->deleteCredential($currentUser);
194
+						SessionAlert::error('Error enabling TOTP: invalid token provided');
195
+					}
196
+
197
+
198
+					$this->redirect('multiFactor');
199
+					return;
200
+				}
201
+				else {
202
+					SessionAlert::error('Error enabling TOTP - no enrollment found or enrollment expired.');
203
+					$this->redirect('multiFactor');
204
+
205
+					return;
206
+				}
207
+			}
208
+
209
+			// urgh, dunno what happened, but it's not something expected.
210
+			throw new ApplicationLogicException();
211
+		}
212
+		else {
213
+			if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
214
+				// user is not enrolled, we shouldn't have got here.
215
+				throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
216
+			}
217
+
218
+			$this->assignCSRFToken();
219
+
220
+			$this->assign('alertmessage', 'To enable your multi-factor credentials, please prove you are who you say you are by providing the information below.');
221
+			$this->assign('alertheader', 'Provide credentials');
222
+			$this->assign('continueText', 'Verify password');
223
+			$this->setTemplate('mfa/enableAuth.tpl');
224
+		}
225
+	}
231 226
 
232
-        $otpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
227
+	protected function disableTotp()
228
+	{
229
+		$database = $this->getDatabase();
230
+		$currentUser = User::getCurrent($database);
231
+
232
+		$otpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
233
+
234
+		$factorType = 'TOTP';
235
+
236
+		$this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
237
+	}
233 238
 
234
-        $factorType = 'TOTP';
239
+	protected function enableU2F() {
240
+		$database = $this->getDatabase();
241
+		$currentUser = User::getCurrent($database);
235 242
 
236
-        $this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
237
-    }
243
+		$otpCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
238 244
 
239
-    protected function enableU2F() {
240
-        $database = $this->getDatabase();
241
-        $currentUser = User::getCurrent($database);
245
+		if (WebRequest::wasPosted()) {
246
+			$this->validateCSRFToken();
242 247
 
243
-        $otpCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
244
-
245
-        if (WebRequest::wasPosted()) {
246
-            $this->validateCSRFToken();
247
-
248
-            // used for routing only, not security
249
-            $stage = WebRequest::postString('stage');
250
-
251
-            if ($stage === "auth") {
252
-                $password = WebRequest::postString('password');
253
-
254
-                $passwordCredentialProvider = new PasswordCredentialProvider($database,
255
-                    $this->getSiteConfiguration());
256
-                $result = $passwordCredentialProvider->authenticate($currentUser, $password);
257
-
258
-                if ($result) {
259
-                    $otpCredentialProvider->setCredential($currentUser, 2, null);
260
-                    $this->assignCSRFToken();
261
-
262
-                    list($data, $reqs) = $otpCredentialProvider->getRegistrationData();
263
-
264
-                    $u2fRequest =json_encode($data);
265
-                    $u2fSigns = json_encode($reqs);
266
-
267
-                    $this->addJs('/vendor/yubico/u2flib-server/examples/assets/u2f-api.js');
268
-                    $this->setTailScript($this->getCspManager()->getNonce(), <<<JS
248
+			// used for routing only, not security
249
+			$stage = WebRequest::postString('stage');
250
+
251
+			if ($stage === "auth") {
252
+				$password = WebRequest::postString('password');
253
+
254
+				$passwordCredentialProvider = new PasswordCredentialProvider($database,
255
+					$this->getSiteConfiguration());
256
+				$result = $passwordCredentialProvider->authenticate($currentUser, $password);
257
+
258
+				if ($result) {
259
+					$otpCredentialProvider->setCredential($currentUser, 2, null);
260
+					$this->assignCSRFToken();
261
+
262
+					list($data, $reqs) = $otpCredentialProvider->getRegistrationData();
263
+
264
+					$u2fRequest =json_encode($data);
265
+					$u2fSigns = json_encode($reqs);
266
+
267
+					$this->addJs('/vendor/yubico/u2flib-server/examples/assets/u2f-api.js');
268
+					$this->setTailScript($this->getCspManager()->getNonce(), <<<JS
269 269
 var request = ${u2fRequest};
270 270
 var signs = ${u2fSigns};
271 271
 
@@ -284,162 +284,162 @@  discard block
 block discarded – undo
284 284
 	form.submit();
285 285
 });
286 286
 JS
287
-                    );
288
-
289
-                    $this->setTemplate('mfa/enableU2FEnroll.tpl');
290
-
291
-                    return;
292
-                }
293
-                else {
294
-                    SessionAlert::error('Error enabling TOTP - invalid credentials.');
295
-                    $this->redirect('multiFactor');
296
-
297
-                    return;
298
-                }
299
-            }
300
-
301
-            if ($stage === "enroll") {
302
-                // we *must* have a defined credential already here,
303
-                if ($otpCredentialProvider->isPartiallyEnrolled($currentUser)) {
304
-
305
-                    $request = json_decode(WebRequest::postString('u2fRequest'));
306
-                    $u2fData = json_decode(WebRequest::postString('u2fData'));
307
-
308
-                    $otpCredentialProvider->enable($currentUser, $request, $u2fData);
309
-
310
-                    SessionAlert::success('Enabled U2F.');
311
-
312
-                    $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
313
-                    if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
314
-                        $scratchProvider->setCredential($currentUser, 2, null);
315
-                        $tokens = $scratchProvider->getTokens();
316
-                        $this->assign('tokens', $tokens);
317
-                        $this->setTemplate('mfa/regenScratchTokens.tpl');
318
-                        return;
319
-                    }
320
-
321
-                    $this->redirect('multiFactor');
322
-                    return;
323
-                }
324
-                else {
325
-                    SessionAlert::error('Error enabling TOTP - no enrollment found or enrollment expired.');
326
-                    $this->redirect('multiFactor');
327
-
328
-                    return;
329
-                }
330
-            }
331
-
332
-            // urgh, dunno what happened, but it's not something expected.
333
-            throw new ApplicationLogicException();
334
-        }
335
-        else {
336
-            if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
337
-                // user is not enrolled, we shouldn't have got here.
338
-                throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
339
-            }
340
-
341
-            $this->assignCSRFToken();
342
-
343
-            $this->assign('alertmessage', 'To enable your multi-factor credentials, please prove you are who you say you are by providing the information below.');
344
-            $this->assign('alertheader', 'Provide credentials');
345
-            $this->assign('continueText', 'Verify password');
346
-            $this->setTemplate('mfa/enableAuth.tpl');
347
-        }
348
-    }
349
-
350
-    protected function disableU2F() {
351
-        $database = $this->getDatabase();
352
-        $currentUser = User::getCurrent($database);
353
-
354
-        $otpCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
355
-
356
-        $factorType = 'U2F';
357
-
358
-        $this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
359
-    }
360
-
361
-    protected function scratch()
362
-    {
363
-        $database = $this->getDatabase();
364
-        $currentUser = User::getCurrent($database);
365
-
366
-        if (WebRequest::wasPosted()) {
367
-            $this->validateCSRFToken();
368
-
369
-            $passwordCredentialProvider = new PasswordCredentialProvider($database,
370
-                $this->getSiteConfiguration());
371
-
372
-            $otpCredentialProvider = new ScratchTokenCredentialProvider($database,
373
-                $this->getSiteConfiguration());
374
-
375
-            $password = WebRequest::postString('password');
376
-
377
-            $result = $passwordCredentialProvider->authenticate($currentUser, $password);
378
-
379
-            if ($result) {
380
-                $otpCredentialProvider->setCredential($currentUser, 2, null);
381
-                $tokens = $otpCredentialProvider->getTokens();
382
-                $this->assign('tokens', $tokens);
383
-                $this->setTemplate('mfa/regenScratchTokens.tpl');
384
-            }
385
-            else {
386
-                SessionAlert::error('Error refreshing scratch tokens - invalid credentials.');
387
-                $this->redirect('multiFactor');
388
-            }
389
-        }
390
-        else {
391
-            $this->assignCSRFToken();
392
-
393
-            $this->assign('alertmessage', 'To regenerate your emergency scratch tokens, please prove you are who you say you are by providing the information below. Note that continuing will invalidate all remaining scratch tokens, and provide a set of new ones.');
394
-            $this->assign('alertheader', 'Re-generate scratch tokens');
395
-            $this->assign('continueText', 'Regenerate Scratch Tokens');
396
-
397
-            $this->setTemplate('mfa/enableAuth.tpl');
398
-        }
399
-    }
400
-
401
-    /**
402
-     * @param PdoDatabase         $database
403
-     * @param User                $currentUser
404
-     * @param ICredentialProvider $otpCredentialProvider
405
-     * @param string              $factorType
406
-     *
407
-     * @throws ApplicationLogicException
408
-     */
409
-    private function deleteCredential(
410
-        PdoDatabase $database,
411
-        User $currentUser,
412
-        ICredentialProvider $otpCredentialProvider,
413
-        $factorType
414
-    ) {
415
-        if (WebRequest::wasPosted()) {
416
-            $passwordCredentialProvider = new PasswordCredentialProvider($database,
417
-                $this->getSiteConfiguration());
418
-
419
-            $this->validateCSRFToken();
420
-
421
-            $password = WebRequest::postString('password');
422
-            $result = $passwordCredentialProvider->authenticate($currentUser, $password);
423
-
424
-            if ($result) {
425
-                $otpCredentialProvider->deleteCredential($currentUser);
426
-                SessionAlert::success('Disabled ' . $factorType . '.');
427
-                $this->redirect('multiFactor');
428
-            }
429
-            else {
430
-                SessionAlert::error('Error disabling ' . $factorType . ' - invalid credentials.');
431
-                $this->redirect('multiFactor');
432
-            }
433
-        }
434
-        else {
435
-            if (!$otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
436
-                // user is not enrolled, we shouldn't have got here.
437
-                throw new ApplicationLogicException('User is not enrolled in the selected MFA mechanism');
438
-            }
439
-
440
-            $this->assignCSRFToken();
441
-            $this->assign('otpType', $factorType);
442
-            $this->setTemplate('mfa/disableOtp.tpl');
443
-        }
444
-    }
287
+					);
288
+
289
+					$this->setTemplate('mfa/enableU2FEnroll.tpl');
290
+
291
+					return;
292
+				}
293
+				else {
294
+					SessionAlert::error('Error enabling TOTP - invalid credentials.');
295
+					$this->redirect('multiFactor');
296
+
297
+					return;
298
+				}
299
+			}
300
+
301
+			if ($stage === "enroll") {
302
+				// we *must* have a defined credential already here,
303
+				if ($otpCredentialProvider->isPartiallyEnrolled($currentUser)) {
304
+
305
+					$request = json_decode(WebRequest::postString('u2fRequest'));
306
+					$u2fData = json_decode(WebRequest::postString('u2fData'));
307
+
308
+					$otpCredentialProvider->enable($currentUser, $request, $u2fData);
309
+
310
+					SessionAlert::success('Enabled U2F.');
311
+
312
+					$scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
313
+					if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
314
+						$scratchProvider->setCredential($currentUser, 2, null);
315
+						$tokens = $scratchProvider->getTokens();
316
+						$this->assign('tokens', $tokens);
317
+						$this->setTemplate('mfa/regenScratchTokens.tpl');
318
+						return;
319
+					}
320
+
321
+					$this->redirect('multiFactor');
322
+					return;
323
+				}
324
+				else {
325
+					SessionAlert::error('Error enabling TOTP - no enrollment found or enrollment expired.');
326
+					$this->redirect('multiFactor');
327
+
328
+					return;
329
+				}
330
+			}
331
+
332
+			// urgh, dunno what happened, but it's not something expected.
333
+			throw new ApplicationLogicException();
334
+		}
335
+		else {
336
+			if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
337
+				// user is not enrolled, we shouldn't have got here.
338
+				throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
339
+			}
340
+
341
+			$this->assignCSRFToken();
342
+
343
+			$this->assign('alertmessage', 'To enable your multi-factor credentials, please prove you are who you say you are by providing the information below.');
344
+			$this->assign('alertheader', 'Provide credentials');
345
+			$this->assign('continueText', 'Verify password');
346
+			$this->setTemplate('mfa/enableAuth.tpl');
347
+		}
348
+	}
349
+
350
+	protected function disableU2F() {
351
+		$database = $this->getDatabase();
352
+		$currentUser = User::getCurrent($database);
353
+
354
+		$otpCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
355
+
356
+		$factorType = 'U2F';
357
+
358
+		$this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
359
+	}
360
+
361
+	protected function scratch()
362
+	{
363
+		$database = $this->getDatabase();
364
+		$currentUser = User::getCurrent($database);
365
+
366
+		if (WebRequest::wasPosted()) {
367
+			$this->validateCSRFToken();
368
+
369
+			$passwordCredentialProvider = new PasswordCredentialProvider($database,
370
+				$this->getSiteConfiguration());
371
+
372
+			$otpCredentialProvider = new ScratchTokenCredentialProvider($database,
373
+				$this->getSiteConfiguration());
374
+
375
+			$password = WebRequest::postString('password');
376
+
377
+			$result = $passwordCredentialProvider->authenticate($currentUser, $password);
378
+
379
+			if ($result) {
380
+				$otpCredentialProvider->setCredential($currentUser, 2, null);
381
+				$tokens = $otpCredentialProvider->getTokens();
382
+				$this->assign('tokens', $tokens);
383
+				$this->setTemplate('mfa/regenScratchTokens.tpl');
384
+			}
385
+			else {
386
+				SessionAlert::error('Error refreshing scratch tokens - invalid credentials.');
387
+				$this->redirect('multiFactor');
388
+			}
389
+		}
390
+		else {
391
+			$this->assignCSRFToken();
392
+
393
+			$this->assign('alertmessage', 'To regenerate your emergency scratch tokens, please prove you are who you say you are by providing the information below. Note that continuing will invalidate all remaining scratch tokens, and provide a set of new ones.');
394
+			$this->assign('alertheader', 'Re-generate scratch tokens');
395
+			$this->assign('continueText', 'Regenerate Scratch Tokens');
396
+
397
+			$this->setTemplate('mfa/enableAuth.tpl');
398
+		}
399
+	}
400
+
401
+	/**
402
+	 * @param PdoDatabase         $database
403
+	 * @param User                $currentUser
404
+	 * @param ICredentialProvider $otpCredentialProvider
405
+	 * @param string              $factorType
406
+	 *
407
+	 * @throws ApplicationLogicException
408
+	 */
409
+	private function deleteCredential(
410
+		PdoDatabase $database,
411
+		User $currentUser,
412
+		ICredentialProvider $otpCredentialProvider,
413
+		$factorType
414
+	) {
415
+		if (WebRequest::wasPosted()) {
416
+			$passwordCredentialProvider = new PasswordCredentialProvider($database,
417
+				$this->getSiteConfiguration());
418
+
419
+			$this->validateCSRFToken();
420
+
421
+			$password = WebRequest::postString('password');
422
+			$result = $passwordCredentialProvider->authenticate($currentUser, $password);
423
+
424
+			if ($result) {
425
+				$otpCredentialProvider->deleteCredential($currentUser);
426
+				SessionAlert::success('Disabled ' . $factorType . '.');
427
+				$this->redirect('multiFactor');
428
+			}
429
+			else {
430
+				SessionAlert::error('Error disabling ' . $factorType . ' - invalid credentials.');
431
+				$this->redirect('multiFactor');
432
+			}
433
+		}
434
+		else {
435
+			if (!$otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
436
+				// user is not enrolled, we shouldn't have got here.
437
+				throw new ApplicationLogicException('User is not enrolled in the selected MFA mechanism');
438
+			}
439
+
440
+			$this->assignCSRFToken();
441
+			$this->assign('otpType', $factorType);
442
+			$this->setTemplate('mfa/disableOtp.tpl');
443
+		}
444
+	}
445 445
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
                     SessionAlert::success('Enabled YubiKey OTP.');
82 82
 
83 83
                     $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
84
-                    if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
84
+                    if ($scratchProvider->getRemaining($currentUser->getId()) < 3) {
85 85
                         $scratchProvider->setCredential($currentUser, 2, null);
86 86
                         $tokens = $scratchProvider->getTokens();
87 87
                         $this->assign('tokens', $tokens);
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
                         SessionAlert::success('Enabled TOTP.');
182 182
 
183 183
                         $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
184
-                        if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
184
+                        if ($scratchProvider->getRemaining($currentUser->getId()) < 3) {
185 185
                             $scratchProvider->setCredential($currentUser, 2, null);
186 186
                             $tokens = $scratchProvider->getTokens();
187 187
                             $this->assign('tokens', $tokens);
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 
262 262
                     list($data, $reqs) = $otpCredentialProvider->getRegistrationData();
263 263
 
264
-                    $u2fRequest =json_encode($data);
264
+                    $u2fRequest = json_encode($data);
265 265
                     $u2fSigns = json_encode($reqs);
266 266
 
267 267
                     $this->addJs('/vendor/yubico/u2flib-server/examples/assets/u2f-api.js');
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
                     SessionAlert::success('Enabled U2F.');
311 311
 
312 312
                     $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
313
-                    if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
313
+                    if ($scratchProvider->getRemaining($currentUser->getId()) < 3) {
314 314
                         $scratchProvider->setCredential($currentUser, 2, null);
315 315
                         $tokens = $scratchProvider->getTokens();
316 316
                         $this->assign('tokens', $tokens);
Please login to merge, or discard this patch.
Braces   +17 added lines, -28 removed lines patch added patch discarded remove patch
@@ -94,13 +94,11 @@  discard block
 block discarded – undo
94 94
                 }
95 95
 
96 96
                 $this->redirect('multiFactor');
97
-            }
98
-            else {
97
+            } else {
99 98
                 SessionAlert::error('Error enabling YubiKey OTP - invalid credentials.');
100 99
                 $this->redirect('multiFactor');
101 100
             }
102
-        }
103
-        else {
101
+        } else {
104 102
             if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
105 103
                 // user is not enrolled, we shouldn't have got here.
106 104
                 throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
@@ -162,8 +160,7 @@  discard block
 block discarded – undo
162 160
                     $this->setTemplate('mfa/enableTotpEnroll.tpl');
163 161
 
164 162
                     return;
165
-                }
166
-                else {
163
+                } else {
167 164
                     SessionAlert::error('Error enabling TOTP - invalid credentials.');
168 165
                     $this->redirect('multiFactor');
169 166
 
@@ -188,8 +185,7 @@  discard block
 block discarded – undo
188 185
                             $this->setTemplate('mfa/regenScratchTokens.tpl');
189 186
                             return;
190 187
                         }
191
-                    }
192
-                    else {
188
+                    } else {
193 189
                         $otpCredentialProvider->deleteCredential($currentUser);
194 190
                         SessionAlert::error('Error enabling TOTP: invalid token provided');
195 191
                     }
@@ -197,8 +193,7 @@  discard block
 block discarded – undo
197 193
 
198 194
                     $this->redirect('multiFactor');
199 195
                     return;
200
-                }
201
-                else {
196
+                } else {
202 197
                     SessionAlert::error('Error enabling TOTP - no enrollment found or enrollment expired.');
203 198
                     $this->redirect('multiFactor');
204 199
 
@@ -208,8 +203,7 @@  discard block
 block discarded – undo
208 203
 
209 204
             // urgh, dunno what happened, but it's not something expected.
210 205
             throw new ApplicationLogicException();
211
-        }
212
-        else {
206
+        } else {
213 207
             if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
214 208
                 // user is not enrolled, we shouldn't have got here.
215 209
                 throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
@@ -236,7 +230,8 @@  discard block
 block discarded – undo
236 230
         $this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
237 231
     }
238 232
 
239
-    protected function enableU2F() {
233
+    protected function enableU2F()
234
+    {
240 235
         $database = $this->getDatabase();
241 236
         $currentUser = User::getCurrent($database);
242 237
 
@@ -289,8 +284,7 @@  discard block
 block discarded – undo
289 284
                     $this->setTemplate('mfa/enableU2FEnroll.tpl');
290 285
 
291 286
                     return;
292
-                }
293
-                else {
287
+                } else {
294 288
                     SessionAlert::error('Error enabling TOTP - invalid credentials.');
295 289
                     $this->redirect('multiFactor');
296 290
 
@@ -320,8 +314,7 @@  discard block
 block discarded – undo
320 314
 
321 315
                     $this->redirect('multiFactor');
322 316
                     return;
323
-                }
324
-                else {
317
+                } else {
325 318
                     SessionAlert::error('Error enabling TOTP - no enrollment found or enrollment expired.');
326 319
                     $this->redirect('multiFactor');
327 320
 
@@ -331,8 +324,7 @@  discard block
 block discarded – undo
331 324
 
332 325
             // urgh, dunno what happened, but it's not something expected.
333 326
             throw new ApplicationLogicException();
334
-        }
335
-        else {
327
+        } else {
336 328
             if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
337 329
                 // user is not enrolled, we shouldn't have got here.
338 330
                 throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
@@ -347,7 +339,8 @@  discard block
 block discarded – undo
347 339
         }
348 340
     }
349 341
 
350
-    protected function disableU2F() {
342
+    protected function disableU2F()
343
+    {
351 344
         $database = $this->getDatabase();
352 345
         $currentUser = User::getCurrent($database);
353 346
 
@@ -381,13 +374,11 @@  discard block
 block discarded – undo
381 374
                 $tokens = $otpCredentialProvider->getTokens();
382 375
                 $this->assign('tokens', $tokens);
383 376
                 $this->setTemplate('mfa/regenScratchTokens.tpl');
384
-            }
385
-            else {
377
+            } else {
386 378
                 SessionAlert::error('Error refreshing scratch tokens - invalid credentials.');
387 379
                 $this->redirect('multiFactor');
388 380
             }
389
-        }
390
-        else {
381
+        } else {
391 382
             $this->assignCSRFToken();
392 383
 
393 384
             $this->assign('alertmessage', 'To regenerate your emergency scratch tokens, please prove you are who you say you are by providing the information below. Note that continuing will invalidate all remaining scratch tokens, and provide a set of new ones.');
@@ -425,13 +416,11 @@  discard block
 block discarded – undo
425 416
                 $otpCredentialProvider->deleteCredential($currentUser);
426 417
                 SessionAlert::success('Disabled ' . $factorType . '.');
427 418
                 $this->redirect('multiFactor');
428
-            }
429
-            else {
419
+            } else {
430 420
                 SessionAlert::error('Error disabling ' . $factorType . ' - invalid credentials.');
431 421
                 $this->redirect('multiFactor');
432 422
             }
433
-        }
434
-        else {
423
+        } else {
435 424
             if (!$otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
436 425
                 // user is not enrolled, we shouldn't have got here.
437 426
                 throw new ApplicationLogicException('User is not enrolled in the selected MFA mechanism');
Please login to merge, or discard this patch.
includes/Pages/UserAuth/PageOAuth.php 1 patch
Indentation   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -22,81 +22,81 @@
 block discarded – undo
22 22
 
23 23
 class PageOAuth extends InternalPageBase
24 24
 {
25
-    /**
26
-     * Attach entry point
27
-     *
28
-     * must be posted, or will redirect to preferences
29
-     */
30
-    protected function attach()
31
-    {
32
-        if (!WebRequest::wasPosted()) {
33
-            $this->redirect('preferences');
34
-
35
-            return;
36
-        }
37
-
38
-        $database = $this->getDatabase();
39
-
40
-        $this->validateCSRFToken();
41
-
42
-        $oauthProtocolHelper = $this->getOAuthProtocolHelper();
43
-        $user = User::getCurrent($database);
44
-        $oauth = new OAuthUserHelper($user, $database, $oauthProtocolHelper, $this->getSiteConfiguration());
45
-
46
-        try {
47
-            $authoriseUrl = $oauth->getRequestToken();
48
-            $this->redirectUrl($authoriseUrl);
49
-        }
50
-        catch (CurlException $ex) {
51
-            throw new ApplicationLogicException($ex->getMessage(), 0, $ex);
52
-        }
53
-    }
54
-
55
-    /**
56
-     * Detach account entry point
57
-     * @throws Exception
58
-     */
59
-    protected function detach()
60
-    {
61
-        if ($this->getSiteConfiguration()->getEnforceOAuth()) {
62
-            throw new AccessDeniedException($this->getSecurityManager());
63
-        }
64
-
65
-        $database = $this->getDatabase();
66
-        $user = User::getCurrent($database);
67
-        $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
68
-
69
-        try {
70
-            $oauth->refreshIdentity();
71
-        }
72
-        catch (CurlException $ex) {
73
-            // do nothing. The user's already revoked this access anyway.
74
-        }
75
-        catch (OAuthException $ex) {
76
-            // do nothing. The user's already revoked this access anyway.
77
-        }
78
-        catch (OptimisticLockFailedException $e) {
79
-            // do nothing. The user's already revoked this access anyway.
80
-        }
81
-
82
-        $oauth->detach();
83
-
84
-        // TODO: figure out why we need to force logout after a detach.
85
-        $user->setForcelogout(true);
86
-        $user->save();
87
-
88
-        // force the user to log out
89
-        Session::destroy();
90
-
91
-        $this->redirect('login');
92
-    }
93
-
94
-    /**
95
-     * Main function for this page, when no specific actions are called.
96
-     * @return void
97
-     */
98
-    protected function main()
99
-    {
100
-        $this->redirect('preferences');
101
-    }
25
+	/**
26
+	 * Attach entry point
27
+	 *
28
+	 * must be posted, or will redirect to preferences
29
+	 */
30
+	protected function attach()
31
+	{
32
+		if (!WebRequest::wasPosted()) {
33
+			$this->redirect('preferences');
34
+
35
+			return;
36
+		}
37
+
38
+		$database = $this->getDatabase();
39
+
40
+		$this->validateCSRFToken();
41
+
42
+		$oauthProtocolHelper = $this->getOAuthProtocolHelper();
43
+		$user = User::getCurrent($database);
44
+		$oauth = new OAuthUserHelper($user, $database, $oauthProtocolHelper, $this->getSiteConfiguration());
45
+
46
+		try {
47
+			$authoriseUrl = $oauth->getRequestToken();
48
+			$this->redirectUrl($authoriseUrl);
49
+		}
50
+		catch (CurlException $ex) {
51
+			throw new ApplicationLogicException($ex->getMessage(), 0, $ex);
52
+		}
53
+	}
54
+
55
+	/**
56
+	 * Detach account entry point
57
+	 * @throws Exception
58
+	 */
59
+	protected function detach()
60
+	{
61
+		if ($this->getSiteConfiguration()->getEnforceOAuth()) {
62
+			throw new AccessDeniedException($this->getSecurityManager());
63
+		}
64
+
65
+		$database = $this->getDatabase();
66
+		$user = User::getCurrent($database);
67
+		$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
68
+
69
+		try {
70
+			$oauth->refreshIdentity();
71
+		}
72
+		catch (CurlException $ex) {
73
+			// do nothing. The user's already revoked this access anyway.
74
+		}
75
+		catch (OAuthException $ex) {
76
+			// do nothing. The user's already revoked this access anyway.
77
+		}
78
+		catch (OptimisticLockFailedException $e) {
79
+			// do nothing. The user's already revoked this access anyway.
80
+		}
81
+
82
+		$oauth->detach();
83
+
84
+		// TODO: figure out why we need to force logout after a detach.
85
+		$user->setForcelogout(true);
86
+		$user->save();
87
+
88
+		// force the user to log out
89
+		Session::destroy();
90
+
91
+		$this->redirect('login');
92
+	}
93
+
94
+	/**
95
+	 * Main function for this page, when no specific actions are called.
96
+	 * @return void
97
+	 */
98
+	protected function main()
99
+	{
100
+		$this->redirect('preferences');
101
+	}
102 102
 }
Please login to merge, or discard this patch.