-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBaseMemberExtension.php
414 lines (367 loc) · 11.7 KB
/
BaseMemberExtension.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
<?php
namespace LeKoala\Base\Security;
use Exception;
use LeKoala\Base\Controllers\HasSession;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\ArrayList;
use SilverStripe\Forms\FieldList;
use SilverStripe\Security\Member;
use LeKoala\Base\Helpers\IPHelper;
use SilverStripe\Control\Director;
use SilverStripe\ORM\DataExtension;
use SilverStripe\Security\Security;
use LeKoala\CmsActions\CustomAction;
use SilverStripe\Core\Config\Config;
use SilverStripe\GraphQL\Controller;
use SilverStripe\Admin\SecurityAdmin;
use SilverStripe\Security\Permission;
use LeKoala\Base\Security\MemberAudit;
use SilverStripe\ORM\ValidationResult;
use SilverStripe\Security\LoginAttempt;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Security\IdentityStore;
use LeKoala\Base\Security\BaseAuthenticator;
use SilverStripe\Security\DefaultAdminService;
use LeKoala\CommonExtensions\ValidationStatusExtension;
use SilverStripe\Forms\GridField\GridFieldAddNewButton;
use SilverStripe\Security\MemberAuthenticator\MemberAuthenticator;
use SilverStripe\Forms\GridField\GridFieldAddExistingAutocompleter;
use SilverStripe\ORM\ValidationException;
/**
* A lot of base functionalities for your members
*
* Most group of functions are grouped within traits when possible
*
* @link https://docs.silverstripe.org/en/4/developer_guides/extending/how_tos/track_member_logins/
* @property \SilverStripe\Security\Member|\LeKoala\Base\Security\BaseMemberExtension|\LeKoala\Base\Security\TwoFactorMemberExtension $owner
* @property string $LastVisited
* @property int $NumVisit
* @method \SilverStripe\ORM\DataList|\LeKoala\Base\Security\MemberAudit[] Audits()
*/
class BaseMemberExtension extends DataExtension
{
use MasqueradeMember;
use MemberAuthenticatorExtensions;
use HasSession;
private static $db = [
'LastVisited' => 'Datetime',
'NumVisit' => 'Int',
];
private static $has_many = [
"Audits" => MemberAudit::class . ".Member",
];
/**
* @var boolean
*/
public static $do_base_member_fields_update = true;
/**
* @return string
*/
public function Fullname()
{
return trim($this->owner->FirstName . ' ' . $this->owner->Surname);
}
/**
* @return string
*/
public function getPasswordResetLink()
{
$token = $this->owner->generateAutologinTokenAndStoreHash();
return Director::absoluteURL(Security::getPasswordResetLink($this->owner, $token));
}
/**
* This is called by Member::validateCanLogin which is typically called in MemberAuthenticator::authenticate::authenticateMember
* which is used in LoginHandler::doLogin::checkLogin
*
* This means canLogIn is called before 2FA, for instance
*
* @param ValidationResult $result
* @return void
*/
public function canLogIn(ValidationResult $result)
{
// We can avoid bots by allowing to tick a box
// if ($this->owner->isLockedOut() && GoogleRecaptchaField::isSetupReady()) {
// $result->addError('There was too many failed login attempt. Please check the captcha box to try again.');
// return;
// }
// Admin can always log in
if (Permission::check('ADMIN', 'any', $this->owner)) {
return;
}
// If MemberValidationStatus extension is applied, check validation status
if ($this->owner->hasExtension(ValidationStatusExtension::class)) {
if ($this->owner->IsValidationStatusPending()) {
$result->addError(_t('BaseMemberExtension.ACCOUNT_PENDING', "Your account is currently pending"));
}
if ($this->owner->IsValidationStatusDisabled()) {
$result->addError(_t('BaseMemberExtension.ACCOUNT_DISABLED', "Your account has been disabled"));
}
}
}
public function onBeforeWrite()
{
if ($this->owner->Email) {
$this->owner->Email = trim($this->owner->Email);
}
}
/**
* @deprecated
*/
public function beforeMemberLoggedIn()
{
//
}
public function afterMemberLoggedIn()
{
$this->logVisit();
}
/**
* Called by CookieAuthenticationHandler
*/
public function memberAutoLoggedIn()
{
$this->logVisit();
}
public function beforeMemberLoggedOut($request)
{
//
}
public function afterMemberLoggedOut($request)
{
//
}
/**
* Returns the fields for the member form - used in the registration/profile module.
* It should return fields that are editable by the admin and the logged-in user.
*
* @param FieldList $fields
*/
public function updateMemberFormFields(FieldList $fields)
{
//
}
public function updateMemberPasswordField($password)
{
//
}
public function updateDateFormat($format)
{
//
}
public function updateTimeFormat($format)
{
//
}
public function updateGroups($groups)
{
//
}
/**
* @param string $password
* @param ValidationResult $valid
* @return void
*/
public function onBeforeChangePassword($password, &$valid)
{
if (!$password && $this->owner->isChanged("Password")) {
throw new ValidationException("Your password cannot be empty");
}
}
/**
* @param string $password
* @param ValidationResult $valid
* @return void
*/
public function onAfterChangePassword($password, $valid)
{
if ($valid->isValid()) {
$this->owner->audit('password_changed_success');
// Can prove useful to send custom toast message or notification
self::getSession()->set('PasswordChanged', 1);
} else {
$this->owner->audit('password_changed_error');
}
}
public function registerFailedLogin()
{
//
}
public function updateCMSFields(FieldList $fields)
{
if (!self::$do_base_member_fields_update) {
return;
}
$ctrl = Controller::curr();
$fields->makeFieldReadonly([
'FailedLoginCount',
'LastVisited',
'NumVisit',
]);
$Audits = $fields->dataFieldByName('Audits');
if ($Audits) {
if (Permission::check('ADMIN')) {
$AuditsConfig = $Audits->getConfig();
$AuditsConfig->removeComponentsByType(GridFieldAddExistingAutocompleter::class);
$AuditsConfig->removeComponentsByType(GridFieldAddNewButton::class);
} else {
$fields->removeByName('Audits');
}
}
// Some fields don't make sense upon creation
if (!$this->owner->ID) {
$fields->removeByName(
[
'FailedLoginCount',
]
);
}
// Some fields required ADMIN rights
if (!Permission::check('ADMIN')) {
$fields->removeByName('FailedLoginCount');
}
// Some things should never be shown outside of SecurityAdmin
if (get_class($ctrl) != SecurityAdmin::class && !Permission::check('ADMIN', 'any', $this->owner)) {
$fields->removeByName([
'DirectGroups',
'Permissions',
]);
}
}
public function updateCMSActions(FieldList $actions)
{
// Admin can unlock people
if (Permission::check('ADMIN') && $this->owner->isLockedOut()) {
$actions->push($doUnlock = new CustomAction('doUnlock', 'Unlock'));
}
// Login as (but cannot login as yourself :-) )
if (Permission::check('ADMIN') && $this->owner->ID != Member::currentUserID()) {
// check config flag
$login_as_only_default_admin = $this->owner->config()->login_as_only_default_admin;
$canLoginAs = false;
if ($login_as_only_default_admin) {
try {
$defaultAdmin = DefaultAdminService::getDefaultAdminUsername();
if ($defaultAdmin == Security::getCurrentUser()->Email) {
$canLoginAs = true;
}
} catch (Exception $ex) {
}
} else {
$canLoginAs = true;
}
if ($canLoginAs) {
$actions->push($doLoginAs = new CustomAction('doLoginAs', 'Login as'));
}
}
}
public function doUnlock()
{
if (!$this->owner->isLockedOut()) {
return _t('BaseMemberExtension.MEMBER_NOT_LOCKED', 'Member is not locked');
}
$lastSuccess = LoginAttempt::get()->filter($filter = array(
'MemberID' => $this->owner->ID
))->sort('Created', 'DESC')->filter('Status', 'Success')->first();
$sql = 'DELETE FROM LoginAttempt WHERE MemberID = ? AND Status = ?';
$params = [
$this->owner->ID,
'Failure'
];
if ($lastSuccess) {
$sql .= ' AND ID > ?';
$params[] = $lastSuccess->ID;
}
// Cleanup failure attempt
DB::prepared_query($sql, $params);
try {
$this->owner->LockedOutUntil = null;
$this->owner->write();
$msg = _t('BaseMemberExtension.MEMBER_UNLOCKED', 'Member unlocked');
} catch (Exception $ex) {
$msg = $ex->getMessage();
}
return $msg;
}
/**
* @return boolean
*/
public function NotMe()
{
return $this->owner->ID !== Member::currentUserID();
}
/**
* @return boolean
*/
public function IsAdmin()
{
return Permission::check('CMS_ACCESS', 'any', $this->owner);
}
/**
* Force member login
* (since Member::login has been deprecated but is really useful)
*
* @param HTTPRequest $request
* @param boolean $remember
* @return void
*/
public function forceLogin($request = null, $remember = false)
{
if ($request === null) {
$request = Controller::curr()->getRequest();
}
Security::setCurrentUser($this->owner);
$identityStore = Injector::inst()->get(IdentityStore::class);
return $identityStore->logIn($this->owner, $remember, $request);
}
/**
* @param string $event
* @param string|array $data
* @return int
*/
public function audit($event, $data = null)
{
$r = new MemberAudit;
$r->MemberID = $this->owner->ID;
$r->Event = $event;
if ($data) {
$r->AuditData = $data;
}
return $r->write();
}
protected function logVisit()
{
if (!Security::database_is_ready()) {
return;
}
DB::query(sprintf(
'UPDATE "Member" SET "LastVisited" = %s, "NumVisit" = "NumVisit" + 1 WHERE "ID" = %d',
DB::get_conn()->now(),
$this->owner->ID
));
}
/**
* @return array
*/
public static function getMembersFromSecurityGroupsIDs()
{
$sql = 'SELECT DISTINCT MemberID FROM Group_Members INNER JOIN Permission ON Permission.GroupID = Group_Members.GroupID WHERE Code LIKE \'CMS_%\' OR Code = \'ADMIN\'';
return DB::query($sql)->column();
}
/**
* @param array $extraIDs
* @return Member[]|ArrayList
*/
public static function getMembersFromSecurityGroups($extraIDs = [])
{
$ids = array_merge(self::getMembersFromSecurityGroupsIDs(), $extraIDs);
return Member::get()->filter('ID', $ids);
}
/**
* @return string
*/
public function DirectGroupsList()
{
return implode(',', $this->owner->DirectGroups()->column('Title'));
}
}