public function save($email)
 {
     $query = $this->db->prepareQuery('INSERT INTO `*PREFIX*registration`' . ' ( `email`, `token`, `requested` ) VALUES( ?, ?, NOW() )');
     $token = $this->random->generate(30);
     $query->execute(array($email, $token));
     return $token;
 }
Пример #2
0
 public function testCreateCredentials()
 {
     $this->jobList->expects($this->once())->method('add')->with('OCA\\UpdateNotification\\ResetTokenBackgroundJob');
     $this->secureRandom->expects($this->once())->method('generate')->with(64)->willReturn('MyGeneratedToken');
     $this->config->expects($this->once())->method('setSystemValue')->with('updater.secret');
     $this->timeFactory->expects($this->once())->method('getTime')->willReturn(12345);
     $this->config->expects($this->once())->method('setAppValue')->with('core', 'updater.secret.created', 12345);
     $expected = new DataResponse('MyGeneratedToken');
     $this->assertEquals($expected, $this->adminController->createCredentials());
 }
Пример #3
0
 /**
  * @return DataResponse
  */
 public function createCredentials()
 {
     // Create a new job and store the creation date
     $this->jobList->add('OCA\\UpdateNotification\\ResetTokenBackgroundJob');
     $this->config->setAppValue('core', 'updater.secret.created', $this->timeFactory->getTime());
     // Create a new token
     $newToken = $this->secureRandom->generate(64);
     $this->config->setSystemValue('updater.secret', password_hash($newToken, PASSWORD_DEFAULT));
     return new DataResponse($newToken);
 }
Пример #4
0
 /**
  * add server to the list of trusted ownCloud servers
  *
  * @param $url
  * @return int server id
  */
 public function addServer($url)
 {
     $url = $this->updateProtocol($url);
     $result = $this->dbHandler->addServer($url);
     if ($result) {
         $token = $this->secureRandom->generate(16);
         $this->dbHandler->addToken($url, $token);
         $this->jobList->add('OCA\\Federation\\BackgroundJob\\RequestSharedSecret', ['url' => $url, 'token' => $token]);
     }
     return $result;
 }
Пример #5
0
 /**
  * Encrypts a value and adds an HMAC (Encrypt-Then-MAC)
  * @param string $plaintext
  * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  * @return string Authenticated ciphertext
  */
 public function encrypt($plaintext, $password = '')
 {
     if ($password === '') {
         $password = $this->config->getSystemValue('secret');
     }
     $this->cipher->setPassword($password);
     $iv = $this->random->getLowStrengthGenerator()->generate($this->ivLength);
     $this->cipher->setIV($iv);
     $ciphertext = bin2hex($this->cipher->encrypt($plaintext));
     $hmac = bin2hex($this->calculateHMAC($ciphertext . $iv, $password));
     return $ciphertext . '|' . $iv . '|' . $hmac;
 }
Пример #6
0
 /**
  * @param string $user
  * @throws \Exception
  */
 protected function sendEmail($user)
 {
     if (!$this->userManager->userExists($user)) {
         throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
     }
     $email = $this->config->getUserValue($user, 'settings', 'email');
     if (empty($email)) {
         throw new \Exception($this->l10n->t('Couldn\'t send reset email because there is no ' . 'email address for this username. Please ' . 'contact your administrator.'));
     }
     $token = $this->secureRandom->getMediumStrengthGenerator()->generate(21, ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER);
     $this->config->setUserValue($user, 'owncloud', 'lostpassword', $token);
     $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
     $tmpl = new \OC_Template('core/lostpassword', 'email');
     $tmpl->assign('link', $link, false);
     $msg = $tmpl->fetchPage();
     try {
         $message = $this->mailer->createMessage();
         $message->setTo([$email => $user]);
         $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
         $message->setPlainBody($msg);
         $message->setFrom([$this->from => $this->defaults->getName()]);
         $this->mailer->send($message);
     } catch (\Exception $e) {
         throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please contact your administrator.'));
     }
 }
