Welcome to mirror list, hosted at ThFree Co, Russian Federation.

RegistrationService.php « Service « lib - github.com/nextcloud/registration.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f0a527063ebc491e7e6732d284d6a8c826d6e8d4 (plain)
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
<?php

declare(strict_types=1);

/**
 * @copyright Copyright (c) 2017 Julius Härtl <jus@bitgrid.net>
 * @copyright Copyright (c) 2017 Pellaeon Lin <pellaeon@hs.ntnu.edu.tw>
 * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
 *
 * @author Julius Härtl <jus@bitgrid.net>
 * @author Pellaeon Lin <pellaeon@hs.ntnu.edu.tw>
 * @author Lukas Reschke <lukas@statuscode.ch>
 *
 * @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\Registration\Service;

use InvalidArgumentException;
use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberUtil;
use OC\Authentication\Exceptions\InvalidTokenException;
use OC\Authentication\Exceptions\PasswordlessTokenException;
use OC\Authentication\Token\IProvider;
use OC\Authentication\Token\IToken;
use OCA\Registration\AppInfo\Application;
use OCA\Registration\Db\Registration;
use OCA\Registration\Db\RegistrationMapper;
use OCA\Settings\Mailer\NewUserMailHelper;
use OCP\Accounts\IAccountManager;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\IRequest;
use OCP\ISession;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\Security\ICrypto;
use OCP\Session\Exceptions\SessionNotAvailableException;
use \OCP\IUserManager;
use \OCP\IUserSession;
use \OCP\IGroupManager;
use \OCP\IL10N;
use \OCP\IConfig;
use \OCP\Security\ISecureRandom;
use Psr\Log\LoggerInterface;

class RegistrationService {

	/** @var string */
	private $appName;
	/** @var MailService */
	private $mailService;
	/** @var IL10N */
	private $l10n;
	/** @var IURLGenerator */
	private $urlGenerator;
	/** @var RegistrationMapper */
	private $registrationMapper;
	/** @var IUserManager */
	private $userManager;
	/** @var IAccountManager */
	private $accountManager;
	/** @var IConfig */
	private $config;
	/** @var IGroupManager */
	private $groupManager;
	/** @var ISecureRandom */
	private $random;
	/** @var IUserSession  */
	private $userSession;
	/** @var IRequest */
	private $request;
	/** @var LoggerInterface */
	private $logger;
	/** @var ISession */
	private $session;
	/** @var IProvider */
	private $tokenProvider;
	/** @var ICrypto */
	private $crypto;

	public function __construct(
		string $appName,
		MailService $mailService,
		IL10N $l10n,
		IURLGenerator $urlGenerator,
		RegistrationMapper $registrationMapper,
		IUserManager $userManager,
		IAccountManager $accountManager,
		IConfig $config,
		IGroupManager $groupManager,
		ISecureRandom $random,
		IUserSession $userSession,
		IRequest $request,
		LoggerInterface $logger,
		ISession $session,
		IProvider $tokenProvider,
		ICrypto $crypto
	) {
		$this->appName = $appName;
		$this->mailService = $mailService;
		$this->l10n = $l10n;
		$this->urlGenerator = $urlGenerator;
		$this->registrationMapper = $registrationMapper;
		$this->userManager = $userManager;
		$this->accountManager = $accountManager;
		$this->config = $config;
		$this->groupManager = $groupManager;
		$this->random = $random;
		$this->userSession = $userSession;
		$this->request = $request;
		$this->logger = $logger;
		$this->session = $session;
		$this->tokenProvider = $tokenProvider;
		$this->crypto = $crypto;
	}

	public function confirmEmail(Registration $registration): void {
		$registration->setEmailConfirmed(true);
		$this->registrationMapper->update($registration);
	}

	public function generateNewToken(Registration $registration): void {
		$this->registrationMapper->generateNewToken($registration);
		$this->registrationMapper->update($registration);
	}

	/**
	 * Create registration request, used by both the API and form
	 * @param string $email
	 * @param string $username
	 * @param string $password
	 * @param string $displayname
	 * @return Registration
	 */
	public function createRegistration(string $email, string $username = '', string $password = '', string $displayname = ''): Registration {
		$registration = new Registration();
		$registration->setEmail($email);
		$registration->setUsername($username);
		$registration->setDisplayname($displayname);
		if ($password !== '') {
			$password = $this->crypto->encrypt($password);
			$registration->setPassword($password);
		}
		$this->registrationMapper->generateNewToken($registration);
		$this->registrationMapper->generateClientSecret($registration);
		$this->registrationMapper->insert($registration);
		return $registration;
	}

	/**
	 * @param string $email
	 * @throws RegistrationException
	 */
	public function validateEmail(string $email): void {
		if ($email === '' && $this->config->getAppValue($this->appName, 'email_is_optional', 'no') === 'yes') {
			return;
		}

		$this->mailService->validateEmail($email);

		// check for pending registrations
		try {
			$this->registrationMapper->find($email);//if not found DB will throw a exception
			throw new RegistrationException(
				$this->l10n->t('A user has already taken this email, maybe you already have an account?')
			);
		} catch (DoesNotExistException $e) {
		}

		if ($this->userManager->getByEmail($email)) {
			throw new RegistrationException(
				$this->l10n->t('A user has already taken this email, maybe you already have an account?'),
				$this->l10n->t('You can <a href="%s">log in now</a>.', [$this->urlGenerator->getAbsoluteURL('/')])
			);
		}

		if ($this->config->getAppValue($this->appName, 'allowed_domains', '') === '') {
			return;
		}

		$emailIsInDomainList = $this->checkAllowedDomains($email);
		$blockDomains = $this->config->getAppValue(Application::APP_ID, 'domains_is_blocklist', 'no') === 'yes';
		$showDomains = $this->config->getAppValue(Application::APP_ID, 'show_domains', 'no') === 'yes';

		if (!$blockDomains && !$emailIsInDomainList) {
			if ($showDomains) {
				throw new RegistrationException(
					$this->l10n->t(
						'Registration is only allowed with the following domains:'
					) . ' ' . implode(', ', explode(';',
						$this->config->getAppValue(Application::APP_ID, 'allowed_domains', '')
					))
				);
			}
			throw new RegistrationException(
				$this->l10n->t('Registration with this email domain is not allowed.')
			);
		}

		if ($blockDomains && $emailIsInDomainList) {
			if ($showDomains) {
				throw new RegistrationException(
					$this->l10n->t(
						'Registration is not allowed with the following domains:'
					) . ' ' . implode(', ', explode(';',
						$this->config->getAppValue(Application::APP_ID, 'allowed_domains', '')
					))
				);
			}
			throw new RegistrationException(
				$this->l10n->t('Registration with this email domain is not allowed.')
			);
		}
	}

	/**
	 * @param string $displayname
	 * @throws RegistrationException
	 */
	public function validateDisplayname(string $displayname): void {
		if ($displayname === '') {
			throw new RegistrationException($this->l10n->t('Please provide a valid display name.'));
		}
	}

	/**
	 * @param string $username
	 * @throws RegistrationException
	 */
	public function validateUsername(string $username): void {
		if ($username === '') {
			throw new RegistrationException($this->l10n->t('Please provide a valid login name.'));
		}

		$regex = $this->config->getAppValue($this->appName, 'username_policy_regex', '');
		if ($regex && preg_match($regex, $username) === 0) {
			throw new RegistrationException($this->l10n->t('Please provide a valid login name.'));
		}

		if ($this->registrationMapper->usernameIsPending($username) || $this->userManager->get($username) !== null) {
			throw new RegistrationException($this->l10n->t('The login name you have chosen already exists.'));
		}
	}

	/**
	 * @param string $phone
	 * @throws RegistrationException
	 */
	public function validatePhoneNumber(string $phone): void {
		$defaultRegion = $this->config->getSystemValueString('default_phone_region', '');

		if ($defaultRegion === '') {
			// When no default region is set, only +49… numbers are valid
			if (strpos($phone, '+') !== 0) {
				throw new RegistrationException($this->l10n->t('The phone number needs to contain the country code.'));
			}

			$defaultRegion = 'EN';
		}

		$phoneUtil = PhoneNumberUtil::getInstance();
		try {
			$phoneNumber = $phoneUtil->parse($phone, $defaultRegion);
			if (!$phoneNumber instanceof PhoneNumber || !$phoneUtil->isValidNumber($phoneNumber)) {
				throw new RegistrationException($this->l10n->t('The phone number is invalid.'));
			}
		} catch (NumberParseException $e) {
			throw new RegistrationException($this->l10n->t('The phone number is invalid.'));
		}
	}

	/**
	 * check if email domain is allowed
	 *
	 * @param string $email
	 * @return bool
	 */
	public function checkAllowedDomains(string $email): bool {
		$allowedDomains = $this->config->getAppValue($this->appName, 'allowed_domains', '');
		if ($allowedDomains !== '') {
			[,$mailDomain] = explode('@', strtolower($email), 2);
			$allowedDomains = explode(';', strtolower($allowedDomains));

			foreach ($allowedDomains as $domain) {
				// valid domain, everything's fine

				// Wildcards
				if (strpos($domain, '*') !== false) {
					// *.example.com
					// Make save for regex:
					// \*\.example\.com
					$regexDomain = preg_quote($domain, '\\');
					// Replace "\*" with an actual regex wildcard and set start and end:
					// /^.+\.example\.com$/
					$regexDomain = '/^' . str_replace('\\*', '.+', $regexDomain) . '$/';

					if (preg_match($regexDomain, $mailDomain)) {
						return true;
					}
				} elseif ($mailDomain === $domain) {
					return true;
				}
			}
			return false;
		}
		return true;
	}

	/**
	 * @return string[]
	 */
	public function getAllowedDomains(): array {
		$allowedDomains = $this->config->getAppValue($this->appName, 'allowed_domains', '');
		$allowedDomains = explode(';', $allowedDomains);
		return $allowedDomains;
	}

	/**
	 * @param Registration $registration
	 * @param string|null $loginName
	 * @param string|null $fullName
	 * @param string|null $phone
	 * @param string|null $password
	 * @return IUser
	 * @throws RegistrationException|InvalidArgumentException
	 */
	public function createAccount(Registration $registration, ?string $loginName = null, ?string $fullName = null, ?string $phone = null, ?string $password = null): IUser {
		if ($loginName === null) {
			$loginName = $registration->getUsername();
		}

		if ($registration->getPassword() !== null) {
			$password = $this->crypto->decrypt($registration->getPassword());
		}

		if (!$password) {
			throw new RegistrationException($this->l10n->t('Please provide a password.'));
		}

		$this->validateUsername($loginName);

		if ($this->config->getAppValue('registration', 'show_fullname', 'no') === 'yes'
			&& $this->config->getAppValue('registration', 'enforce_fullname', 'no') === 'yes') {
			$this->validateDisplayname($fullName);
		}

		if (class_exists(PhoneNumberUtil::class)
			&& $this->config->getAppValue('registration', 'show_phone', 'no') === 'yes') {
			if ($phone) {
				$this->validatePhoneNumber($phone);
			} elseif ($this->config->getAppValue('registration', 'enforce_phone', 'no') === 'yes') {
				throw new RegistrationException($this->l10n->t('Please provide a valid phone number.'));
			}
		}

		/* TODO
		 * createUser tests username validity once, but validateUsername already checked it,
		 * but createUser doesn't check if there is a pending registration with that name
		 *
		 * And validateUsername will throw RegistrationException while
		 * createUser throws \InvalidArgumentException
		 */
		$user = $this->userManager->createUser($loginName, $password);
		if ($user === false) {
			throw new RegistrationException($this->l10n->t('Unable to create user, there are problems with the user backend.'));
		}
		$userId = $user->getUID();


		// Set user email
		try {
			$user->setEMailAddress($registration->getEmail());
		} catch (\Exception $e) {
			throw new RegistrationException($this->l10n->t('Unable to set user email: ' . $e->getMessage()));
		}

		// Set display name
		if ($fullName && $this->config->getAppValue('registration', 'show_fullname', 'no') === 'yes') {
			$user->setDisplayName($fullName);
		}

		// Set phone number in account data
		if (method_exists($this->accountManager, 'updateAccount')
			&& $phone
			&& $this->config->getAppValue('registration', 'show_phone', 'no') === 'yes') {
			$account = $this->accountManager->getAccount($user);
			$property = $account->getProperty(IAccountManager::PROPERTY_PHONE);
			$account->setProperty(
				IAccountManager::PROPERTY_PHONE,
				$phone,
				$property->getScope(),
				IAccountManager::NOT_VERIFIED
			);
			$this->accountManager->updateAccount($account);
		}

		// Add user to group
		$registeredUserGroup = $this->config->getAppValue($this->appName, 'registered_user_group', 'none');
		if ($registeredUserGroup !== 'none') {
			$group = $this->groupManager->get($registeredUserGroup);
			if ($group === null) {
				// This might happen if $registered_user_group is deleted after setting the value
				// Here I choose to log error instead of stopping the user to register
				$this->logger->error("You specified newly registered users be added to '$registeredUserGroup' group, but it does not exist.");
				$groupId = '';
			} else {
				$group->addUser($user);
				$groupId = $group->getGID();
			}
		} else {
			$groupId = '';
		}

		// disable user if this is requested by config
		$adminApprovalRequired = $this->config->getAppValue($this->appName, 'admin_approval_required', 'no');
		if ($adminApprovalRequired === 'yes') {
			$user->setEnabled(false);
			$this->config->setUserValue($userId, Application::APP_ID,'send_welcome_mail_on_enable', 'yes');
		} else {
			$this->sendWelcomeMail($user);
		}

		$this->mailService->notifyAdmins($userId, $user->getEMailAddress(), $user->isEnabled(), $groupId);
		return $user;
	}

	public function sendWelcomeMail(IUser $user): void {
		if ($this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes') {
			/** @var NewUserMailHelper $helper */
			$helper = \OC::$server->get(NewUserMailHelper::class);

			try {
				$emailTemplate = $helper->generateTemplate($user);
				$helper->sendMail($user, $emailTemplate);
			} catch (\Exception $e) {
				// Catching this so at least admins are notified
				$this->logger->error(
					'Unable to send the invitation mail to {user}',
					[
						'user' => $user->getUID(),
						'exception' => $e,
					]
				);
			}
		}
	}

	/**
	 * @param string $email
	 * @return Registration
	 * @throws DoesNotExistException
	 */
	public function getRegistrationForEmail(string $email): Registration {
		return $this->registrationMapper->find($email);
	}

	/**
	 * @param string $secret
	 * @return Registration
	 * @throws DoesNotExistException
	 */
	public function getRegistrationForSecret(string $secret): Registration {
		return $this->registrationMapper->findBySecret($secret);
	}

	public function deleteRegistration(Registration $registration): void {
		$this->registrationMapper->delete($registration);
	}

	/**
	 * Return a 25 digit device password
	 *
	 * Example: AbCdE-fGhIj-KlMnO-pQrSt-12345
	 *
	 * @return string
	 */
	private function generateRandomDeviceToken(): string {
		$groups = [];
		for ($i = 0; $i < 5; $i++) {
			$groups[] = $this->random->generate(5, ISecureRandom::CHAR_HUMAN_READABLE);
		}
		return implode('-', $groups);
	}

	/**
	 * @param string $uid
	 * @return string
	 * @throws RegistrationException
	 */
	public function generateAppPassword(string $uid): string {
		$name = $this->l10n->t('Registration app auto setup');
		try {
			$sessionId = $this->session->getId();
		} catch (SessionNotAvailableException $ex) {
			throw new RegistrationException('Failed to generate an app token.');
		}

		try {
			$sessionToken = $this->tokenProvider->getToken($sessionId);
			$loginName = $sessionToken->getLoginName();
			try {
				$password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
			} catch (PasswordlessTokenException $ex) {
				$password = null;
			}
		} catch (InvalidTokenException $ex) {
			throw new RegistrationException('Failed to generate an app token.');
		}

		$token = $this->generateRandomDeviceToken();
		$this->tokenProvider->generateToken($token, $uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN);
		return $token;
	}

	/**
	 * @param string $userId
	 * @param string $username
	 * @param string $password
	 * @param bool $decrypt
	 */
	public function loginUser(string $userId, string $username, string $password, bool $decrypt = false): void {
		if ($decrypt) {
			$password = $this->crypto->decrypt($password);
		}

		$this->userSession->login($username, $password);
		$this->userSession->createSessionToken($this->request, $userId, $username, $password);
	}
}