-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathBackend.php
323 lines (287 loc) · 10.7 KB
/
Backend.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
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\UserOIDC\User;
use OCA\UserOIDC\AppInfo\Application;
use OCA\UserOIDC\Controller\LoginController;
use OCA\UserOIDC\Db\Provider;
use OCA\UserOIDC\Db\ProviderMapper;
use OCA\UserOIDC\Db\UserMapper;
use OCA\UserOIDC\Event\TokenValidatedEvent;
use OCA\UserOIDC\Service\DiscoveryService;
use OCA\UserOIDC\Service\LdapService;
use OCA\UserOIDC\Service\ProviderService;
use OCA\UserOIDC\User\Validator\SelfEncodedValidator;
use OCA\UserOIDC\User\Validator\UserInfoValidator;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\Authentication\IApacheBackend;
use OCP\DB\Exception;
use OCP\EventDispatcher\GenericEvent;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\IConfig;
use OCP\IRequest;
use OCP\ISession;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use OCP\User\Backend\ABackend;
use OCP\User\Backend\ICountUsersBackend;
use OCP\User\Backend\ICustomLogout;
use OCP\User\Backend\IGetDisplayNameBackend;
use OCP\User\Backend\IPasswordConfirmationBackend;
use Psr\Log\LoggerInterface;
class Backend extends ABackend implements IPasswordConfirmationBackend, IGetDisplayNameBackend, IApacheBackend, ICustomLogout, ICountUsersBackend {
private $tokenValidators = [
SelfEncodedValidator::class,
UserInfoValidator::class,
];
public function __construct(
private IConfig $config,
private UserMapper $userMapper,
private LoggerInterface $logger,
private IRequest $request,
private ISession $session,
private IURLGenerator $urlGenerator,
private IEventDispatcher $eventDispatcher,
private DiscoveryService $discoveryService,
private ProviderMapper $providerMapper,
private ProviderService $providerService,
private LdapService $ldapService,
private IUserManager $userManager,
) {
}
public function getBackendName(): string {
return Application::APP_ID;
}
public function countUsers(): int {
$uids = $this->getUsers();
return count($uids);
}
public function deleteUser($uid): bool {
try {
$user = $this->userMapper->getUser($uid);
$this->userMapper->delete($user);
return true;
} catch (Exception $e) {
$this->logger->error('Failed to delete user', [ 'exception' => $e ]);
return false;
}
}
public function getUsers($search = '', $limit = null, $offset = null) {
return array_map(function ($user) {
return $user->getUserId();
}, $this->userMapper->find($search, $limit, $offset));
}
public function userExists($uid): bool {
return $this->userMapper->userExists($uid);
}
public function getDisplayName($uid): string {
try {
$user = $this->userMapper->getUser($uid);
} catch (DoesNotExistException $e) {
return $uid;
}
return $user->getDisplayName();
}
public function getDisplayNames($search = '', $limit = null, $offset = null): array {
return $this->userMapper->findDisplayNames($search, $limit, $offset);
}
public function hasUserListings(): bool {
return true;
}
public function canConfirmPassword(string $uid): bool {
return false;
}
/**
* As session cannot be injected in the constructor here, we inject it later
*
* @param ISession $session
* @return void
*/
public function injectSession(ISession $session): void {
$this->session = $session;
}
/**
* In case the user has been authenticated by Apache true is returned.
*
* @return bool whether Apache reports a user as currently logged in.
* @since 6.0.0
*/
public function isSessionActive(): bool {
// if this returns true, getCurrentUserId is called
// not sure if we should rather to the validation in here as otherwise it might fail for other backends or bave other side effects
$headerToken = $this->request->getHeader(Application::OIDC_API_REQ_HEADER);
// session is active if we have a bearer token (API request) OR if we logged in via user_oidc (we have a provider ID in the session)
return $headerToken !== '' || $this->session->get(LoginController::PROVIDERID) !== null;
}
/**
* {@inheritdoc}
*/
public function getLogoutUrl(): string {
return $this->urlGenerator->linkToRouteAbsolute(
'user_oidc.login.singleLogoutService',
[
'requesttoken' => \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue(),
]
);
}
/**
* Return the id of the current user
* @return string
* @since 6.0.0
*/
public function getCurrentUserId(): string {
$providers = $this->providerMapper->getProviders();
if (count($providers) === 0) {
$this->logger->debug('no OIDC providers');
return '';
}
// get the bearer token from headers
$headerToken = $this->request->getHeader(Application::OIDC_API_REQ_HEADER);
$headerToken = preg_replace('/^bearer\s+/i', '', $headerToken);
if ($headerToken === '') {
$this->logger->debug('No Bearer token');
return '';
}
$oidcSystemConfig = $this->config->getSystemValue('user_oidc', []);
// check if we should use UserInfoValidator (default is false)
if (!isset($oidcSystemConfig['userinfo_bearer_validation']) || !$oidcSystemConfig['userinfo_bearer_validation']) {
if (($key = array_search(UserInfoValidator::class, $this->tokenValidators)) !== false) {
unset($this->tokenValidators[$key]);
}
}
// check if we should use SelfEncodedValidator (default is true)
if (isset($oidcSystemConfig['selfencoded_bearer_validation']) && !$oidcSystemConfig['selfencoded_bearer_validation']) {
if (($key = array_search(SelfEncodedValidator::class, $this->tokenValidators)) !== false) {
unset($this->tokenValidators[$key]);
}
}
$autoProvisionAllowed = (!isset($oidcSystemConfig['auto_provision']) || $oidcSystemConfig['auto_provision']);
// try to validate with all providers
foreach ($providers as $provider) {
if ($this->providerService->getSetting($provider->getId(), ProviderService::SETTING_CHECK_BEARER, '0') === '1') {
// find user id through different token validation methods
foreach ($this->tokenValidators as $validatorClass) {
$validator = \OC::$server->get($validatorClass);
$tokenUserId = $validator->isValidBearerToken($provider, $headerToken);
if ($tokenUserId) {
$this->logger->debug(
'Token validated with ' . $validatorClass . ' by provider: ' . $provider->getId()
. ' (' . $provider->getIdentifier() . ')'
);
$discovery = $this->discoveryService->obtainDiscovery($provider);
$this->eventDispatcher->dispatchTyped(new TokenValidatedEvent(['token' => $headerToken], $provider, $discovery));
if ($autoProvisionAllowed) {
// look for user in other backends
if (!$this->userManager->userExists($tokenUserId)) {
$this->userManager->search($tokenUserId);
$this->ldapService->syncUser($tokenUserId);
}
$userFromOtherBackend = $this->userManager->get($tokenUserId);
if ($userFromOtherBackend !== null && $this->ldapService->isLdapDeletedUser($userFromOtherBackend)) {
$userFromOtherBackend = null;
}
$softAutoProvisionAllowed = (!isset($oidcSystemConfig['soft_auto_provision']) || $oidcSystemConfig['soft_auto_provision']);
if (!$softAutoProvisionAllowed && $userFromOtherBackend !== null) {
// if soft auto-provisioning is disabled,
// we refuse login for a user that already exists in another backend
return '';
}
if ($userFromOtherBackend === null) {
// only create the user in our backend if the user does not exist in another backend
$backendUser = $this->userMapper->getOrCreate($provider->getId(), $tokenUserId);
$userId = $backendUser->getUserId();
} else {
$userId = $userFromOtherBackend->getUID();
}
$this->checkFirstLogin($userId);
if ($this->providerService->getSetting($provider->getId(), ProviderService::SETTING_BEARER_PROVISIONING, '0') === '1') {
$provisioningStrategy = $validator->getProvisioningStrategy();
if ($provisioningStrategy) {
$this->provisionUser($validator->getProvisioningStrategy(), $provider, $tokenUserId, $headerToken, $userFromOtherBackend);
}
}
return $userId;
} elseif ($this->userExists($tokenUserId)) {
$this->checkFirstLogin($tokenUserId);
return $tokenUserId;
} else {
// check if the user exists locally
// if not, this potentially triggers a user_ldap search
// to get the user if it has not been synced yet
if (!$this->userManager->userExists($tokenUserId)) {
$this->userManager->search($tokenUserId);
$this->ldapService->syncUser($tokenUserId);
// return nothing, if the user was not found after the user_ldap search
if (!$this->userManager->userExists($tokenUserId)) {
return '';
}
}
$user = $this->userManager->get($tokenUserId);
if ($user === null || $this->ldapService->isLdapDeletedUser($user)) {
return '';
}
$this->checkFirstLogin($tokenUserId);
return $tokenUserId;
}
}
}
}
}
$this->logger->debug('Could not find unique token validation');
return '';
}
/**
* Inspired by lib/private/User/Session.php::prepareUserLogin()
*
* @param string $userId
* @return bool
* @throws NotFoundException
*/
private function checkFirstLogin(string $userId): bool {
$user = $this->userManager->get($userId);
if ($user === null) {
return false;
}
$firstLogin = $user->getLastLogin() === 0;
if ($firstLogin) {
\OC_Util::setupFS($userId);
// trigger creation of user home and /files folder
$userFolder = \OC::$server->getUserFolder($userId);
try {
// copy skeleton
\OC_Util::copySkeleton($userId, $userFolder);
} catch (NotPermittedException $ex) {
// read only uses
}
// trigger any other initialization
$this->eventDispatcher->dispatch(IUser::class . '::firstLogin', new GenericEvent($user));
// TODO add this when user_oidc min NC version is >= 28
// $this->eventDispatcher->dispatchTyped(new UserFirstTimeLoggedInEvent($user));
}
$user->updateLastLoginTimestamp();
return $firstLogin;
}
/**
* Triggers user provisioning based on the provided strategy
*
* @param string $provisioningStrategyClass
* @param Provider $provider
* @param string $tokenUserId
* @param string $headerToken
* @param IUser|null $userFromOtherBackend
* @return IUser|null
*/
private function provisionUser(
string $provisioningStrategyClass, Provider $provider, string $tokenUserId, string $headerToken,
?IUser $userFromOtherBackend,
): ?IUser {
$provisioningStrategy = \OC::$server->get($provisioningStrategyClass);
return $provisioningStrategy->provisionUser($provider, $tokenUserId, $headerToken, $userFromOtherBackend);
}
}