Пример #7
0
 /**
  * @param IConfig $config
  * @param ICrypto $crypto
  * @param ISecureRandom $random
  * @param IRequest $request
  */
 public function __construct(IConfig $config, ICrypto $crypto, ISecureRandom $random, IRequest $request)
 {
     $this->crypto = $crypto;
     $this->config = $config;
     $this->random = $random;
     if (!is_null($request->getCookie(self::COOKIE_NAME))) {
         $this->passphrase = $request->getCookie(self::COOKIE_NAME);
     } else {
         $this->passphrase = $this->random->getMediumStrengthGenerator()->generate(128);
         $secureCookie = $request->getServerProtocol() === 'https';
         // FIXME: Required for CI
         if (!defined('PHPUNIT_RUN')) {
             setcookie(self::COOKIE_NAME, $this->passphrase, 0, \OC::$WEBROOT, '', $secureCookie, true);
         }
     }
 }
 /**
  * Return a 20 digit device password
  *
  * Example: ABCDE-FGHIJ-KLMNO-PQRST
  *
  * @return string
  */
 private function generateRandomDeviceToken()
 {
     $groups = [];
     for ($i = 0; $i < 4; $i++) {
         $groups[] = $this->random->generate(5, implode('', range('A', 'Z')));
     }
     return implode('-', $groups);
 }
Пример #9
0
 public function testGetIdWithoutModUnique()
 {
     $lowRandomSource = $this->getMockBuilder('\\OCP\\Security\\ISecureRandom')->disableOriginalConstructor()->getMock();
     $lowRandomSource->expects($this->once())->method('generate')->with('20')->will($this->returnValue('GeneratedByOwnCloudItself'));
     $this->secureRandom->expects($this->once())->method('getLowStrengthGenerator')->will($this->returnValue($lowRandomSource));
     $request = new Request([], $this->secureRandom, $this->getMock('\\OCP\\Security\\ICrypto'), $this->config, $this->stream);
     $this->assertSame('GeneratedByOwnCloudItself', $request->getId());
 }
