diff --git a/admin.php b/admin.php index b085198..b8f3323 100644 --- a/admin.php +++ b/admin.php @@ -11,6 +11,7 @@ namespace OCA\Registration\AppInfo; -$app = new Application(); -$controller = $app->getContainer()->query('SettingsController'); +use OCA\Registration\Controller\SettingsController; + +$controller = \OC::$server->query(SettingsController::class); return $controller->displayPanel()->render(); diff --git a/appinfo/app.php b/appinfo/app.php index a29f1c5..feadb9d 100644 --- a/appinfo/app.php +++ b/appinfo/app.php @@ -11,9 +11,9 @@ namespace OCA\Registration\AppInfo; -$app = new Application(); -$c = $app->getContainer(); +\OC_App::registerLogIn([ + 'name' => \OC::$server->getL10N('registration')->t('Register'), + 'href' => \OC::$server->getURLGenerator()->linkToRoute('registration.register.askEmail') +]); -\OC_App::registerLogIn(array('name' => $c->query('L10N')->t('Register'), 'href' => $c->query('URLGenerator')->linkToRoute('registration.register.askEmail'))); - -\OCP\App::registerAdmin($c->getAppName(), 'admin'); +\OCP\App::registerAdmin('registration', 'admin'); \ No newline at end of file diff --git a/appinfo/application.php b/appinfo/application.php deleted file mode 100644 index 3ab1f54..0000000 --- a/appinfo/application.php +++ /dev/null @@ -1,100 +0,0 @@ - - * @copyright Pellaeon Lin 2014 - */ - -namespace OCA\Registration\AppInfo; - -use \OC\AppFramework\Utility\SimpleContainer; - -use \OCP\AppFramework\App; - -use \OCA\Registration\Controller\RegisterController; -use \OCA\Registration\Controller\SettingsController; -use \OCA\Registration\Wrapper; -use \OCA\Registration\Db\PendingRegist; - - -class Application extends App { - - public function __construct (array $urlParams=array()) { - parent::__construct('registration', $urlParams); - - $container = $this->getContainer(); - - /** - * Controllers - */ - $container->registerService('RegisterController', function(SimpleContainer $c) { - return new RegisterController( - $c->query('AppName'), - $c->query('Request'), - $c->query('Mailer'), - $c->query('L10N'), - $c->query('URLGenerator'), - $c->query('PendingRegist'), - $c->query('UserManager'), - $c->query('Config'), - $c->query('GroupManager'), - $c->query('Defaults'), - $c->query('ServerContainer')->getSecureRandom()->getMediumStrengthGenerator(), - $c->query('ServerContainer')->getUserSession() - ); - }); - - $container->registerService('SettingsController', function(SimpleContainer $c) { - return new SettingsController( - $c->query('AppName'), - $c->query('Request'), - $c->query('L10N'), - $c->query('Config'), - $c->query('GroupManager') - ); - }); - - - /** - * Core - */ - $container->registerService('UserManager', function(SimpleContainer $c) { - return $c->query('ServerContainer')->getUserManager(); - }); - - $container->registerService('GroupManager', function(SimpleContainer $c) { - return $c->query('ServerContainer')->getGroupManager(); - }); - - $container->registerService('Config', function(SimpleContainer $c) { - return $c->query('ServerContainer')->getConfig(); - }); - - $container->registerService('Mailer', function(SimpleContainer $c) { - return $c->query('ServerContainer')->getMailer(); - }); - - $container->registerService('L10N', function(SimpleContainer $c) { - return $c->query('ServerContainer')->getL10N($c->query('AppName')); - }); - - $container->registerService('URLGenerator', function(SimpleContainer $c) { - return $c->getServer()->getURLGenerator(); - }); - - $container->registerService('PendingRegist', function(SimpleContainer $c) { - return new PendingRegist($c->query('ServerContainer')->getDatabaseConnection(), - $c->query('ServerContainer')->getSecureRandom()->getMediumStrengthGenerator()); - }); - - $container->registerService('Defaults', function(SimpleContainer $c) { - return new \OCP\Defaults; - }); - } - - -} diff --git a/controller/registercontroller.php b/controller/registercontroller.php index 464e8c6..1770cfc 100644 --- a/controller/registercontroller.php +++ b/controller/registercontroller.php @@ -6,64 +6,50 @@ * later. See the COPYING file. * * @author Pellaeon Lin + * @author Julius Härtl * @copyright Pellaeon Lin 2014 */ namespace OCA\Registration\Controller; - +use OCA\Registration\Service\RegistrationException; +use OCA\Registration\Service\RegistrationService; use \OCP\IRequest; use \OCP\AppFramework\Http\TemplateResponse; use \OCP\AppFramework\Http\RedirectResponse; use \OCP\AppFramework\Controller; -use \OCP\Defaults; -use \OCP\Util; -use \OCA\Registration\Wrapper; -use \OCP\IUserManager; -use \OCP\IUserSession; -use \OCP\IGroupManager; +use OCP\IURLGenerator; use \OCP\IL10N; -use \OCP\IConfig; -use \OCP\Mail\IMailer; -use \OCP\Security\ISecureRandom; -use \OC_User; -use \OC_Util; class RegisterController extends Controller { - private $mailer; private $l10n; private $urlgenerator; - private $pendingreg; - private $usermanager; - private $config; - private $groupmanager; - /** @var \OCP\Defaults */ - private $defaults; - private $random; - private $usersession; - protected $appName; + /** @var RegistrationService */ + private $registrationService; - public function __construct($appName, IRequest $request, IMailer $mailer, IL10N $l10n, $urlgenerator, - $pendingreg, IUserManager $usermanager, IConfig $config, IGroupManager $groupmanager, Defaults $defaults, - ISecureRandom $random, IUserSession $us){ - $this->mailer = $mailer; + + public function __construct( + $appName, + IRequest $request, + IL10N $l10n, + IURLGenerator $urlgenerator, + RegistrationService $registrationService + ){ + parent::__construct($appName, $request); + $this->request = $request; $this->l10n = $l10n; $this->urlgenerator = $urlgenerator; - $this->pendingreg = $pendingreg; - $this->usermanager = $usermanager; - $this->config = $config; - $this->groupmanager = $groupmanager; - $this->defaults = $defaults; - $this->appName = $appName; - $this->random = $random; - $this->usersession = $us; - parent::__construct($appName, $request); + $this->registrationService = $registrationService; } /** * @NoCSRFRequired * @PublicPage + * + * @param $errormsg + * @param $entered + * @return TemplateResponse */ public function askEmail($errormsg, $entered) { $params = array( @@ -75,83 +61,19 @@ class RegisterController extends Controller { /** * @PublicPage + * @return TemplateResponse */ public function validateEmail() { $email = $this->request->getParam('email'); - if ( !$this->mailer->validateMailAddress($email) ) { - return new TemplateResponse('', 'error', array( - 'errors' => array(array( - 'error' => $this->l10n->t('The email address you entered is not valid'), - 'hint' => '' - )) - ), 'error'); - } - - if ( $this->pendingreg->find($email) ) { - $this->pendingreg->delete($email); - $token = $this->pendingreg->save($email); - - try { - $this->sendValidationEmail($token, $email); - } catch (\Exception $e) { - return new TemplateResponse('', 'error', array( - 'errors' => array(array( - 'error' => $this->l10n->t('A problem occurred sending email, please contact your administrator.'), - 'hint' => '' - )) - ), 'error'); - } - return new TemplateResponse('', 'error', array( - 'errors' => array(array( - 'error' => $this->l10n->t('There is already a pending registration with this email, a new verification email has been sent to the address.'), - 'hint' => '' - )) - ), 'error'); - } - - if ( $this->config->getUsersForUserValue('settings', 'email', $email) ) { - return new TemplateResponse('', 'error', array( - 'errors' => array(array( - 'error' => $this->l10n->t('A user has already taken this email, maybe you already have an account?'), - 'hint' => str_replace( - '{login}', $this->urlgenerator->getAbsoluteURL('/'), - $this->l10n->t('You can log in now.')) - )) - ), 'error'); - } - - - // allow only from specific email domain - $allowed_domains = $this->config->getAppValue($this->appName, 'allowed_domains', ''); - if ( $allowed_domains !== '' ) { - $allowed_domains = explode(';', $allowed_domains); - $allowed = false; - foreach ( $allowed_domains as $domain ) { - $maildomain=explode("@",$email)[1]; - // valid domain, everythings fine - if ($maildomain === $domain) { - $allowed=true; - break; - } - } - if ( $allowed === false ) { - return new TemplateResponse('registration', 'domains', ['domains' => - $allowed_domains - ], 'guest'); - } - } - - $token = $this->pendingreg->save($email); try { - $this->sendValidationEmail($token, $email); - } catch (\Exception $e) { - return new TemplateResponse('', 'error', array( - 'errors' => array(array( - 'error' => $this->l10n->t('A problem occurred sending email, please contact your administrator.'), - 'hint' => '' - )) - ), 'error'); + $validation = $this->registrationService->validateEmail($email); + if($validation instanceof TemplateResponse) { + return $validation; + } + } catch (RegistrationException $e) { + return $this->renderError($e->getMessage(), $e->getHint()); } + return new TemplateResponse('registration', 'message', array('msg' => $this->l10n->t('Verification email successfully sent.') ), 'guest'); @@ -160,207 +82,60 @@ class RegisterController extends Controller { /** * @NoCSRFRequired * @PublicPage + * + * @param $token + * @return TemplateResponse */ public function verifyToken($token) { - $email = $this->pendingreg->findEmailByToken($token); - if ( $email === false ) { - return new TemplateResponse('', 'error', array( - 'errors' => array(array( - 'error' => $this->l10n->t('Invalid verification URL. No registration request with this verification URL is found.'), - 'hint' => '' - )) - ), 'error'); - } elseif ( $email ) { - return new TemplateResponse('registration', 'form', array('email' => $email, 'token' => $token), 'guest'); + try { + $registration = $this->registrationService->verifyToken($token); + return new TemplateResponse('registration', 'form', ['email' => $registration->getEmail(), 'token' => $registration->getToken()], 'guest'); + } catch (RegistrationException $exception) { + return $this->renderError($exception->getMessage(), $exception->getHint()); } + } /** * @PublicPage * @UseSession + * + * @param $token + * @return RedirectResponse|TemplateResponse */ public function createAccount($token) { - $email = $this->pendingreg->findEmailByToken($token); - if ( $email === false ) { - return new TemplateResponse('', 'error', array( - 'errors' => array(array( - 'error' => $this->l10n->t('Invalid verification URL. No registration request with this verification URL is found.'), - 'hint' => '' - )) - ), 'error'); - } elseif ( $email ) { - $username = $this->request->getParam('username'); - $password = $this->request->getParam('password'); - try { - $user = $this->usermanager->createUser($username, $password); - } catch (\Exception $e) { - return new TemplateResponse('registration', 'form', - array('email' => $email, - 'entered_data' => array('username' => $username), - 'errormsgs' => array($e->getMessage()), - 'token' => $token), 'guest'); - } - if ( $user === false ) { - return new TemplateResponse('', 'error', array( - 'errors' => array(array( - 'error' => $this->l10n->t('Unable to create user, there are problems with the user backend.'), - 'hint' => '' - )) - ), 'error'); - } else { - $userId = $user->getUID(); - // Set user email - try { - $this->config->setUserValue($userId, 'settings', 'email', $email); - } catch (\Exception $e) { - return new TemplateResponse('', 'error', array( - 'errors' => array(array( - 'error' => $this->l10n->t('Unable to set user email: '.$e->getMessage()), - 'hint' => '' - )) - ), 'error'); - } + $username = $this->request->getParam('username'); + $password = $this->request->getParam('password'); + $registration = $this->registrationService->getRegistrationForToken($token); - // Add user to group - $registered_user_group = $this->config->getAppValue($this->appName, 'registered_user_group', 'none'); - if ( $registered_user_group !== 'none' ) { - try { - $group = $this->groupmanager->get($registered_user_group); - $group->addUser($user); - } catch (\Exception $e) { - return new TemplateResponse('', 'error', array( - 'errors' => array(array( - 'error' => $e->message, - )) - ), 'error'); - } - } - - // Delete pending reg request - $res = $this->pendingreg->delete($email); - if ( $res === false ) { - return new TemplateResponse('', 'error', array( - 'errors' => array(array( - 'error' => $this->l10n->t('Failed to delete pending registration request'), - 'hint' => '' - )) - ), 'error'); - } - - // Notify admin - $admin_users = $this->groupmanager->get('admin')->getUsers(); - $to_arr = array(); - foreach ( $admin_users as $au ) { - $au_email = $this->config->getUserValue($au->getUID(), 'settings', 'email'); - if ( $au_email !== '' ) { - $to_arr[$au_email] = $au->getDisplayName(); - } - } - try { - $this->sendNewUserNotifEmail($to_arr, $userId); - } catch (\Exception $e) { - \OCP\Util::writeLog('registration', 'Sending admin notification email failed: '. $e->getMessage, \OCP\Util::ERROR); - } - - // Try to log user in - if ( method_exists($this->usersession, 'createSessionToken') ) { - $this->usersession->login($username, $password); - $this->usersession->createSessionToken($this->request, $userId, $username, $password); - return new RedirectResponse($this->urlgenerator->linkToRoute('files.view.index')); - } elseif (OC_User::login($username, $password)) { - $this->cleanupLoginTokens($userId); - // FIXME unsetMagicInCookie will fail from session already closed, so now we always remember - $logintoken = $this->random->generate(32); - $this->config->setUserValue($userId, 'login_token', $logintoken, time()); - OC_User::setMagicInCookie($userId, $logintoken); - OC_Util::redirectToDefaultPage(); - - // Render message in case redirect failed - return new TemplateResponse('registration', 'message', array('msg' => - str_replace('{link}', - $this->urlgenerator->getAbsoluteURL('/'), - $this->l10n->t('Your account has been successfully created, you can log in now.') - )), 'guest'); - } - } + try { + $this->registrationService->createAccount($token, $username, $password); + } catch (RegistrationException $exception) { + return $this->renderError($exception->getMessage(), $exception->getHint()); + } catch (\InvalidArgumentException $exception) { + // Render form with previously sent values + return new TemplateResponse('registration', 'form', + [ + 'email' => $registration->getEmail(), + 'entered_data' => array('user' => $username), + 'errormsgs' => array($exception->getMessage()), + 'token' => $token + ], 'guest'); } + + return new TemplateResponse('registration', 'message', + ['msg' => $this->l10n->t('Your account has been successfully created, you can log in now.', [$this->urlgenerator->getAbsoluteURL('/')])], + 'guest' + ); } - /** - * Sends validation email - * @param string $token - * @param string $to - * @return null - * @throws \Exception - */ - private function sendValidationEmail($token, $to) { - $link = $this->urlgenerator->linkToRoute('registration.register.verifyToken', array('token' => $token)); - $link = $this->urlgenerator->getAbsoluteURL($link); - $template_var = [ - 'link' => $link, - 'sitename' => $this->defaults->getName() - ]; - $html_template = new TemplateResponse('registration', 'email.validate_html', $template_var, 'blank'); - $html_part = $html_template->render(); - $plaintext_template = new TemplateResponse('registration', 'email.validate_plaintext', $template_var, 'blank'); - $plaintext_part = $plaintext_template->render(); - $subject = $this->l10n->t('Verify your %s registration request', [$this->defaults->getName()]); - - $from = Util::getDefaultEmailAddress('register'); - $message = $this->mailer->createMessage(); - $message->setFrom([$from => $this->defaults->getName()]); - $message->setTo([$to]); - $message->setSubject($subject); - $message->setPlainBody($plaintext_part); - $message->setHtmlBody($html_part); - $failed_recipients = $this->mailer->send($message); - if ( !empty($failed_recipients) ) - throw new \Exception('Failed recipients: '.print_r($failed_recipients, true)); + private function renderError($error, $hint="") { + return new TemplateResponse('', 'error', array( + 'errors' => array(array( + 'error' => $error, + 'hint' => $hint + )) + ), 'error'); } - /** - * Sends new user notification email to admin - * @param array $to - * @param string $username the new user - * @return null - * @throws \Exception - */ - private function sendNewUserNotifEmail(array $to, $username) { - $template_var = [ - 'user' => $username, - 'sitename' => $this->defaults->getName() - ]; - $html_template = new TemplateResponse('registration', 'email.newuser_html', $template_var, 'blank'); - $html_part = $html_template->render(); - $plaintext_template = new TemplateResponse('registration', 'email.newuser_plaintext', $template_var, 'blank'); - $plaintext_part = $plaintext_template->render(); - $subject = $this->l10n->t('A new user "%s" has created an account on %s', [$username, $this->defaults->getName()]); - - $from = Util::getDefaultEmailAddress('register'); - $message = $this->mailer->createMessage(); - $message->setFrom([$from => $this->defaults->getName()]); - $message->setTo($to); - $message->setSubject($subject); - $message->setPlainBody($plaintext_part); - $message->setHtmlBody($html_part); - $failed_recipients = $this->mailer->send($message); - if ( !empty($failed_recipients) ) - throw new \Exception('Failed recipients: '.print_r($failed_recipients, true)); - } - - /** - * Replicates OC::cleanupLoginTokens() since it's protected - * @param string $userId - * @return null - */ - private function cleanupLoginTokens($userId) { - $cutoff = time() - $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15); - $tokens = $this->config->getUserKeys($userId, 'login_token'); - foreach ($tokens as $token) { - $time = $this->config->getUserValue($userId, 'login_token', $token); - if ($time < $cutoff) { - $this->config->deleteUserValue($userId, 'login_token', $token); - } - } - } } diff --git a/controller/settingscontroller.php b/controller/settingscontroller.php index c8b62b1..f01eadc 100644 --- a/controller/settingscontroller.php +++ b/controller/settingscontroller.php @@ -6,6 +6,7 @@ * later. See the COPYING file. * * @author Pellaeon Lin + * @author Julius Härtl * @copyright Pellaeon Lin 2015 */ @@ -19,21 +20,24 @@ use \OCP\AppFramework\Controller; use \OCP\IGroupManager; use \OCP\IL10N; use \OCP\IConfig; -use \OCP\IUser; class SettingsController extends Controller { + /** @var IL10N */ private $l10n; + /** @var IConfig */ private $config; + /** @var IGroupManager */ private $groupmanager; + /** @var string */ protected $appName; public function __construct($appName, IRequest $request, IL10N $l10n, IConfig $config, IGroupManager $groupmanager){ + parent::__construct($appName, $request); $this->l10n = $l10n; $this->config = $config; $this->groupmanager = $groupmanager; $this->appName = $appName; - parent::__construct($appName, $request); } @@ -89,6 +93,7 @@ class SettingsController extends Controller { */ public function displayPanel() { $groups = $this->groupmanager->search(''); + $group_id_list = []; foreach ( $groups as $group ) { $group_id_list[] = $group->getGid(); } diff --git a/db/pendingregist.php b/db/pendingregist.php deleted file mode 100644 index 1cdb7ee..0000000 --- a/db/pendingregist.php +++ /dev/null @@ -1,49 +0,0 @@ -db = $db; - $this->random = $random; - } - - public function save($email) { - $query = $this->db->prepare( 'INSERT INTO `*PREFIX*registration`' - .' ( `email`, `token`, `requested` ) VALUES( ?, ?, NOW() )' ); - - $token = $this->random->generate(6, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS); - - $query->execute(array( $email, $token )); - return $token; - } - public function find($email) { - $query = $this->db->prepare('SELECT `email` FROM `*PREFIX*registration` WHERE `email` = ? '); - $query->execute(array($email)); - return $query->fetchAll(); - } - - public function delete($email) { - $query = $this->db->prepare('DELETE FROM `*PREFIX*registration` WHERE `email` = ? '); - return $query->execute(array($email)); - } - - /** - * @return string|false - */ - public function findEmailByToken($token) { - $query = $this->db->prepare('SELECT `email` FROM `*PREFIX*registration` WHERE `token` = ? '); - $query->execute(array($token)); - return $query->fetch()['email']; - } - -} diff --git a/db/registration.php b/db/registration.php new file mode 100644 index 0000000..6798d5f --- /dev/null +++ b/db/registration.php @@ -0,0 +1,39 @@ + + * + * @author Julius Härtl + * + * @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 . + * + */ + +namespace OCA\Registration\Db; + +use OCP\AppFramework\Db\Entity; + +class Registration extends Entity { + + public $id; + protected $email; + protected $token; + protected $requested; + protected $confirmed; + + public function __construct() { + $this->addType('confirmed', 'boolean'); + } +} \ No newline at end of file diff --git a/db/registrationmapper.php b/db/registrationmapper.php new file mode 100644 index 0000000..320cf65 --- /dev/null +++ b/db/registrationmapper.php @@ -0,0 +1,69 @@ + + * + * @author Julius Härtl + * + * @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 . + * + */ + +namespace OCA\Registration\Db; + +use OCP\AppFramework\Db\Mapper; +use OCP\IDBConnection; +use OCP\Security\ISecureRandom; + +class RegistrationMapper extends Mapper { + + /** @var \OCP\Security\ISecureRandom */ + protected $random; + + public function __construct(IDBConnection $db, ISecureRandom $random) { + parent::__construct($db, 'registration', Registration::class); + $this->random = $random; + } + + public function findByToken($token) { + return $this->findEntity('SELECT * FROM `*PREFIX*registration` WHERE `token` = ? ', [$token]); + } + + public function findEmailByToken($token) { + $entity = $this->findByToken($token); + return $entity->getEmail(); + } + + public function find($email) { + $sql = 'SELECT `email` FROM `*PREFIX*registration` WHERE `email` = ? '; + return $this->findEntity($sql, [$email]); + } + + public function deleteByEmail($email) { + $entity = $this->findEntity('SELECT * FROM `*PREFIX*registration` WHERE `email` = ?', [$email]); + return $this->delete($entity); + } + + public function save($email) { + $token = $this->random->generate(6, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS); + $registration = new Registration(); + $registration->setEmail($email); + $registration->setToken($token); + $registration->setRequested(date('Y-m-d H:i:s')); + return $this->insert($registration); + + } + +} \ No newline at end of file diff --git a/service/registrationexception.php b/service/registrationexception.php new file mode 100644 index 0000000..48d6e2c --- /dev/null +++ b/service/registrationexception.php @@ -0,0 +1,42 @@ + + * + * @author Julius Härtl + * + * @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 . + * + */ + +namespace OCA\Registration\Service; + +class RegistrationException extends \Exception { + + protected $hint; + + public function __construct($message, $hint = "") { + parent::__construct($message); + $this->setHint($hint); + } + + public function setHint($hint) { + $this->hint = $hint; + } + + public function getHint() { + return $this->hint; + } +} \ No newline at end of file diff --git a/service/registrationservice.php b/service/registrationservice.php new file mode 100644 index 0000000..1c90ae2 --- /dev/null +++ b/service/registrationservice.php @@ -0,0 +1,342 @@ + + * + * @author Julius Härtl + * + * @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 . + * + */ + +namespace OCA\Registration\Service; + +use OCA\Registration\Db\RegistrationMapper; +use OCP\AppFramework\Db\DoesNotExistException; +use \OCP\AppFramework\Http\TemplateResponse; +use \OCP\AppFramework\Http\RedirectResponse; +use \OCP\Defaults; +use OCP\ILogger; +use OCP\IRequest; +use OCP\IURLGenerator; +use \OCP\Util; +use \OCP\IUserManager; +use \OCP\IUserSession; +use \OCP\IGroupManager; +use \OCP\IL10N; +use \OCP\IConfig; +use \OCP\Mail\IMailer; +use \OCP\Security\ISecureRandom; +use \OC_User; +use \OC_Util; + +class RegistrationService { + + /** @var IMailer */ + private $mailer; + /** @var IL10N */ + private $l10n; + /** @var IURLGenerator */ + private $urlGenerator; + /** @var RegistrationMapper */ + private $registrationMapper; + /** @var IUserManager */ + private $userManager; + /** @var IConfig */ + private $config; + /** @var IGroupManager */ + private $groupManager; + /** @var \OCP\Defaults */ + private $defaults; + /** @var ISecureRandom */ + private $random; + /** @var IUserSession */ + private $usersession; + /** @var string */ + private $appName; + /** @var IRequest */ + private $request; + /** @var ILogger */ + private $logger; + + public function __construct($appName, IMailer $mailer, IL10N $l10n, IURLGenerator $urlGenerator, + RegistrationMapper $registrationMapper, IUserManager $userManager, IConfig $config, IGroupManager $groupManager, Defaults $defaults, + ISecureRandom $random, IUserSession $us, IRequest $request, ILogger $logger){ + $this->mailer = $mailer; + $this->l10n = $l10n; + $this->urlGenerator = $urlGenerator; + $this->registrationMapper = $registrationMapper; + $this->userManager = $userManager; + $this->config = $config; + $this->groupManager = $groupManager; + $this->defaults = $defaults; + $this->random = $random; + $this->usersession = $us; + $this->appName = $appName; + $this->request = $request; + $this->logger = $logger; + } + + + public function validateEmail($email) { + + if ( !$this->mailer->validateMailAddress($email) ) { + throw new RegistrationException($this->l10n->t('The email address you entered is not valid')); + } + + try { + $registration = $this->registrationMapper->find($email); + } catch (\Exception $e) { + $registration = null; + } + // check if email already tried to register + if ( $registration !== null) { + $this->registrationMapper->delete($registration); + $this->generateToken($email); + throw new RegistrationException($this->l10n->t('There is already a pending registration with this email, a new verification email has been sent to the address.')); + } + + if ( $this->config->getUsersForUserValue('settings', 'email', $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 log in now.', [$this->urlGenerator->getAbsoluteURL('/')]) + ); + } + + // allow only from specific email domain} + if (!$this->checkAllowedDomains($email)) { + $allowed_domains = $this->config->getAppValue($this->appName, 'allowed_domains', ''); + $allowed_domains = explode(';', $allowed_domains); + return new TemplateResponse('registration', 'domains', [ + 'domains' => $allowed_domains + ], 'guest'); + } + + $this->generateToken($email); + + return null; + + } + + public function generateToken($email) { + try { + $registration = $this->registrationMapper->find($email); + $this->registrationMapper->delete($registration); + } catch (\Exception $exception) {} + $registration = $this->registrationMapper->save($email); + + try { + $this->sendValidationEmail($registration->getToken(), $email); + } catch (\Exception $e) { + throw new RegistrationException($this->l10n->t('A problem occurred sending email, please contact your administrator.')); + } + } + + /** + * check if email domain is allowed + * + * @param $email + * @return bool + */ + public function checkAllowedDomains($email) { + $allowed_domains = $this->config->getAppValue($this->appName, 'allowed_domains', ''); + if ( $allowed_domains !== '' ) { + $allowed_domains = explode(';', $allowed_domains); + $allowed = false; + foreach ($allowed_domains as $domain) { + $maildomain = explode("@", $email)[1]; + // valid domain, everythings fine + if ($maildomain === $domain) { + $allowed = true; + break; + } + } + return $allowed; + } + return true; + } + + /** + * @param $token + * @return string + * @throws RegistrationException + */ + public function verifyToken($token) { + try { + return $this->registrationMapper->findByToken($token); + } catch (DoesNotExistException $exception) { + throw new RegistrationException($this->l10n->t('Invalid verification URL. No registration request with this verification URL is found.')); + } + } + + + public function createAccount($token, $username, $password) { + $email = $this->registrationMapper->findEmailByToken($token); + if ( $email === false ) { + throw new RegistrationException($this->l10n->t('Invalid verification URL. No registration request with this verification URL is found.')); + } + + $user = $this->userManager->createUser($username, $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 { + $this->config->setUserValue($userId, 'settings', 'email', $email); + } catch (\Exception $e) { + throw new RegistrationException($this->l10n->t('Unable to set user email: ' . $e->getMessage())); + } + + // Add user to group + $registered_user_group = $this->config->getAppValue($this->appName, 'registered_user_group', 'none'); + if ( $registered_user_group !== 'none' ) { + try { + $group = $this->groupManager->get($registered_user_group); + $group->addUser($user); + } catch (\Exception $e) { + throw new RegistrationException($e->getMessage()); + } + } + + // Delete pending reg request + $res = $this->registrationMapper->deleteByEmail($email); + if ($res === false) { + throw new RegistrationException($this->l10n->t('Failed to delete pending registration request')); + } + + $this->notifyAdmins($userId); + + $this->loginUser($userId, $username, $password); + + } + + public function loginUser($userId, $username, $password) { + if ( method_exists($this->usersession, 'createSessionToken') ) { + $this->usersession->login($username, $password); + $this->usersession->createSessionToken($this->request, $userId, $username, $password); + return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index')); + } elseif (OC_User::login($username, $password)) { + $this->cleanupLoginTokens($userId); + // FIXME unsetMagicInCookie will fail from session already closed, so now we always remember + $logintoken = $this->random->generate(32); + $this->config->setUserValue($userId, 'login_token', $logintoken, time()); + OC_User::setMagicInCookie($userId, $logintoken); + OC_Util::redirectToDefaultPage(); + } + // Render message in case redirect failed + return new TemplateResponse('registration', 'message', + ['msg' => $this->l10n->t('Your account has been successfully created, you can log in now.'), [$this->urlGenerator->getAbsoluteURL('/')]] + , 'guest' + ); + + } + + public function notifyAdmins($userId) { + // Notify admin + $admin_users = $this->groupManager->get('admin')->getUsers(); + $to_arr = array(); + foreach ( $admin_users as $au ) { + $au_email = $this->config->getUserValue($au->getUID(), 'settings', 'email'); + if ( $au_email !== '' ) { + $to_arr[$au_email] = $au->getDisplayName(); + } + } + try { + $this->sendNewUserNotifEmail($to_arr, $userId); + } catch (\Exception $e) { + $this->logger->error('Sending admin notification email failed: '. $e->getMessage()); + } + } + + /** + * Sends validation email + * @param string $token + * @param string $to + * @throws \Exception + */ + private function sendValidationEmail($token, $to) { + $link = $this->urlGenerator->linkToRoute('registration.register.verifyToken', array('token' => $token)); + $link = $this->urlGenerator->getAbsoluteURL($link); + $template_var = [ + 'link' => $link, + 'sitename' => $this->defaults->getName() + ]; + $html_template = new TemplateResponse('registration', 'email.validate_html', $template_var, 'blank'); + $html_part = $html_template->render(); + $plaintext_template = new TemplateResponse('registration', 'email.validate_plaintext', $template_var, 'blank'); + $plaintext_part = $plaintext_template->render(); + $subject = $this->l10n->t('Verify your %s registration request', [$this->defaults->getName()]); + + $from = Util::getDefaultEmailAddress('register'); + $message = $this->mailer->createMessage(); + $message->setFrom([$from => $this->defaults->getName()]); + $message->setTo([$to]); + $message->setSubject($subject); + $message->setPlainBody($plaintext_part); + $message->setHtmlBody($html_part); + $failed_recipients = $this->mailer->send($message); + if ( !empty($failed_recipients) ) + throw new RegistrationException('Failed recipients: '.print_r($failed_recipients, true)); + } + + /** + * Sends new user notification email to admin + * @param array $to + * @param string $username the new user + * @throws \Exception + */ + private function sendNewUserNotifEmail(array $to, $username) { + $template_var = [ + 'user' => $username, + 'sitename' => $this->defaults->getName() + ]; + $html_template = new TemplateResponse('registration', 'email.newuser_html', $template_var, 'blank'); + $html_part = $html_template->render(); + $plaintext_template = new TemplateResponse('registration', 'email.newuser_plaintext', $template_var, 'blank'); + $plaintext_part = $plaintext_template->render(); + $subject = $this->l10n->t('A new user "%s" has created an account on %s', [$username, $this->defaults->getName()]); + + $from = Util::getDefaultEmailAddress('register'); + $message = $this->mailer->createMessage(); + $message->setFrom([$from => $this->defaults->getName()]); + $message->setTo($to); + $message->setSubject($subject); + $message->setPlainBody($plaintext_part); + $message->setHtmlBody($html_part); + $failed_recipients = $this->mailer->send($message); + if ( !empty($failed_recipients) ) + throw new RegistrationException('Failed recipients: '.print_r($failed_recipients, true)); + } + + /** + * Replicates OC::cleanupLoginTokens() since it's protected + * @param string $userId + */ + public function cleanupLoginTokens($userId) { + $cutoff = time() - $this->config->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15); + $tokens = $this->config->getUserKeys($userId, 'login_token'); + foreach ($tokens as $token) { + $time = $this->config->getUserValue($userId, 'login_token', $token); + if ($time < $cutoff) { + $this->config->deleteUserValue($userId, 'login_token', $token); + } + } + } + + public function getRegistrationForToken($token) { + return $this->registrationMapper->findByToken($token); + } +}