-
Notifications
You must be signed in to change notification settings - Fork 8
/
ExpireUsers.php
249 lines (220 loc) · 7.32 KB
/
ExpireUsers.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
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019 Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\UserRetention\BackgroundJob;
use OC\Authentication\Token\DefaultToken;
use OC\Authentication\Token\Manager;
use OC\BackgroundJob\TimedJob;
use OCA\Guests\UserBackend;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\ILogger;
use OCP\IServerContainer;
use OCP\IUser;
use OCP\IUserManager;
use OCP\LDAP\IDeletionFlagSupport;
use OCP\LDAP\ILDAPProvider;
use Psr\Log\LoggerInterface;
/**
* Class ExpireUsers
*
* @package OCA\UserRetention\BackgroundJob
*/
class ExpireUsers extends TimedJob {
/** @var IConfig */
protected $config;
/** @var IUserManager */
protected $userManager;
/** @var IGroupManager */
protected $groupManager;
/** @var ITimeFactory */
protected $timeFactory;
/** @var LoggerInterface */
protected $logger;
/** @var IServerContainer */
private $server;
protected $userMaxLastLogin = 0;
protected $guestMaxLastLogin = 0;
protected $excludedGroups = [];
/** @var bool*/
protected $keepUsersWithoutLogin = true;
public function __construct(
IConfig $config,
IUserManager $userManager,
IGroupManager $groupManager,
ITimeFactory $timeFactory,
IServerContainer $server,
LoggerInterface $logger
) {
$this->config = $config;
$this->userManager = $userManager;
$this->groupManager = $groupManager;
$this->timeFactory = $timeFactory;
$this->server = $server;
$this->logger = $logger;
// Every day
$this->setInterval(60 * 60 * 24);
}
protected function run($argument): void {
$now = new \DateTimeImmutable();
$userDays = (int) $this->config->getAppValue('user_retention', 'user_days', 0);
if ($userDays > 0) {
$userMaxLastLogin = $now->sub(new \DateInterval('P' . $userDays . 'D'));
$this->userMaxLastLogin = $userMaxLastLogin->getTimestamp();
$this->logger->debug('Account retention with last login before ' . $userMaxLastLogin->format(\DateTimeInterface::ATOM));
} else {
$this->logger->debug('Account retention is disabled');
}
$guestDays = (int) $this->config->getAppValue('user_retention', 'guest_days', 0);
if ($guestDays > 0) {
$guestMaxLastLogin = $now->sub(new \DateInterval('P' . $guestDays . 'D'));
$this->guestMaxLastLogin = $guestMaxLastLogin->getTimestamp();
$this->logger->debug('Guest account retention with last login before ' . $guestMaxLastLogin->format(\DateTimeInterface::ATOM));
} else {
$this->logger->debug('Guest account retention is disabled');
}
$this->keepUsersWithoutLogin = $this->config->getAppValue('user_retention', 'keep_users_without_login', 'yes') === 'yes';
$excludedGroups = $this->config->getAppValue('user_retention', 'excluded_groups', '["admin"]');
$excludedGroups = json_decode($excludedGroups, true);
$this->excludedGroups = \is_array($excludedGroups) ? $excludedGroups : [];
$handler = function(IUser $user) {
$maxLastLogin = $this->userMaxLastLogin;
if ($user->getBackend() instanceof UserBackend) {
$maxLastLogin = $this->guestMaxLastLogin;
}
if ($this->shouldExpireUser($user, $maxLastLogin)) {
$this->logger->debug('Attempting to delete account: {user}', [
'user' => $user->getUID(),
]);
if($user->getBackendClassName() === 'LDAP' && !$this->prepareLDAPUser($user)) {
$this->logger->warning('Expired LDAP account ' . $user->getUID() . ' was not deleted');
return;
}
if ($user->delete()) {
$this->logger->info('Account deleted: ' . $user->getUID());
} else {
$this->logger->warning('Expired account ' . $user->getUID() . ' was not deleted');
}
}
};
if ($this->keepUsersWithoutLogin) {
$this->userManager->callForSeenUsers($handler);
} else {
$this->userManager->callForAllUsers($handler);
}
}
protected function shouldExpireUser(IUser $user, int $maxLastLogin): bool {
if (!$maxLastLogin) {
return false;
}
$createdAt = $this->getCreatedAt($user);
if ($createdAt === 0) {
// Set "now" as created at timestamp for the user.
$this->setCreatedAt($user, $this->timeFactory->getTime());
$this->logger->debug('New user, saving discovery time: {user}', [
'user' => $user->getUID(),
]);
return false;
}
if ($this->keepUsersWithoutLogin && $user->getLastLogin() === 0) {
// no need for deletion when no user dir was initialized
$this->logger->debug('Skipping user that never logged in: {user}', [
'user' => $user->getUID(),
]);
return false;
}
if ($maxLastLogin < $user->getLastLogin()) {
$this->logger->debug('Skipping user because of login time: {user}', [
'user' => $user->getUID(),
]);
return false;
}
if (!$this->allAuthTokensInactive($user, $maxLastLogin)) {
$this->logger->debug('Skipping user because of auth token time: {user}', [
'user' => $user->getUID(),
]);
return false;
}
if (!$this->keepUsersWithoutLogin && $maxLastLogin < $createdAt) {
$this->logger->debug('Skipping user because of discovery time: {user}', [
'user' => $user->getUID(),
]);
return false;
}
if (empty($this->excludedGroups)) {
return true;
}
$userGroups = $this->groupManager->getUserGroupIds($user);
$excludedGroups = array_intersect($userGroups, $this->excludedGroups);
if (!empty($excludedGroups)) {
$this->logger->debug('Skipping user because of excluded groups ({groups}): {user}', [
'user' => $user->getUID(),
'groups' => implode(',', $excludedGroups),
]);
return false;
}
return true;
}
protected function allAuthTokensInactive(IUser $user, int $maxLastActivity): bool {
/** @var Manager $authTokenManager */
$authTokenManager = $this->server->get(Manager::class);
/** @var DefaultToken[] $tokens */
$tokens = $authTokenManager->getTokenByUser($user->getUID());
foreach ($tokens as $token) {
if ($maxLastActivity < $token->getLastActivity()) {
return false;
}
}
return true;
}
protected function getCreatedAt(IUser $user): int {
return (int) $this->config->getUserValue(
$user->getUID(),
'user_retention',
'user_created_at',
0
);
}
protected function setCreatedAt(IUser $user, int $time): void {
$this->config->setUserValue(
$user->getUID(),
'user_retention',
'user_created_at',
$time
);
}
protected function prepareLDAPUser(IUser $user): bool {
try {
$ldapProvider = $this->server->get(ILDAPProvider::class);
if($ldapProvider instanceof IDeletionFlagSupport) {
$ldapProvider->flagRecord($user->getUID());
$this->logger->info('Marking LDAP user as deleted: ' . $user->getUID());
}
} catch (\Exception $e) {
$this->logger->warning($e->getMessage(), [
'exception' => $e,
]);
return false;
}
return true;
}
}