Пример #10
0
 /**
  * Share a path
  *
  * @param \OCP\Share\IShare $share
  * @return Share The share object
  * @throws \Exception
  *
  * TODO: handle link share permissions or check them
  */
 public function createShare(\OCP\Share\IShare $share)
 {
     if (!$this->canShare($share)) {
         throw new \Exception('The Share API is disabled');
     }
     $this->generalCreateChecks($share);
     //Verify share type
     if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
         $this->userCreateChecks($share);
     } else {
         if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
             $this->groupCreateChecks($share);
         } else {
             if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
                 $this->linkCreateChecks($share);
                 $this->setLinkParent($share);
                 /*
                  * For now ignore a set token.
                  */
                 $share->setToken($this->secureRandom->generate(\OC\Share\Constants::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER . \OCP\Security\ISecureRandom::CHAR_DIGITS));
                 //Verify the expiration date
                 $this->validateExpirationDate($share);
                 //Verify the password
                 $this->verifyPassword($share->getPassword());
                 // If a password is set. Hash it!
                 if ($share->getPassword() !== null) {
                     $share->setPassword($this->hasher->hash($share->getPassword()));
                 }
             }
         }
     }
     // Verify if there are any issues with the path
     $this->pathCreateChecks($share->getNode());
     // On creation of a share the owner is always the owner of the path
     $share->setShareOwner($share->getNode()->getOwner()->getUID());
     // Cannot share with the owner
     if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() === $share->getShareOwner()) {
         throw new \InvalidArgumentException('Can\'t share with the share owner');
     }
     // Generate the target
     $target = $this->config->getSystemValue('share_folder', '/') . '/' . $share->getNode()->getName();
     $target = \OC\Files\Filesystem::normalizePath($target);
     $share->setTarget($target);
     // Pre share hook
     $run = true;
     $error = '';
     $preHookData = ['itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'shareType' => $share->getShareType(), 'uidOwner' => $share->getSharedBy(), 'permissions' => $share->getPermissions(), 'fileSource' => $share->getNode()->getId(), 'expiration' => $share->getExpirationDate(), 'token' => $share->getToken(), 'itemTarget' => $share->getTarget(), 'shareWith' => $share->getSharedWith(), 'run' => &$run, 'error' => &$error];
     \OC_Hook::emit('OCP\\Share', 'pre_shared', $preHookData);
     if ($run === false) {
         throw new \Exception($error);
     }
     $provider = $this->factory->getProviderForType($share->getShareType());
     $share = $provider->create($share);
     // Post share hook
     $postHookData = ['itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'shareType' => $share->getShareType(), 'uidOwner' => $share->getSharedBy(), 'permissions' => $share->getPermissions(), 'fileSource' => $share->getNode()->getId(), 'expiration' => $share->getExpirationDate(), 'token' => $share->getToken(), 'id' => $share->getId(), 'shareWith' => $share->getSharedWith(), 'itemTarget' => $share->getTarget(), 'fileTarget' => $share->getTarget()];
     \OC_Hook::emit('OCP\\Share', 'post_shared', $postHookData);
     return $share;
 }
Пример #11
0
 /**
  * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
  * If `mod_unique_id` is installed this value will be taken.
  * @return string
  */
 public function getId()
 {
     if (isset($this->server['UNIQUE_ID'])) {
         return $this->server['UNIQUE_ID'];
     }
     if (empty($this->requestId)) {
         $this->requestId = $this->secureRandom->getLowStrengthGenerator()->generate(20);
     }
     return $this->requestId;
 }
Пример #12
0
 /**
  * create shared secret and return it
  *
  * @return \OC_OCS_Result
  */
 public function getSharedSecret()
 {
     $url = $this->request->getParam('url');
     $token = $this->request->getParam('token');
     if ($this->trustedServers->isTrustedServer($url) === false || $this->isValidToken($url, $token) === false) {
         return new \OC_OCS_Result(null, HTTP::STATUS_FORBIDDEN);
     }
     $sharedSecret = $this->secureRandom->getMediumStrengthGenerator()->generate(32);
     $this->trustedServers->addSharedSecret($url, $sharedSecret);
     // reset token after the exchange of the shared secret was successful
     $this->dbHandler->addToken($url, '');
     return new \OC_OCS_Result(['sharedSecret' => $sharedSecret], Http::STATUS_OK);
 }
Пример #13
0
 /**
  * @NoAdminRequired
  *
  * @param string $enable	'true' if the feed is enabled
  * @return DataResponse
  */
 public function feed($enable)
 {
     $token = $tokenUrl = '';
     if ($enable === 'true') {
         $conflicts = true;
         // Check for collisions
         while (!empty($conflicts)) {
             $token = $this->random->generate(30);
             $conflicts = $this->config->getUsersForUserValue('activity', 'rsstoken', $token);
         }
         $tokenUrl = $this->urlGenerator->linkToRouteAbsolute('activity.Feed.show', ['token' => $token]);
     }
     $this->config->setUserValue($this->user, 'activity', 'rsstoken', $token);
     return new DataResponse(array('data' => array('message' => (string) $this->l10n->t('Your settings have been updated.'), 'rsslink' => $tokenUrl)));
 }
Пример #14
0
 /**
  * create shared secret and return it
  *
  * @return \OC_OCS_Result
  */
 public function getSharedSecret()
 {
     $url = $this->request->getParam('url');
     $token = $this->request->getParam('token');
     if ($this->trustedServers->isTrustedServer($url) === false) {
         $this->logger->log(\OCP\Util::ERROR, 'remote server not trusted (' . $url . ') while getting shared secret');
         return new \OC_OCS_Result(null, HTTP::STATUS_FORBIDDEN);
     }
     if ($this->isValidToken($url, $token) === false) {
         $this->logger->log(\OCP\Util::ERROR, 'remote server (' . $url . ') didn\'t send a valid token (got ' . $token . ') while getting shared secret');
         return new \OC_OCS_Result(null, HTTP::STATUS_FORBIDDEN);
     }
     $sharedSecret = $this->secureRandom->generate(32);
     $this->trustedServers->addSharedSecret($url, $sharedSecret);
     // reset token after the exchange of the shared secret was successful
     $this->dbHandler->addToken($url, '');
     return new \OC_OCS_Result(['sharedSecret' => $sharedSecret], Http::STATUS_OK);
 }
Пример #15
0
 public function testCreateShareLink()
 {
     $manager = $this->createManagerMock()->setMethods(['canShare', 'generalCreateChecks', 'linkCreateChecks', 'pathCreateChecks', 'validateExpirationDate', 'verifyPassword', 'setLinkParent'])->getMock();
     $shareOwner = $this->getMock('\\OCP\\IUser');
     $shareOwner->method('getUID')->willReturn('shareOwner');
     $storage = $this->getMock('\\OCP\\Files\\Storage');
     $path = $this->getMock('\\OCP\\Files\\File');
     $path->method('getOwner')->willReturn($shareOwner);
     $path->method('getName')->willReturn('target');
     $path->method('getId')->willReturn(1);
     $path->method('getStorage')->willReturn($storage);
     $date = new \DateTime();
     $share = $this->manager->newShare();
     $share->setShareType(\OCP\Share::SHARE_TYPE_LINK)->setNode($path)->setSharedBy('sharedBy')->setPermissions(\OCP\Constants::PERMISSION_ALL)->setExpirationDate($date)->setPassword('password');
     $manager->expects($this->once())->method('canShare')->with($share)->willReturn(true);
     $manager->expects($this->once())->method('generalCreateChecks')->with($share);
     $manager->expects($this->once())->method('linkCreateChecks')->with($share);
     $manager->expects($this->once())->method('pathCreateChecks')->with($path);
     $manager->expects($this->once())->method('validateExpirationDate')->with($share);
     $manager->expects($this->once())->method('verifyPassword')->with('password');
     $manager->expects($this->once())->method('setLinkParent')->with($share);
     $this->hasher->expects($this->once())->method('hash')->with('password')->willReturn('hashed');
     $this->secureRandom->method('getMediumStrengthGenerator')->will($this->returnSelf());
     $this->secureRandom->method('generate')->willReturn('token');
     $this->defaultProvider->expects($this->once())->method('create')->with($share)->will($this->returnCallback(function (Share $share) {
         return $share->setId(42);
     }));
     $hookListner = $this->getMockBuilder('Dummy')->setMethods(['pre', 'post'])->getMock();
     \OCP\Util::connectHook('OCP\\Share', 'pre_shared', $hookListner, 'pre');
     \OCP\Util::connectHook('OCP\\Share', 'post_shared', $hookListner, 'post');
     $hookListnerExpectsPre = ['itemType' => 'file', 'itemSource' => 1, 'shareType' => \OCP\Share::SHARE_TYPE_LINK, 'uidOwner' => 'sharedBy', 'permissions' => 31, 'fileSource' => 1, 'expiration' => $date, 'token' => 'token', 'run' => true, 'error' => '', 'itemTarget' => '/target', 'shareWith' => null];
     $hookListnerExpectsPost = ['itemType' => 'file', 'itemSource' => 1, 'shareType' => \OCP\Share::SHARE_TYPE_LINK, 'uidOwner' => 'sharedBy', 'permissions' => 31, 'fileSource' => 1, 'expiration' => $date, 'token' => 'token', 'id' => 42, 'itemTarget' => '/target', 'fileTarget' => '/target', 'shareWith' => null];
     $hookListner->expects($this->once())->method('pre')->with($this->equalTo($hookListnerExpectsPre));
     $hookListner->expects($this->once())->method('post')->with($this->equalTo($hookListnerExpectsPost));
     /** @var IShare $share */
     $share = $manager->createShare($share);
     $this->assertSame('shareOwner', $share->getShareOwner());
     $this->assertEquals('/target', $share->getTarget());
     $this->assertSame($date, $share->getExpirationDate());
     $this->assertEquals('token', $share->getToken());
     $this->assertEquals('hashed', $share->getPassword());
 }
Пример #16
0
 /**
  * @param \Doctrine\DBAL\Schema\Table $table
  * @param string $newName
  * @return \Doctrine\DBAL\Schema\Table
  */
 protected function renameTableSchema(Table $table, $newName)
 {
     /**
      * @var \Doctrine\DBAL\Schema\Index[] $indexes
      */
     $indexes = $table->getIndexes();
     $newIndexes = array();
     foreach ($indexes as $index) {
         if ($index->isPrimary()) {
             // do not rename primary key
             $indexName = $index->getName();
         } else {
             // avoid conflicts in index names
             $indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
         }
         $newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
     }
     // foreign keys are not supported so we just set it to an empty array
     return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
 }
Пример #17
0
 /**
  * Generate a new access token clients can authenticate with
  *
  * @PublicPage
  * @NoCSRFRequired
  *
  * @param string $user
  * @param string $password
  * @param string $name the name of the client
  * @return JSONResponse
  */
 public function generateToken($user, $password, $name = 'unknown client')
 {
     if (is_null($user) || is_null($password)) {
         $response = new JSONResponse();
         $response->setStatus(Http::STATUS_UNPROCESSABLE_ENTITY);
         return $response;
     }
     $loginName = $user;
     $user = $this->userManager->checkPassword($loginName, $password);
     if ($user === false) {
         $response = new JSONResponse();
         $response->setStatus(Http::STATUS_UNAUTHORIZED);
         return $response;
     }
     if ($this->twoFactorAuthManager->isTwoFactorAuthenticated($user)) {
         $resp = new JSONResponse();
         $resp->setStatus(Http::STATUS_UNAUTHORIZED);
         return $resp;
     }
     $token = $this->secureRandom->generate(128);
     $this->tokenProvider->generateToken($token, $user->getUID(), $loginName, $password, $name, IToken::PERMANENT_TOKEN);
     return ['token' => $token];
 }
Пример #18
0
 public function testCreateShareLink()
 {
     $manager = $this->getMockBuilder('\\OC\\Share20\\Manager')->setConstructorArgs([$this->logger, $this->config, $this->defaultProvider, $this->secureRandom, $this->hasher, $this->mountManager, $this->groupManager, $this->l])->setMethods(['canShare', 'generalCreateChecks', 'linkCreateChecks', 'pathCreateChecks', 'validateExpiredate', 'verifyPassword'])->getMock();
     $sharedBy = $this->getMock('\\OCP\\IUser');
     $sharedBy->method('getUID')->willReturn('sharedBy');
     $shareOwner = $this->getMock('\\OCP\\IUser');
     $path = $this->getMock('\\OCP\\Files\\File');
     $path->method('getOwner')->willReturn($shareOwner);
     $path->method('getName')->willReturn('target');
     $path->method('getId')->willReturn(1);
     $date = new \DateTime();
     $share = $this->createShare(null, \OCP\Share::SHARE_TYPE_LINK, $path, null, $sharedBy, null, \OCP\Constants::PERMISSION_ALL, $date, 'password');
     $manager->expects($this->once())->method('canShare')->with($share)->willReturn(true);
     $manager->expects($this->once())->method('generalCreateChecks')->with($share);
     $manager->expects($this->once())->method('linkCreateChecks')->with($share);
     $manager->expects($this->once())->method('pathCreateChecks')->with($path);
     $manager->expects($this->once())->method('validateExpiredate')->with($date)->will($this->returnArgument(0));
     $manager->expects($this->once())->method('verifyPassword')->with('password');
     $this->hasher->expects($this->once())->method('hash')->with('password')->willReturn('hashed');
     $this->secureRandom->method('getMediumStrengthGenerator')->will($this->returnSelf());
     $this->secureRandom->method('generate')->willReturn('token');
     $this->defaultProvider->expects($this->once())->method('create')->with($share)->will($this->returnArgument(0));
     $share->expects($this->once())->method('setShareOwner')->with($shareOwner);
     $share->expects($this->once())->method('setTarget')->with('/target');
     $share->expects($this->once())->method('setExpirationDate')->with($date);
     $share->expects($this->once())->method('setPassword')->with('hashed');
     $share->method('getToken')->willReturn('token');
     $hookListner = $this->getMockBuilder('Dummy')->setMethods(['pre', 'post'])->getMock();
     \OCP\Util::connectHook('OCP\\Share', 'pre_shared', $hookListner, 'pre');
     \OCP\Util::connectHook('OCP\\Share', 'post_shared', $hookListner, 'post');
     $hookListnerExpectsPre = ['itemType' => 'file', 'itemSource' => 1, 'shareType' => \OCP\Share::SHARE_TYPE_LINK, 'uidOwner' => 'sharedBy', 'permissions' => 31, 'fileSource' => 1, 'expiration' => $date, 'token' => 'token', 'run' => true, 'error' => ''];
     $hookListnerExpectsPost = ['itemType' => 'file', 'itemSource' => 1, 'shareType' => \OCP\Share::SHARE_TYPE_LINK, 'uidOwner' => 'sharedBy', 'permissions' => 31, 'fileSource' => 1, 'expiration' => $date, 'token' => 'token', 'id' => 42];
     $share->method('getId')->willReturn(42);
     $hookListner->expects($this->once())->method('pre')->with($this->equalTo($hookListnerExpectsPre));
     $hookListner->expects($this->once())->method('post')->with($this->equalTo($hookListnerExpectsPost));
     $manager->createShare($share);
 }
Пример #19
0
 /**
  * generate to token used to authenticate federated shares
  *
  * @return string
  */
 public function generateToken()
 {
     $token = $this->secureRandom->generate(self::TOKEN_LENGTH, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
     return $token;
 }
Пример #20
0
 /**
  * Generate a new CSRF token.
  *
  * @param int $length Length of the token in characters.
  * @return string
  */
 public function generateToken($length = 32)
 {
     return $this->random->generate($length);
 }
Пример #21
0
 /**
  * generate one time password for the user and store it in a array
  *
  * @param string $uid
  * @return string password
  */
 protected function generateOneTimePassword($uid)
 {
     $password = $this->secureRandom->generate(8);
     $this->userPasswords[$uid] = $password;
     return $password;
 }
Пример #22
0
 /**
  * @param $options
  * @return array
  */
 public function install($options)
 {
     $l = $this->l10n;
     $error = array();
     $dbType = $options['dbtype'];
     if (empty($options['adminlogin'])) {
         $error[] = $l->t('Set an admin username.');
     }
     if (empty($options['adminpass'])) {
         $error[] = $l->t('Set an admin password.');
     }
     if (empty($options['directory'])) {
         $options['directory'] = \OC::$SERVERROOT . "/data";
     }
     if (!isset(self::$dbSetupClasses[$dbType])) {
         $dbType = 'sqlite';
     }
     $username = htmlspecialchars_decode($options['adminlogin']);
     $password = htmlspecialchars_decode($options['adminpass']);
     $dataDir = htmlspecialchars_decode($options['directory']);
     $class = self::$dbSetupClasses[$dbType];
     /** @var \OC\Setup\AbstractDatabase $dbSetup */
     $dbSetup = new $class($l, 'db_structure.xml', $this->config, $this->logger, $this->random);
     $error = array_merge($error, $dbSetup->validate($options));
     // validate the data directory
     if (!is_dir($dataDir) and !mkdir($dataDir) or !is_writable($dataDir)) {
         $error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
     }
     if (count($error) != 0) {
         return $error;
     }
     $request = \OC::$server->getRequest();
     //no errors, good
     if (isset($options['trusted_domains']) && is_array($options['trusted_domains'])) {
         $trustedDomains = $options['trusted_domains'];
     } else {
         $trustedDomains = [$request->getInsecureServerHost()];
     }
     if (\OC_Util::runningOnWindows()) {
         $dataDir = rtrim(realpath($dataDir), '\\');
     }
     //use sqlite3 when available, otherwise sqlite2 will be used.
     if ($dbType == 'sqlite' and class_exists('SQLite3')) {
         $dbType = 'sqlite3';
     }
     //generate a random salt that is used to salt the local user passwords
     $salt = $this->random->generate(30);
     // generate a secret
     $secret = $this->random->generate(48);
     //write the config file
     $this->config->setSystemValues(['passwordsalt' => $salt, 'secret' => $secret, 'trusted_domains' => $trustedDomains, 'datadirectory' => $dataDir, 'overwrite.cli.url' => $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT, 'dbtype' => $dbType, 'version' => implode('.', \OCP\Util::getVersion())]);
     try {
         $dbSetup->initialize($options);
         $dbSetup->setupDatabase($username);
     } catch (\OC\DatabaseSetupException $e) {
         $error[] = array('error' => $e->getMessage(), 'hint' => $e->getHint());
         return $error;
     } catch (Exception $e) {
         $error[] = array('error' => 'Error while trying to create admin user: '******'hint' => '');
         return $error;
     }
     //create the user and group
     $user = null;
     try {
         $user = \OC::$server->getUserManager()->createUser($username, $password);
         if (!$user) {
             $error[] = "User <{$username}> could not be created.";
         }
     } catch (Exception $exception) {
         $error[] = $exception->getMessage();
     }
     if (count($error) == 0) {
         $config = \OC::$server->getConfig();
         $config->setAppValue('core', 'installedat', microtime(true));
         $config->setAppValue('core', 'lastupdatedat', microtime(true));
         $group = \OC::$server->getGroupManager()->createGroup('admin');
         $group->addUser($user);
         \OC_User::login($username, $password);
         //guess what this does
         \OC_Installer::installShippedApps();
         // create empty file in data dir, so we can later find
         // out that this is indeed an ownCloud data directory
         file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
         // Update .htaccess files
         Setup::updateHtaccess();
         Setup::protectDataDirectory();
         //try to write logtimezone
         if (date_default_timezone_get()) {
             $config->setSystemValue('logtimezone', date_default_timezone_get());
         }
         //and we are done
         $config->setSystemValue('installed', true);
     }
     return $error;
 }
Пример #23
0
 public function testGenerateTokenWithDefault()
 {
     $this->random->expects($this->once())->method('generate')->with(32)->willReturn('12345678901234567890123456789012');
     $this->assertSame('12345678901234567890123456789012', $this->csrfTokenGenerator->generateToken(32));
 }
Пример #24
0
 public function testGetIdWithoutModUnique()
 {
     $this->secureRandom->expects($this->once())->method('generate')->with('20')->will($this->returnValue('GeneratedByOwnCloudItself'));
     $request = new Request([], $this->secureRandom, $this->config, $this->csrfTokenManager, $this->stream);
     $this->assertSame('GeneratedByOwnCloudItself', $request->getId());
 }