-
Notifications
You must be signed in to change notification settings - Fork 25
/
AdminRegistrationController.php
280 lines (240 loc) · 9.44 KB
/
AdminRegistrationController.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
<?php
declare(strict_types=1);
namespace SilverStripe\MFA\Controller;
use Psr\Log\LoggerInterface;
use SilverStripe\Admin\LeftAndMain;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\Middleware\HTTPCacheControlMiddleware;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\MFA\Extension\MemberExtension;
use SilverStripe\MFA\RequestHandler\BaseHandlerTrait;
use SilverStripe\MFA\RequestHandler\RegistrationHandlerTrait;
use SilverStripe\MFA\Service\MethodRegistry;
use SilverStripe\MFA\Service\RegisteredMethodManager;
use SilverStripe\MFA\State\AvailableMethodDetailsInterface;
use SilverStripe\ORM\ValidationException;
use SilverStripe\Security\Member;
use SilverStripe\Security\Security;
use SilverStripe\Security\SecurityToken;
/**
* This controller handles actions that a user may perform on MFA methods registered on their own account while logged
* in. This includes deleting methods, registering new methods and replacing (re-registering) existing methods.
*/
class AdminRegistrationController extends LeftAndMain
{
use RegistrationHandlerTrait;
use BaseHandlerTrait;
private static $url_segment = 'mfa';
private static $ignore_menuitem = true;
private static $url_handlers = [
'GET register/$Method' => 'startRegistration',
'POST register/$Method' => 'finishRegistration',
'DELETE method/$Method' => 'removeRegisteredMethod',
'PUT method/$Method/default' => 'setDefaultRegisteredMethod',
];
private static $allowed_actions = [
'startRegistration',
'finishRegistration',
'removeRegisteredMethod',
'setDefaultRegisteredMethod',
];
private static $required_permission_codes = false;
private static $dependencies = [
'Logger' => '%$' . LoggerInterface::class . '.mfa',
];
/**
* @var LoggerInterface
*/
protected $logger;
/**
* Start a registration for a method on the currently logged in user
*
* @param HTTPRequest $request
* @return HTTPResponse
*/
public function startRegistration(HTTPRequest $request): HTTPResponse
{
// Prevent caching of response
HTTPCacheControlMiddleware::singleton()->disableCache(true);
// Create a fresh store from the current logged in user
$member = Security::getCurrentUser();
$store = $this->createStore($member);
if (!$this->getSudoModeService()->check($request->getSession())) {
return $this->jsonResponse(
['errors' => [_t(__CLASS__ . '.INVALID_SESSION', 'Invalid session. Please refresh and try again.')]],
400
);
}
// Get the specified method
$method = MethodRegistry::singleton()->getMethodByURLSegment($request->param('Method'));
if (!$method) {
return $this->jsonResponse(
['errors' => [_t(__CLASS__ . '.INVALID_METHOD', 'No such method is available')]],
400
);
}
$response = $this->createStartRegistrationResponse($store, $method, true);
$store->save($request);
return $response;
}
/**
* Complete a registration for a method for the currently logged in user
*
* @param HTTPRequest $request
* @return HTTPResponse
*/
public function finishRegistration(HTTPRequest $request): HTTPResponse
{
$store = $this->getStore();
if (!$store || !$this->getSudoModeService()->check($request->getSession())) {
return $this->jsonResponse(
['errors' => [_t(__CLASS__ . '.INVALID_SESSION', 'Invalid session. Please refresh and try again.')]],
400
);
}
$method = MethodRegistry::singleton()->getMethodByURLSegment($request->param('Method'));
if (!$method) {
return $this->jsonResponse(
['errors' => [_t(__CLASS__ . '.INVALID_METHOD', 'No such method is available')]],
400
);
}
$result = $this->completeRegistrationRequest($store, $method, $request);
if (!$result->isSuccessful()) {
return $this->jsonResponse(['errors' => [$result->getMessage()]], 400);
}
$store::clear($request);
return $this->jsonResponse([
'success' => true,
'method' => $result->getContext()['registeredMethod'] ?? null,
], 201);
}
/**
* Remove the specified method from the currently logged in user
*
* @param HTTPRequest $request
* @return HTTPResponse
*/
public function removeRegisteredMethod(HTTPRequest $request): HTTPResponse
{
// Ensure CSRF protection
if (!SecurityToken::inst()->checkRequest($request)) {
return $this->jsonResponse(
['errors' => [_t(__CLASS__ . '.CSRF_FAILURE', 'Request timed out, please try again')]],
400
);
}
// Get the specified method
$methodRegistry = MethodRegistry::singleton();
$specifiedMethod = $request->param('Method');
if (!$specifiedMethod || !($method = $methodRegistry->getMethodByURLSegment($specifiedMethod))) {
return $this->jsonResponse(
['errors' => [_t(__CLASS__ . '.INVALID_METHOD', 'No such method is available')]],
400
);
}
// Remove the method from the user
$member = Security::getCurrentUser();
$registeredMethodManager = RegisteredMethodManager::singleton();
$result = $registeredMethodManager->deleteFromMember($member, $method);
if (!$result) {
return $this->jsonResponse(
['errors' => [_t(
__CLASS__ . '.COULD_NOT_DELETE',
'Could not delete the specified method from the user'
)]],
400
);
}
$backupMethod = $methodRegistry->getBackupMethod();
return $this->jsonResponse([
'success' => true,
'availableMethod' => Injector::inst()->create(AvailableMethodDetailsInterface::class, $method),
// Indicate if the user has a backup method registered to keep the UI up to date
// Deleting methods may remove the backup method if there are no other methods remaining.
'hasBackupMethod' => $backupMethod && $registeredMethodManager->getFromMember(
$member,
$backupMethod
),
]);
}
/**
* Set the default registered method for the current user to that provided by the MethodID parameter.
*
* @param HTTPRequest $request
* @return HTTPResponse
*/
public function setDefaultRegisteredMethod(HTTPRequest $request): HTTPResponse
{
// Ensure CSRF and sudo-mode protection
if (
!SecurityToken::inst()->checkRequest($request)
|| !$this->getSudoModeService()->check($request->getSession())
) {
return $this->jsonResponse(
['errors' => [_t(__CLASS__ . '.CSRF_FAILURE', 'Request timed out, please try again')]],
400
);
}
// Get the specified method
$methodRegistry = MethodRegistry::singleton();
$specifiedMethod = $request->param('Method');
if (!$specifiedMethod || !($method = $methodRegistry->getMethodByURLSegment($specifiedMethod))) {
return $this->jsonResponse(
['errors' => [_t(__CLASS__ . '.INVALID_METHOD', 'No such method is available')]],
400
);
}
// Set the method as the default
/** @var Member&MemberExtension $member */
$member = Security::getCurrentUser();
$registeredMethodManager = RegisteredMethodManager::singleton();
$registeredMethod = $registeredMethodManager->getFromMember($member, $method);
if (!$registeredMethod) {
return $this->jsonResponse(
['errors' => [_t(__CLASS__ . '.INVALID_REGISTERED_METHOD', 'No such registered method is available')]],
400
);
}
try {
$member->setDefaultRegisteredMethod($registeredMethod);
$member->write();
} catch (ValidationException $exception) {
$this->logger->debug(
'Failed to set default registered method for user #' . $member->ID . ' to ' . $specifiedMethod
. ': ' . $exception->getMessage()
);
return $this->jsonResponse(
['errors' => [_t(
__CLASS__ . '.COULD_NOT_SET_DEFAULT',
'Could not set the default method for the user'
)]],
400
);
}
return $this->jsonResponse(['success' => true]);
}
/**
* Respond with the given array as a JSON response
*
* @param array $response
* @param int $code The HTTP response code to set on the response
* @return HTTPResponse
*/
protected function jsonResponse(array $response, int $code = 200): HTTPResponse
{
return HTTPResponse::create(json_encode($response))
->addHeader('Content-Type', 'application/json')
->setStatusCode($code);
}
/**
* @param LoggerInterface|null $logger
* @return $this
*/
public function setLogger(?LoggerInterface $logger): AdminRegistrationController
{
$this->logger = $logger;
return $this;
}
}