/
MethodController.php
490 lines (401 loc) · 15.7 KB
/
MethodController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
<?php
/**
* @package Joomla.Administrator
* @subpackage com_users
*
* @copyright (C) 2022 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\Component\Users\Administrator\Controller;
use Joomla\CMS\Application\CMSApplication;
use Joomla\CMS\Event\MultiFactor\NotifyActionLog;
use Joomla\CMS\Event\MultiFactor\SaveSetup;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\BaseController as BaseControllerAlias;
use Joomla\CMS\MVC\Factory\MVCFactoryInterface;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\User\User;
use Joomla\CMS\User\UserFactoryAwareInterface;
use Joomla\CMS\User\UserFactoryAwareTrait;
use Joomla\CMS\User\UserHelper;
use Joomla\Component\Users\Administrator\Helper\Mfa as MfaHelper;
use Joomla\Component\Users\Administrator\Model\BackupcodesModel;
use Joomla\Component\Users\Administrator\Model\MethodModel;
use Joomla\Component\Users\Administrator\Table\MfaTable;
use Joomla\Input\Input;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/**
* Multi-factor Authentication method controller
*
* @since 4.2.0
*/
class MethodController extends BaseControllerAlias implements UserFactoryAwareInterface
{
use UserFactoryAwareTrait;
/**
* Public constructor
*
* @param array $config Plugin configuration
* @param MVCFactoryInterface|null $factory MVC Factory for the com_users component
* @param CMSApplication|null $app CMS application object
* @param Input|null $input Joomla CMS input object
*
* @since 4.2.0
*/
public function __construct(array $config = [], MVCFactoryInterface $factory = null, ?CMSApplication $app = null, ?Input $input = null)
{
// We have to tell Joomla what is the name of the view, otherwise it defaults to the name of the *component*.
$config['default_view'] = 'method';
$config['default_task'] = 'add';
parent::__construct($config, $factory, $app, $input);
}
/**
* Execute a task by triggering a Method in the derived class.
*
* @param string $task The task to perform. If no matching task is found, the '__default' task is executed, if
* defined.
*
* @return mixed The value returned by the called Method.
*
* @throws \Exception
* @since 4.2.0
*/
public function execute($task)
{
if (empty($task) || $task === 'display') {
$task = 'add';
}
return parent::execute($task);
}
/**
* Add a new MFA Method
*
* @param boolean $cachable Ignored. This page is never cached.
* @param boolean|array $urlparams Ignored. This page is never cached.
*
* @return void
* @throws \Exception
* @since 4.2.0
*/
public function add($cachable = false, $urlparams = []): void
{
$this->assertLoggedInUser();
// Make sure I am allowed to edit the specified user
$userId = $this->input->getInt('user_id', null);
$user = $this->getUserFactory()->loadUserById($userId);
$this->assertCanEdit($user);
// Also make sure the Method really does exist
$method = $this->input->getCmd('method');
$this->assertMethodExists($method);
/** @var MethodModel $model */
$model = $this->getModel('Method');
$model->setState('method', $method);
// Pass the return URL to the view
$returnURL = $this->input->getBase64('returnurl');
$viewLayout = $this->input->get('layout', 'default', 'string');
$view = $this->getView('Method', 'html');
$view->setLayout($viewLayout);
$view->returnURL = $returnURL;
$view->user = $user;
$view->document = $this->app->getDocument();
$view->setModel($model, true);
$event = new NotifyActionLog('onComUsersControllerMethodBeforeAdd', [$user, $method]);
$this->app->getDispatcher()->dispatch($event->getName(), $event);
$view->display();
}
/**
* Edit an existing MFA Method
*
* @param boolean $cachable Ignored. This page is never cached.
* @param boolean|array $urlparams Ignored. This page is never cached.
*
* @return void
* @throws \Exception
* @since 4.2.0
*/
public function edit($cachable = false, $urlparams = []): void
{
$this->assertLoggedInUser();
// Make sure I am allowed to edit the specified user
$userId = $this->input->getInt('user_id', null);
$user = $this->getUserFactory()->loadUserById($userId);
$this->assertCanEdit($user);
// Also make sure the Method really does exist
$id = $this->input->getInt('id');
$record = $this->assertValidRecordId($id, $user);
if ($id <= 0) {
throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403);
}
/** @var MethodModel $model */
$model = $this->getModel('Method');
$model->setState('id', $id);
// Pass the return URL to the view
$returnURL = $this->input->getBase64('returnurl');
$viewLayout = $this->input->get('layout', 'default', 'string');
$view = $this->getView('Method', 'html');
$view->setLayout($viewLayout);
$view->returnURL = $returnURL;
$view->user = $user;
$view->document = $this->app->getDocument();
$view->setModel($model, true);
$event = new NotifyActionLog('onComUsersControllerMethodBeforeEdit', [$id, $user]);
$this->app->getDispatcher()->dispatch($event->getName(), $event);
$view->display();
}
/**
* Regenerate backup codes
*
* @param boolean $cachable Ignored. This page is never cached.
* @param boolean|array $urlparams Ignored. This page is never cached.
*
* @return void
* @throws \Exception
* @since 4.2.0
*/
public function regenerateBackupCodes($cachable = false, $urlparams = []): void
{
$this->assertLoggedInUser();
$this->checkToken($this->input->getMethod());
// Make sure I am allowed to edit the specified user
$userId = $this->input->getInt('user_id', null);
$user = $this->getUserFactory()->loadUserById($userId);
$this->assertCanEdit($user);
/** @var BackupcodesModel $model */
$model = $this->getModel('Backupcodes');
$model->regenerateBackupCodes($user);
$backupCodesRecord = $model->getBackupCodesRecord($user);
// Redirect
$redirectUrl = 'index.php?option=com_users&task=method.edit&user_id=' . $userId . '&id=' . $backupCodesRecord->id;
$returnURL = $this->input->getBase64('returnurl');
if (!empty($returnURL) && Uri::isInternal(base64_decode($returnURL))) {
$redirectUrl .= '&returnurl=' . $returnURL;
}
$this->setRedirect(Route::_($redirectUrl, false));
$event = new NotifyActionLog('onComUsersControllerMethodAfterRegenerateBackupCodes');
$this->app->getDispatcher()->dispatch($event->getName(), $event);
}
/**
* Delete an existing MFA Method
*
* @param boolean $cachable Ignored. This page is never cached.
* @param boolean|array $urlparams Ignored. This page is never cached.
*
* @return void
* @since 4.2.0
*/
public function delete($cachable = false, $urlparams = []): void
{
$this->assertLoggedInUser();
$this->checkToken($this->input->getMethod());
// Make sure I am allowed to edit the specified user
$userId = $this->input->getInt('user_id', null);
$user = $this->getUserFactory()->loadUserById($userId);
$this->assertCanDelete($user);
// Also make sure the Method really does exist
$id = $this->input->getInt('id');
$record = $this->assertValidRecordId($id, $user);
if ($id <= 0) {
throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403);
}
$type = null;
$message = null;
$event = new NotifyActionLog('onComUsersControllerMethodBeforeDelete', [$id, $user]);
$this->app->getDispatcher()->dispatch($event->getName(), $event);
try {
$record->delete();
} catch (\Exception $e) {
$message = $e->getMessage();
$type = 'error';
}
// Redirect
$url = Route::_('index.php?option=com_users&task=methods.display&user_id=' . $userId, false);
$returnURL = $this->input->getBase64('returnurl');
if (!empty($returnURL) && Uri::isInternal(base64_decode($returnURL))) {
$url = base64_decode($returnURL);
}
$this->setRedirect($url, $message, $type);
}
/**
* Save the MFA Method
*
* @param boolean $cachable Ignored. This page is never cached.
* @param boolean|array $urlparams Ignored. This page is never cached.
*
* @return void
* @since 4.2.0
*/
public function save($cachable = false, $urlparams = []): void
{
$this->assertLoggedInUser();
$this->checkToken($this->input->getMethod());
// Make sure I am allowed to edit the specified user
$userId = $this->input->getInt('user_id', null);
$user = $this->getUserFactory()->loadUserById($userId);
$this->assertCanEdit($user);
// Redirect
$url = Route::_('index.php?option=com_users&task=methods.display&user_id=' . $userId, false);
$returnURL = $this->input->getBase64('returnurl');
if (!empty($returnURL) && Uri::isInternal(base64_decode($returnURL))) {
$url = base64_decode($returnURL);
}
// The record must either be new (ID zero) or exist
$id = $this->input->getInt('id', 0);
$record = $this->assertValidRecordId($id, $user);
// If it's a new record we need to read the Method from the request and update the (not yet created) record.
if ($record->id == 0) {
$methodName = $this->input->getCmd('method');
$this->assertMethodExists($methodName);
$record->method = $methodName;
}
/** @var MethodModel $model */
$model = $this->getModel('Method');
// Ask the plugin to validate the input by calling onUserMultifactorSaveSetup
$result = [];
$input = $this->app->getInput();
$event = new NotifyActionLog('onComUsersControllerMethodBeforeSave', [$id, $user]);
$this->app->getDispatcher()->dispatch($event->getName(), $event);
try {
$event = new SaveSetup($record, $input);
$pluginResults = $this->app
->getDispatcher()
->dispatch($event->getName(), $event)
->getArgument('result', []);
foreach ($pluginResults as $pluginResult) {
$result = array_merge($result, $pluginResult);
}
} catch (\RuntimeException $e) {
// Go back to the edit page
$nonSefUrl = 'index.php?option=com_users&task=method.';
if ($id) {
$nonSefUrl .= 'edit&id=' . (int) $id;
} else {
$nonSefUrl .= 'add&method=' . $record->method;
}
$nonSefUrl .= '&user_id=' . $userId;
if (!empty($returnURL)) {
$nonSefUrl .= '&returnurl=' . urlencode($returnURL);
}
$url = Route::_($nonSefUrl, false);
$this->setRedirect($url, $e->getMessage(), 'error');
return;
}
// Update the record's options with the plugin response
$title = $this->input->getString('title', null);
$title = trim($title);
if (empty($title)) {
$method = $model->getMethod($record->method);
$title = $method['display'];
}
// Update the record's "default" flag
$default = $this->input->getBool('default', false);
$record->title = $title;
$record->options = $result;
$record->default = $default ? 1 : 0;
// Ask the model to save the record
$saved = $record->store();
if (!$saved) {
// Go back to the edit page
$nonSefUrl = 'index.php?option=com_users&task=method.';
if ($id) {
$nonSefUrl .= 'edit&id=' . (int) $id;
} else {
$nonSefUrl .= 'add';
}
$nonSefUrl .= '&user_id=' . $userId;
if (!empty($returnURL)) {
$nonSefUrl .= '&returnurl=' . urlencode($returnURL);
}
$url = Route::_($nonSefUrl, false);
$this->setRedirect($url, $record->getError(), 'error');
return;
}
// Method updated, destroy other active sessions
UserHelper::destroyUserSessions($userId, true);
$this->setRedirect($url);
}
/**
* Assert that the provided ID is a valid record identified for the given user
*
* @param int $id Record ID to check
* @param User|null $user User record. Null to use current user.
*
* @return MfaTable The loaded record
* @since 4.2.0
*/
private function assertValidRecordId($id, ?User $user = null): MfaTable
{
if (\is_null($user)) {
$user = $this->app->getIdentity() ?: $this->getUserFactory()->loadUserById(0);
}
/** @var MethodModel $model */
$model = $this->getModel('Method');
$model->setState('id', $id);
$record = $model->getRecord($user);
if (\is_null($record) || ($record->id != $id) || ($record->user_id != $user->id)) {
throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403);
}
return $record;
}
/**
* Assert that the user can add / edit MFA methods.
*
* @param User|null $user User record. Null to use current user.
*
* @return void
* @throws \RuntimeException|\Exception
* @since 4.2.0
*/
private function assertCanEdit(?User $user = null): void
{
if (!MfaHelper::canAddEditMethod($user)) {
throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403);
}
}
/**
* Assert that the user can delete MFA records / disable MFA.
*
* @param User|null $user User record. Null to use current user.
*
* @return void
* @throws \RuntimeException|\Exception
* @since 4.2.0
*/
private function assertCanDelete(?User $user = null): void
{
if (!MfaHelper::canDeleteMethod($user)) {
throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403);
}
}
/**
* Assert that the specified MFA Method exists, is activated and enabled for the current user
*
* @param string|null $method The Method to check
*
* @return void
* @since 4.2.0
*/
private function assertMethodExists(?string $method): void
{
/** @var MethodModel $model */
$model = $this->getModel('Method');
if (empty($method) || !$model->methodExists($method)) {
throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403);
}
}
/**
* Assert that there is a logged in user.
*
* @return void
* @since 4.2.0
*/
private function assertLoggedInUser(): void
{
$user = $this->app->getIdentity() ?: $this->getUserFactory()->loadUserById(0);
if ($user->guest) {
throw new \RuntimeException(Text::_('JERROR_ALERTNOAUTHOR'), 403);
}
}
}