Make RegistrationService strict

Signed-off-by: Joas Schilling <coding@schilljs.com>
This commit is contained in:
Joas Schilling 2020-07-17 11:14:02 +02:00
parent 0b4fac2edf
commit f0aa35b580
No known key found for this signature in database
GPG Key ID: 7076EA9751AACDDA
1 changed files with 50 additions and 47 deletions

View File

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* @copyright Copyright (c) 2017 Julius Härtl <jus@bitgrid.net> * @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 Pellaeon Lin <pellaeon@hs.ntnu.edu.tw>
@ -34,8 +37,6 @@ use OC\Authentication\Token\IToken;
use OCA\Registration\Db\Registration; use OCA\Registration\Db\Registration;
use OCA\Registration\Db\RegistrationMapper; use OCA\Registration\Db\RegistrationMapper;
use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Db\DoesNotExistException;
use \OCP\AppFramework\Http\TemplateResponse;
use \OCP\AppFramework\Http\RedirectResponse;
use OCP\ILogger; use OCP\ILogger;
use OCP\IRequest; use OCP\IRequest;
use OCP\ISession; use OCP\ISession;
@ -71,7 +72,7 @@ class RegistrationService {
/** @var ISecureRandom */ /** @var ISecureRandom */
private $random; private $random;
/** @var IUserSession */ /** @var IUserSession */
private $usersession; private $userSession;
/** @var IRequest */ /** @var IRequest */
private $request; private $request;
/** @var ILogger */ /** @var ILogger */
@ -83,9 +84,23 @@ class RegistrationService {
/** @var ICrypto */ /** @var ICrypto */
private $crypto; private $crypto;
public function __construct($appName, MailService $mailService, IL10N $l10n, IURLGenerator $urlGenerator, public function __construct(
RegistrationMapper $registrationMapper, IUserManager $userManager, IConfig $config, IGroupManager $groupManager, string $appName,
ISecureRandom $random, IUserSession $us, IRequest $request, ILogger $logger, ISession $session, IProvider $tokenProvider, ICrypto $crypto) { MailService $mailService,
IL10N $l10n,
IURLGenerator $urlGenerator,
RegistrationMapper $registrationMapper,
IUserManager $userManager,
IConfig $config,
IGroupManager $groupManager,
ISecureRandom $random,
IUserSession $userSession,
IRequest $request,
ILogger $logger,
ISession $session,
IProvider $tokenProvider,
ICrypto $crypto
) {
$this->appName = $appName; $this->appName = $appName;
$this->mailService = $mailService; $this->mailService = $mailService;
$this->l10n = $l10n; $this->l10n = $l10n;
@ -95,7 +110,7 @@ class RegistrationService {
$this->config = $config; $this->config = $config;
$this->groupManager = $groupManager; $this->groupManager = $groupManager;
$this->random = $random; $this->random = $random;
$this->usersession = $us; $this->userSession = $userSession;
$this->request = $request; $this->request = $request;
$this->logger = $logger; $this->logger = $logger;
$this->session = $session; $this->session = $session;
@ -103,21 +118,16 @@ class RegistrationService {
$this->crypto = $crypto; $this->crypto = $crypto;
} }
/** public function confirmEmail(Registration $registration): void {
* @param Registration $registration
*/
public function confirmEmail(Registration $registration) {
$registration->setEmailConfirmed(true); $registration->setEmailConfirmed(true);
$this->registrationMapper->update($registration); $this->registrationMapper->update($registration);
} }
/** public function generateNewToken(Registration $registration): void {
* @param Registration $registration
*/
public function generateNewToken(Registration $registration) {
$this->registrationMapper->generateNewToken($registration); $this->registrationMapper->generateNewToken($registration);
$this->registrationMapper->update($registration); $this->registrationMapper->update($registration);
} }
/** /**
* Create registration request, used by both the API and form * Create registration request, used by both the API and form
* @param string $email * @param string $email
@ -126,7 +136,7 @@ class RegistrationService {
* @param string $displayname * @param string $displayname
* @return Registration * @return Registration
*/ */
public function createRegistration($email, $username="", $password="", $displayname="") { public function createRegistration(string $email, string $username = '', string $password = '', string $displayname = ''): Registration {
$registration = new Registration(); $registration = new Registration();
$registration->setEmail($email); $registration->setEmail($email);
$registration->setUsername($username); $registration->setUsername($username);
@ -178,8 +188,8 @@ class RegistrationService {
* @param string $displayname * @param string $displayname
* @throws RegistrationException * @throws RegistrationException
*/ */
public function validateDisplayname($displayname) { public function validateDisplayname(string $displayname): void {
if ($displayname === "") { if ($displayname === '') {
throw new RegistrationException($this->l10n->t('Please provide a valid display name.')); throw new RegistrationException($this->l10n->t('Please provide a valid display name.'));
} }
} }
@ -188,7 +198,7 @@ class RegistrationService {
* @param string $username * @param string $username
* @throws RegistrationException * @throws RegistrationException
*/ */
public function validateUsername($username) { public function validateUsername(string $username): void {
if ($username === "") { if ($username === "") {
throw new RegistrationException($this->l10n->t('Please provide a valid user name.')); throw new RegistrationException($this->l10n->t('Please provide a valid user name.'));
} }
@ -204,7 +214,7 @@ class RegistrationService {
* @param string $email * @param string $email
* @return bool * @return bool
*/ */
public function checkAllowedDomains($email) { public function checkAllowedDomains(string $email): bool {
$allowed_domains = $this->config->getAppValue($this->appName, 'allowed_domains', ''); $allowed_domains = $this->config->getAppValue($this->appName, 'allowed_domains', '');
if ($allowed_domains !== '') { if ($allowed_domains !== '') {
$allowed_domains = explode(';', $allowed_domains); $allowed_domains = explode(';', $allowed_domains);
@ -223,9 +233,9 @@ class RegistrationService {
} }
/** /**
* @return array * @return string[]
*/ */
public function getAllowedDomains() { public function getAllowedDomains(): array {
$allowed_domains = $this->config->getAppValue($this->appName, 'allowed_domains', ''); $allowed_domains = $this->config->getAppValue($this->appName, 'allowed_domains', '');
$allowed_domains = explode(';', $allowed_domains); $allowed_domains = explode(';', $allowed_domains);
return $allowed_domains; return $allowed_domains;
@ -250,10 +260,10 @@ class RegistrationService {
* @param $registration * @param $registration
* @param string|null $username * @param string|null $username
* @param string|null $password * @param string|null $password
* @return \OCP\IUser * @return IUser
* @throws RegistrationException|InvalidTokenException * @throws RegistrationException|InvalidTokenException
*/ */
public function createAccount(Registration $registration, ?string $username = null, ?string $password = null) { public function createAccount(Registration $registration, ?string $username = null, ?string $password = null): IUser {
if ($password === null && $registration->getPassword() === null) { if ($password === null && $registration->getPassword() === null) {
$generatedPassword = $this->generateRandomDeviceToken(); $generatedPassword = $this->generateRandomDeviceToken();
$registration->setPassword($this->crypto->encrypt($generatedPassword)); $registration->setPassword($this->crypto->encrypt($generatedPassword));
@ -281,6 +291,7 @@ class RegistrationService {
throw new RegistrationException($this->l10n->t('Unable to create user, there are problems with the user backend.')); throw new RegistrationException($this->l10n->t('Unable to create user, there are problems with the user backend.'));
} }
$userId = $user->getUID(); $userId = $user->getUID();
// Set user email // Set user email
try { try {
$user->setEMailAddress($registration->getEmail()); $user->setEMailAddress($registration->getEmail());
@ -289,25 +300,25 @@ class RegistrationService {
} }
// Add user to group // Add user to group
$registered_user_group = $this->config->getAppValue($this->appName, 'registered_user_group', 'none'); $registeredUserGroup = $this->config->getAppValue($this->appName, 'registered_user_group', 'none');
if ($registered_user_group !== 'none') { if ($registeredUserGroup !== 'none') {
$group = $this->groupManager->get($registered_user_group); $group = $this->groupManager->get($registeredUserGroup);
if ($group === null) { if ($group === null) {
// This might happen if $registered_user_group is deleted after setting the value // 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 // Here I choose to log error instead of stopping the user to register
$this->logger->error("You specified newly registered users be added to '$registered_user_group' group, but it does not exist."); $this->logger->error("You specified newly registered users be added to '$registeredUserGroup' group, but it does not exist.");
$groupId = ''; $groupId = '';
} else { } else {
$group->addUser($user); $group->addUser($user);
$groupId = $group->getGID(); $groupId = $group->getGID();
} }
} else { } else {
$groupId = ""; $groupId = '';
} }
// disable user if this is requested by config // disable user if this is requested by config
$admin_approval_required = $this->config->getAppValue($this->appName, 'admin_approval_required', "no"); $adminApprovalRequired = $this->config->getAppValue($this->appName, 'admin_approval_required', 'no');
if ($admin_approval_required === "yes") { if ($adminApprovalRequired === 'yes') {
$user->setEnabled(false); $user->setEnabled(false);
} }
@ -353,19 +364,11 @@ class RegistrationService {
return $this->registrationMapper->findBySecret($secret); return $this->registrationMapper->findBySecret($secret);
} }
/** public function getUserAccount(Registration $registration): ?IUser {
* @param Registration $registation return $this->userManager->get($registration->getUsername());
* @return null|\OCP\IUser
*/
public function getUserAccount(Registration $registation) {
$user = $this->userManager->get($registation->getUsername());
return $user;
} }
/** public function deleteRegistration(Registration $registration): void {
* @param Registration $registration
*/
public function deleteRegistration(Registration $registration) {
$this->registrationMapper->delete($registration); $this->registrationMapper->delete($registration);
} }
@ -376,7 +379,7 @@ class RegistrationService {
* *
* @return string * @return string
*/ */
private function generateRandomDeviceToken() { private function generateRandomDeviceToken(): string {
$groups = []; $groups = [];
for ($i = 0; $i < 5; $i++) { for ($i = 0; $i < 5; $i++) {
$groups[] = $this->random->generate(5, ISecureRandom::CHAR_HUMAN_READABLE); $groups[] = $this->random->generate(5, ISecureRandom::CHAR_HUMAN_READABLE);
@ -389,7 +392,7 @@ class RegistrationService {
* @return string * @return string
* @throws RegistrationException * @throws RegistrationException
*/ */
public function generateAppPassword($uid) { public function generateAppPassword(string $uid): string {
$name = $this->l10n->t('Registration app auto setup'); $name = $this->l10n->t('Registration app auto setup');
try { try {
$sessionId = $this->session->getId(); $sessionId = $this->session->getId();
@ -425,15 +428,15 @@ class RegistrationService {
$password = $this->crypto->decrypt($password); $password = $this->crypto->decrypt($password);
} }
$this->usersession->login($username, $password); $this->userSession->login($username, $password);
$this->usersession->createSessionToken($this->request, $userId, $username, $password); $this->userSession->createSessionToken($this->request, $userId, $username, $password);
} }
/** /**
* Replicates OC::cleanupLoginTokens() since it's protected * Replicates OC::cleanupLoginTokens() since it's protected
* @param string $userId * @param string $userId
*/ */
public function cleanupLoginTokens($userId) { public function cleanupLoginTokens(string $userId): void {
$cutoff = time() - $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15); $cutoff = time() - $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
$tokens = $this->config->getUserKeys($userId, 'login_token'); $tokens = $this->config->getUserKeys($userId, 'login_token');
foreach ($tokens as $token) { foreach ($tokens as $token) {