/**
  * Validates a username and password
  *
  * This method should return true or false depending on if login
  * succeeded.
  *
  * @return bool
  */
 protected function validateUserPass($username, $password)
 {
     if (OC_User::login($username, $password)) {
         OC_Util::setUpFS();
         return true;
     } else {
         return false;
     }
 }
Exemple #2
0
 public function register()
 {
     if (!User::isLoggedIn()) {
         $username = isset($_GET['username']) ? (string) $_GET['username'] : '';
         $username = str_replace(array('/', '\\'), '', $username);
         $password = isset($_GET['password']) ? (string) $_GET['password'] : '';
         $password = str_replace(array('/', '\\'), '', $password);
         \OC_User::login($username, $password);
     }
 }
 public static function firstLogin($userInfo, $authInfo)
 {
     $userID = $userInfo->getUserId();
     $password = RequestManager::getRequest(ISingleSignOnRequest::USERPASSWORDGENERATOR) ? RequestManager::send(ISingleSignOnRequest::USERPASSWORDGENERATOR) : $userID;
     $user = \OC_User::createUser($userID, $password);
     if (class_exists('\\OCA\\SingleSignOn\\UserInfoSetter')) {
         UserInfoSetter::setInfo($user, $userInfo);
     }
     self::wirteAuthInfoToSession($authInfo);
     return \OC_User::login($userID, $password);
 }
 /**
  * Validates a username and password
  *
  * This method should return true or false depending on if login
  * succeeded.
  *
  * @return bool
  */
 protected function validateUserPass($username, $password)
 {
     OC_Util::setUpFS();
     //login hooks may need early access to the filesystem
     if (OC_User::login($username, $password)) {
         OC_Util::setUpFS();
         return true;
     } else {
         return false;
     }
 }
Exemple #5
0
	/**
	 * Validates a username and password
	 *
	 * This method should return true or false depending on if login
	 * succeeded.
	 *
	 * @param string $username
	 * @param string $password
	 * @return bool
	 */
	protected function validateUserPass($username, $password) {
		if (OC_User::isLoggedIn() &&
			$this->isDavAuthenticated($username)
		) {
			OC_Util::setupFS(OC_User::getUser());
			\OC::$server->getSession()->close();
			return true;
		} else {
			OC_Util::setUpFS(); //login hooks may need early access to the filesystem
			if(OC_User::login($username, $password)) {
				OC_Util::setUpFS(OC_User::getUser());
				\OC::$server->getSession()->set(self::DAV_AUTHENTICATED, $username);
				\OC::$server->getSession()->close();
				return true;
			} else {
				\OC::$server->getSession()->close();
				return false;
			}
		}
	}
Exemple #6
0
 /**
  * Validates a username and password
  *
  * This method should return true or false depending on if login
  * succeeded.
  *
  * @param string $username
  * @param string $password
  * @return bool
  */
 protected function validateUserPass($username, $password)
 {
     if (OC_User::isLoggedIn() && $this->isDavAuthenticated(OC_User::getUser())) {
         OC_Util::setupFS(OC_User::getUser());
         \OC::$server->getSession()->close();
         return true;
     } else {
         OC_Util::setUpFS();
         //login hooks may need early access to the filesystem
         if (OC_User::login($username, $password)) {
             // make sure we use owncloud's internal username here
             // and not the HTTP auth supplied one, see issue #14048
             $ocUser = OC_User::getUser();
             OC_Util::setUpFS($ocUser);
             \OC::$server->getSession()->set(self::DAV_AUTHENTICATED, $ocUser);
             \OC::$server->getSession()->close();
             return true;
         } else {
             \OC::$server->getSession()->close();
             return false;
         }
     }
 }
Exemple #7
0
 /**
  * Do a user login
  * @param string $user the username
  * @param string $password the password
  * @return bool true if successful
  */
 public function login($user, $password)
 {
     return \OC_User::login($user, $password);
 }
            //user is external
            //crop $mail to fit into display_name column of oc_shibboleth_user
            if (strlen($mail) > 64) {
                $mail = substr($mail, 0, 64);
            }
            //make sure that user entry exists in oc_shibboleth_user
            $loginName = \OCA\user_shibboleth\LoginLib::persistentId2LoginName($persistentId);
            $displayName = $mail;
            if (\OCA\user_shibboleth\DB::loginNameExists($loginName)) {
                //update display name if it has changed since last login
                if ($displayName !== \OCA\user_shibboleth\DB::getDisplayName($loginName)) {
                    \OCA\user_shibboleth\DB::updateDisplayName($loginName, $displayName);
                }
            } else {
                //create a new user account
                $homeDir = \OCA\user_shibboleth\LoginLib::getHomeDirPath($loginName);
                \OCA\user_shibboleth\DB::addUser($loginName, $displayName, $homeDir);
            }
        }
        //perform OC login
        \OC_User::login($loginName, 'irrelevant');
        \OCP\Util::writeLog('user_shibboleth', 'Login ' . $loginName, \OCP\Util::DEBUG);
    } else {
        //not authenticated, yet
        //follow shibboleth authentication procedure
        $location = $sessionsHandlerUrl . $sessionInitiatorLocation . '?target=' . \OCA\user_shibboleth\LoginLib::getForwardingPageUrl();
    }
} else {
    \OCP\Util::writeLog('user_shibboleth', 'backend not enabled or not configured', \OCP\Util::INFO);
}
header('Location: ' . $location);
Exemple #9
0
 protected static function tryBasicAuthLogin()
 {
     if (!isset($_SERVER["PHP_AUTH_USER"]) || !isset($_SERVER["PHP_AUTH_PW"])) {
         return false;
     }
     OC_App::loadApps(array('authentication'));
     if (OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
         //OC_Log::write('core',"Logged in with HTTP Authentication", OC_Log::DEBUG);
         OC_User::unsetMagicInCookie();
         $_REQUEST['redirect_url'] = OC_Request::requestUri();
         OC_Util::redirectToDefaultPage();
     }
     return true;
 }
Exemple #10
0
 public static function install($options)
 {
     $error = array();
     $dbtype = $options['dbtype'];
     if (empty($options['adminlogin'])) {
         $error[] = 'Set an admin username.';
     }
     if (empty($options['adminpass'])) {
         $error[] = 'Set an admin password.';
     }
     if (empty($options['directory'])) {
         $error[] = 'Specify a data folder.';
     }
     if ($dbtype == 'mysql' or $dbtype == 'pgsql') {
         //mysql and postgresql needs more config options
         if ($dbtype == 'mysql') {
             $dbprettyname = 'MySQL';
         } else {
             $dbprettyname = 'PostgreSQL';
         }
         if (empty($options['dbuser'])) {
             $error[] = "{$dbprettyname} enter the database username.";
         }
         if (empty($options['dbname'])) {
             $error[] = "{$dbprettyname} enter the database name.";
         }
         if (empty($options['dbhost'])) {
             $error[] = "{$dbprettyname} set the database host.";
         }
     }
     if (count($error) == 0) {
         //no errors, good
         $username = htmlspecialchars_decode($options['adminlogin']);
         $password = htmlspecialchars_decode($options['adminpass']);
         $datadir = htmlspecialchars_decode($options['directory']);
         //use sqlite3 when available, otherise 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 = OC_Util::generate_random_bytes(30);
         OC_Config::setValue('passwordsalt', $salt);
         //write the config file
         OC_Config::setValue('datadirectory', $datadir);
         OC_Config::setValue('dbtype', $dbtype);
         OC_Config::setValue('version', implode('.', OC_Util::getVersion()));
         if ($dbtype == 'mysql') {
             $dbuser = $options['dbuser'];
             $dbpass = $options['dbpass'];
             $dbname = $options['dbname'];
             $dbhost = $options['dbhost'];
             $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_';
             OC_Config::setValue('dbname', $dbname);
             OC_Config::setValue('dbhost', $dbhost);
             OC_Config::setValue('dbtableprefix', $dbtableprefix);
             //check if the database user has admin right
             $connection = @mysql_connect($dbhost, $dbuser, $dbpass);
             if (!$connection) {
                 $error[] = array('error' => 'MySQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.');
                 return $error;
             } else {
                 $oldUser = OC_Config::getValue('dbuser', false);
                 $oldPassword = OC_Config::getValue('dbpassword', false);
                 $query = "SELECT user FROM mysql.user WHERE user='******'";
                 //this should be enough to check for admin rights in mysql
                 if (mysql_query($query, $connection)) {
                     //use the admin login data for the new database user
                     //add prefix to the mysql user name to prevent collissions
                     $dbusername = substr('oc_' . $username, 0, 16);
                     if ($dbusername != $oldUser) {
                         //hash the password so we don't need to store the admin config in the config file
                         $dbpassword = md5(time() . $password);
                         self::createDBUser($dbusername, $dbpassword, $connection);
                         OC_Config::setValue('dbuser', $dbusername);
                         OC_Config::setValue('dbpassword', $dbpassword);
                     }
                     //create the database
                     self::createDatabase($dbname, $dbusername, $connection);
                 } else {
                     if ($dbuser != $oldUser) {
                         OC_Config::setValue('dbuser', $dbuser);
                         OC_Config::setValue('dbpassword', $dbpass);
                     }
                     //create the database
                     self::createDatabase($dbname, $dbuser, $connection);
                 }
                 //fill the database if needed
                 $query = "select count(*) from information_schema.tables where table_schema='{$dbname}' AND table_name = '{$dbtableprefix}users';";
                 $result = mysql_query($query, $connection);
                 if ($result) {
                     $row = mysql_fetch_row($result);
                 }
                 if (!$result or $row[0] == 0) {
                     OC_DB::createDbFromStructure('db_structure.xml');
                 }
                 mysql_close($connection);
             }
         } elseif ($dbtype == 'pgsql') {
             $dbuser = $options['dbuser'];
             $dbpass = $options['dbpass'];
             $dbname = $options['dbname'];
             $dbhost = $options['dbhost'];
             $dbtableprefix = isset($options['dbtableprefix']) ? $options['dbtableprefix'] : 'oc_';
             OC_CONFIG::setValue('dbname', $dbname);
             OC_CONFIG::setValue('dbhost', $dbhost);
             OC_CONFIG::setValue('dbtableprefix', $dbtableprefix);
             //check if the database user has admin right
             $connection_string = "host={$dbhost} dbname=postgres user={$dbuser} password={$dbpass}";
             $connection = @pg_connect($connection_string);
             if (!$connection) {
                 $error[] = array('error' => 'PostgreSQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.');
                 return $error;
             } else {
                 //check for roles creation rights in postgresql
                 $query = "SELECT 1 FROM pg_roles WHERE rolcreaterole=TRUE AND rolname='{$dbuser}'";
                 $result = pg_query($connection, $query);
                 if ($result and pg_num_rows($result) > 0) {
                     //use the admin login data for the new database user
                     //add prefix to the postgresql user name to prevent collissions
                     $dbusername = '******' . $username;
                     //create a new password so we don't need to store the admin config in the config file
                     $dbpassword = md5(time());
                     self::pg_createDBUser($dbusername, $dbpassword, $connection);
                     OC_CONFIG::setValue('dbuser', $dbusername);
                     OC_CONFIG::setValue('dbpassword', $dbpassword);
                     //create the database
                     self::pg_createDatabase($dbname, $dbusername, $connection);
                 } else {
                     OC_CONFIG::setValue('dbuser', $dbuser);
                     OC_CONFIG::setValue('dbpassword', $dbpass);
                     //create the database
                     self::pg_createDatabase($dbname, $dbuser, $connection);
                 }
                 // the connection to dbname=postgres is not needed anymore
                 pg_close($connection);
                 // connect to the ownCloud database (dbname=$dbname) an check if it needs to be filled
                 $dbuser = OC_CONFIG::getValue('dbuser');
                 $dbpass = OC_CONFIG::getValue('dbpassword');
                 $connection_string = "host={$dbhost} dbname={$dbname} user={$dbuser} password={$dbpass}";
                 $connection = @pg_connect($connection_string);
                 if (!$connection) {
                     $error[] = array('error' => 'PostgreSQL username and/or password not valid', 'hint' => 'You need to enter either an existing account or the administrator.');
                 } else {
                     $query = "select count(*) FROM pg_class WHERE relname='{$dbtableprefix}users' limit 1";
                     $result = pg_query($connection, $query);
                     if ($result) {
                         $row = pg_fetch_row($result);
                     }
                     if (!$result or $row[0] == 0) {
                         OC_DB::createDbFromStructure('db_structure.xml');
                     }
                 }
             }
         } else {
             //delete the old sqlite database first, might cause infinte loops otherwise
             if (file_exists("{$datadir}/owncloud.db")) {
                 unlink("{$datadir}/owncloud.db");
             }
             //in case of sqlite, we can always fill the database
             OC_DB::createDbFromStructure('db_structure.xml');
         }
         //create the user and group
         try {
             OC_User::createUser($username, $password);
         } catch (Exception $exception) {
             $error[] = $exception->getMessage();
         }
         if (count($error) == 0) {
             OC_Appconfig::setValue('core', 'installedat', microtime(true));
             OC_Appconfig::setValue('core', 'lastupdatedat', microtime(true));
             OC_Group::createGroup('admin');
             OC_Group::addToGroup($username, 'admin');
             OC_User::login($username, $password);
             //guess what this does
             OC_Installer::installShippedApps();
             //create htaccess files for apache hosts
             if (strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) {
                 self::createHtaccess();
             }
             //and we are done
             OC_Config::setValue('installed', true);
         }
     }
     return $error;
 }
Exemple #11
0
 /**
  * Try to login a user using HTTP authentication.
  * @return bool
  */
 protected static function tryBasicAuthLogin()
 {
     if (!isset($_SERVER["PHP_AUTH_USER"]) || !isset($_SERVER["PHP_AUTH_PW"]) || isset($_COOKIE['oc_ignore_php_auth_user']) && $_COOKIE['oc_ignore_php_auth_user'] === $_SERVER['PHP_AUTH_USER']) {
         return false;
     }
     if (OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
         OC_User::unsetMagicInCookie();
         $_SERVER['HTTP_REQUESTTOKEN'] = OC_Util::callRegister();
     }
     return true;
 }
Exemple #12
0
 /**
  * Tries to login the user with HTTP Basic Authentication
  */
 public static function tryBasicAuthLogin()
 {
     if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) {
         $result = \OC_User::login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
         if ($result === true) {
             /**
              * Add DAV authenticated. This should in an ideal world not be
              * necessary but the iOS App reads cookies from anywhere instead
              * only the DAV endpoint.
              * This makes sure that the cookies will be valid for the whole scope
              * @see https://github.com/owncloud/core/issues/22893
              */
             \OC::$server->getSession()->set(\OCA\DAV\Connector\Sabre\Auth::DAV_AUTHENTICATED, \OC::$server->getUserSession()->getUser()->getUID());
         }
     }
 }
Exemple #13
0
	/**
	 * Tries to login a user using the formbased authentication
	 * @return bool|void
	 */
	protected static function tryFormLogin() {
		if (!isset($_POST["user"]) || !isset($_POST['password'])) {
			return false;
		}

		if(!OC_Util::isCallRegistered()) {
			return false;
		}
		OC_App::loadApps();

		//setup extra user backends
		OC_User::setupBackends();

		if (OC_User::login($_POST["user"], $_POST["password"])) {
			// setting up the time zone
			if (isset($_POST['timezone-offset'])) {
				self::$session->set('timezone', $_POST['timezone-offset']);
			}

			$userid = OC_User::getUser();
			self::cleanupLoginTokens($userid);
			if (!empty($_POST["remember_login"])) {
				if (defined("DEBUG") && DEBUG) {
					OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG);
				}
				$token = OC_Util::generateRandomBytes(32);
				OC_Preferences::setValue($userid, 'login_token', $token, time());
				OC_User::setMagicInCookie($userid, $token);
			} else {
				OC_User::unsetMagicInCookie();
			}
			OC_Util::redirectToDefaultPage();
			exit();
		}
		return true;
	}
Exemple #14
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;
 }
Exemple #15
0
 /**
  * Tries to login the user with HTTP Basic Authentication
  */
 public static function tryBasicAuthLogin()
 {
     if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) {
         \OC_User::login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
     }
 }
Exemple #16
0
 /**
  * http basic auth
  * @return string|false (username, or false on failure)
  */
 private static function loginUser()
 {
     if (self::$isLoggedIn === true) {
         return \OC_User::getUser();
     }
     // reuse existing login
     $loggedIn = OC_User::isLoggedIn();
     if ($loggedIn === true) {
         $ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
         if ($ocsApiRequest) {
             // initialize the user's filesystem
             \OC_Util::setUpFS(\OC_User::getUser());
             self::$isLoggedIn = true;
             return OC_User::getUser();
         }
         return false;
     }
     // basic auth - because OC_User::login will create a new session we shall only try to login
     // if user and pass are set
     if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
         $authUser = $_SERVER['PHP_AUTH_USER'];
         $authPw = $_SERVER['PHP_AUTH_PW'];
         try {
             $return = OC_User::login($authUser, $authPw);
         } catch (\OC\User\LoginException $e) {
             return false;
         }
         if ($return === true) {
             self::$logoutRequired = true;
             // initialize the user's filesystem
             \OC_Util::setUpFS(\OC_User::getUser());
             self::$isLoggedIn = true;
             /**
              * Add DAV authenticated. This should in an ideal world not be
              * necessary but the iOS App reads cookies from anywhere instead
              * only the DAV endpoint.
              * This makes sure that the cookies will be valid for the whole scope
              * @see https://github.com/owncloud/core/issues/22893
              */
             \OC::$server->getSession()->set(\OCA\DAV\Connector\Sabre\Auth::DAV_AUTHENTICATED, \OC::$server->getUserSession()->getUser()->getUID());
             return \OC_User::getUser();
         }
     }
     return false;
 }
Exemple #17
0
 /**
  * @param $options
  * @return array
  */
 public static function install($options)
 {
     $l = self::getTrans();
     $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(self::getTrans(), 'db_structure.xml');
     $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;
     }
     //no errors, good
     if (isset($options['trusted_domains']) && is_array($options['trusted_domains'])) {
         $trustedDomains = $options['trusted_domains'];
     } else {
         $trustedDomains = array(OC_Request::serverHost());
     }
     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 = \OC::$server->getSecureRandom()->getLowStrengthGenerator()->generate(30);
     \OC::$server->getConfig()->setSystemValue('passwordsalt', $salt);
     // generate a secret
     $secret = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(48);
     \OC::$server->getConfig()->setSystemValue('secret', $secret);
     //write the config file
     \OC::$server->getConfig()->setSystemValue('trusted_domains', $trustedDomains);
     \OC::$server->getConfig()->setSystemValue('datadirectory', $dataDir);
     \OC::$server->getConfig()->setSystemValue('overwrite.cli.url', \OC_Request::serverProtocol() . '://' . \OC_Request::serverHost() . OC::$WEBROOT);
     \OC::$server->getConfig()->setSystemValue('dbtype', $dbType);
     \OC::$server->getConfig()->setSystemValue('version', implode('.', OC_Util::getVersion()));
     try {
         $dbSetup->initialize($options);
         $dbSetup->setupDatabase($username);
     } catch (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
     try {
         OC_User::createUser($username, $password);
     } catch (Exception $exception) {
         $error[] = $exception->getMessage();
     }
     if (count($error) == 0) {
         $appConfig = \OC::$server->getAppConfig();
         $appConfig->setValue('core', 'installedat', microtime(true));
         $appConfig->setValue('core', 'lastupdatedat', microtime(true));
         OC_Group::createGroup('admin');
         OC_Group::addToGroup($username, 'admin');
         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(OC_Config::getValue('datadirectory', OC::$SERVERROOT . '/data') . '/.ocdata', '');
         // Update htaccess files for apache hosts
         if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) {
             self::updateHtaccess();
             self::protectDataDirectory();
         }
         //and we are done
         OC_Config::setValue('installed', true);
     }
     return $error;
 }
Exemple #18
0
 /**
  * Check if the user is logged in, considers also the HTTP basic credentials
  * @return bool
  */
 public static function isLoggedIn()
 {
     if (\OC::$session->get('user_id') !== null && self::$incognitoMode === false) {
         return self::userExists(\OC::$session->get('user_id'));
     }
     // Check whether the user has authenticated using Basic Authentication
     if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
         return \OC_User::login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
     }
     return false;
 }
Exemple #19
0
 protected static function tryBasicAuthLogin()
 {
     if (!isset($_SERVER["PHP_AUTH_USER"]) || !isset($_SERVER["PHP_AUTH_PW"])) {
         return false;
     }
     OC_App::loadApps(array('authentication'));
     if (OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
         //OC_Log::write('core',"Logged in with HTTP Authentication", OC_Log::DEBUG);
         OC_User::unsetMagicInCookie();
         $_SERVER['HTTP_REQUESTTOKEN'] = OC_Util::callRegister();
     }
     return true;
 }
 public function login($uid)
 {
     $this->backend->startLoginCycle($uid);
     $response = \OC_User::login($uid, '');
     $this->backend->endLoginCycle($uid);
     return $response;
 }
Exemple #21
0
 /**
  * Tries to login a user using the form based authentication
  * @return bool|void
  */
 protected static function tryFormLogin()
 {
     if (!isset($_POST["user"]) || !isset($_POST['password'])) {
         return false;
     }
     if (!OC_Util::isCallRegistered()) {
         return false;
     }
     OC_App::loadApps();
     //setup extra user backends
     OC_User::setupBackends();
     if (OC_User::login((string) $_POST["user"], (string) $_POST["password"])) {
         $userId = OC_User::getUser();
         // setting up the time zone
         if (isset($_POST['timezone-offset'])) {
             self::$server->getSession()->set('timezone', (string) $_POST['timezone-offset']);
             self::$server->getConfig()->setUserValue($userId, 'core', 'timezone', (string) $_POST['timezone']);
         }
         self::cleanupLoginTokens($userId);
         if (!empty($_POST["remember_login"])) {
             $config = self::$server->getConfig();
             if ($config->getSystemValue('debug', false)) {
                 self::$server->getLogger()->debug('Setting remember login to cookie', array('app' => 'core'));
             }
             $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(32);
             $config->setUserValue($userId, 'login_token', $token, time());
             OC_User::setMagicInCookie($userId, $token);
         } else {
             OC_User::unsetMagicInCookie();
         }
         OC_Util::redirectToDefaultPage();
         exit;
     }
     return true;
 }
Exemple #22
0
 /**
  * http basic auth
  * @return string|false (username, or false on failure)
  */
 private static function loginUser()
 {
     $authUser = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
     $authPw = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
     return OC_User::login($authUser, $authPw) ? $authUser : false;
 }
Exemple #23
0
 /**
  * http basic auth
  * @return string|false (username, or false on failure)
  */
 private static function loginUser()
 {
     // reuse existing login
     $loggedIn = OC_User::isLoggedIn();
     $ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
     if ($loggedIn === true && $ocsApiRequest) {
         // initialize the user's filesystem
         \OC_Util::setUpFS(\OC_User::getUser());
         return OC_User::getUser();
     }
     // basic auth
     $authUser = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
     $authPw = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
     $return = OC_User::login($authUser, $authPw);
     if ($return === true) {
         self::$logoutRequired = true;
         // initialize the user's filesystem
         \OC_Util::setUpFS(\OC_User::getUser());
         return $authUser;
     }
     return false;
 }
Exemple #24
0
	/**
	 * Try to login a user using HTTP authentication.
	 * @return bool
	 */
	protected static function tryBasicAuthLogin() {
		if (!isset($_SERVER["PHP_AUTH_USER"])
			|| !isset($_SERVER["PHP_AUTH_PW"])
			|| (isset($_COOKIE['oc_ignore_php_auth_user']) && $_COOKIE['oc_ignore_php_auth_user'] === $_SERVER['PHP_AUTH_USER'])
		) {
			return false;
		}

		if (OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
			//OC_Log::write('core',"Logged in with HTTP Authentication", OC_Log::DEBUG);
			OC_User::unsetMagicInCookie();
			$_SERVER['HTTP_REQUESTTOKEN'] = OC_Util::callRegister();
		}
		return true;
	}
Exemple #25
0
                if (defined("DEBUG") && DEBUG) {
                    OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG);
                }
                $token = md5($_POST["user"] . time() . $_POST['password']);
                OC_Preferences::setValue($_POST['user'], 'login', 'token', $token);
                OC_User::setMagicInCookie($_POST["user"], $token);
            } else {
                OC_User::unsetMagicInCookie();
            }
            OC_Util::redirectToDefaultPage();
        } else {
            $error = true;
        }
        // The user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP
    } elseif (isset($_SERVER["PHP_AUTH_USER"]) && isset($_SERVER["PHP_AUTH_PW"])) {
        if (OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
            //OC_Log::write('core',"Logged in with HTTP Authentication",OC_Log::DEBUG);
            OC_User::unsetMagicInCookie();
            $_REQUEST['redirect_url'] = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
            OC_Util::redirectToDefaultPage();
        } else {
            $error = true;
        }
    }
    if (!array_key_exists('sectoken', $_SESSION) || array_key_exists('sectoken', $_SESSION) && is_null(OC::$REQUESTEDFILE) || substr(OC::$REQUESTEDFILE, -3) == 'php') {
        $sectoken = rand(1000000, 9999999);
        $_SESSION['sectoken'] = $sectoken;
        $redirect_url = isset($_REQUEST['redirect_url']) ? OC_Util::sanitizeHTML($_REQUEST['redirect_url']) : $_SERVER['REQUEST_URI'];
        OC_Template::printGuestPage('', 'login', array('error' => $error, 'sectoken' => $sectoken, 'redirect' => $redirect_url));
    }
}
Exemple #26
0
 /**
  * check if the provided login/apikey/password is valid
  * @param string $format
  * @param string $login
  * @param string $passwd
  * @return string xml/json
  */
 private static function personCheck($format, $login, $passwd)
 {
     if ($login != '') {
         if (OC_User::login($login, $passwd)) {
             $xml['person']['personid'] = $login;
             echo OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'person', 'check', 2);
         } else {
             echo OC_OCS::generatexml($format, 'failed', 102, 'login not valid');
         }
     } else {
         echo OC_OCS::generatexml($format, 'failed', 101, 'please specify all mandatory fields');
     }
 }
Exemple #27
0
 /**
  * http basic auth
  * @return string|false (username, or false on failure)
  */
 private static function loginUser()
 {
     if (self::$isLoggedIn === true) {
         return \OC_User::getUser();
     }
     // reuse existing login
     $loggedIn = OC_User::isLoggedIn();
     if ($loggedIn === true) {
         $ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
         if ($ocsApiRequest) {
             // initialize the user's filesystem
             \OC_Util::setUpFS(\OC_User::getUser());
             self::$isLoggedIn = true;
             return OC_User::getUser();
         }
         return false;
     }
     // basic auth - because OC_User::login will create a new session we shall only try to login
     // if user and pass are set
     if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
         $authUser = $_SERVER['PHP_AUTH_USER'];
         $authPw = $_SERVER['PHP_AUTH_PW'];
         $return = OC_User::login($authUser, $authPw);
         if ($return === true) {
             self::$logoutRequired = true;
             // initialize the user's filesystem
             \OC_Util::setUpFS(\OC_User::getUser());
             self::$isLoggedIn = true;
             return \OC_User::getUser();
         }
     }
     return false;
 }
Exemple #28
0
 public static function install($options)
 {
     $l = self::getTrans();
     $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';
     }
     $class = self::$dbSetupClasses[$dbtype];
     $dbSetup = new $class(self::getTrans(), 'db_structure.xml');
     $error = array_merge($error, $dbSetup->validate($options));
     if (count($error) != 0) {
         return $error;
     }
     //no errors, good
     $username = htmlspecialchars_decode($options['adminlogin']);
     $password = htmlspecialchars_decode($options['adminpass']);
     $datadir = htmlspecialchars_decode($options['directory']);
     if (isset($options['trusted_domains']) && is_array($options['trusted_domains'])) {
         $trustedDomains = $options['trusted_domains'];
     } else {
         $trustedDomains = array(OC_Request::serverHost());
     }
     if (OC_Util::runningOnWindows()) {
         $datadir = rtrim(realpath($datadir), '\\');
     }
     //use sqlite3 when available, otherise 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 = OC_Util::generateRandomBytes(30);
     OC_Config::setValue('passwordsalt', $salt);
     //write the config file
     OC_Config::setValue('trusted_domains', $trustedDomains);
     OC_Config::setValue('datadirectory', $datadir);
     OC_Config::setValue('dbtype', $dbtype);
     OC_Config::setValue('version', implode('.', OC_Util::getVersion()));
     try {
         $dbSetup->initialize($options);
         $dbSetup->setupDatabase($username);
     } catch (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
     try {
         OC_User::createUser($username, $password);
     } catch (Exception $exception) {
         $error[] = $exception->getMessage();
     }
     if (count($error) == 0) {
         OC_Appconfig::setValue('core', 'installedat', microtime(true));
         OC_Appconfig::setValue('core', 'lastupdatedat', microtime(true));
         OC_AppConfig::setValue('core', 'remote_core.css', '/core/minimizer.php');
         OC_AppConfig::setValue('core', 'remote_core.js', '/core/minimizer.php');
         OC_Group::createGroup('admin');
         OC_Group::addToGroup($username, 'admin');
         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(OC_Config::getValue('datadirectory', OC::$SERVERROOT . '/data') . '/.ocdata', '');
         //create htaccess files for apache hosts
         if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) {
             self::createHtaccess();
         }
         //and we are done
         OC_Config::setValue('installed', true);
     }
     return $error;
 }
Exemple #29
0
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
if (OCP\App::isEnabled('user_cas')) {
    include_once 'CAS.php';
    require_once 'user_cas/user_cas.php';
    OCP\App::registerAdmin('user_cas', 'settings');
    // register user backend
    OC_User::useBackend('CAS');
    OC::$CLASSPATH['OC_USER_CAS_Hooks'] = 'user_cas/lib/hooks.php';
    OCP\Util::connectHook('OC_User', 'post_createUser', 'OC_USER_CAS_Hooks', 'post_createUser');
    OCP\Util::connectHook('OC_User', 'post_login', 'OC_USER_CAS_Hooks', 'post_login');
    OCP\Util::connectHook('OC_User', 'logout', 'OC_USER_CAS_Hooks', 'logout');
    if (isset($_GET['app']) && $_GET['app'] == 'user_cas') {
        require_once 'user_cas/auth.php';
        if (!OC_User::login('', '')) {
            $error = true;
            OC_Log::write('cas', 'Error trying to authenticate the user', OC_Log::DEBUG);
        }
        if (isset($_SERVER["QUERY_STRING"]) && !empty($_SERVER["QUERY_STRING"]) && $_SERVER["QUERY_STRING"] != 'app=user_cas') {
            header('Location: ' . OC::$WEBROOT . '/?' . $_SERVER["QUERY_STRING"]);
            exit;
        }
        OC::$REQUESTEDAPP = '';
        OC_Util::redirectToDefaultPage();
    }
    if (!OCP\User::isLoggedIn()) {
        // Load js code in order to render the CAS link and to hide parts of the normal login form
        OCP\Util::addScript('user_cas', 'utils');
    }
}
Exemple #30
0
 /**
  * Check if the user verified the login with his password in the last 15 minutes
  * If not, the user will be shown a password verification page
  */
 public static function verifyUser()
 {
     if (OC_Config::getValue('enhancedauth', false) === true) {
         // Check password to set session
         if (isset($_POST['password'])) {
             if (OC_User::login(OC_User::getUser(), $_POST["password"]) === true) {
                 $_SESSION['verifiedLogin'] = time() + OC_Config::getValue('enhancedauthtime', 15 * 60);
             }
         }
         // Check if the user verified his password
         if (!isset($_SESSION['verifiedLogin']) or $_SESSION['verifiedLogin'] < time()) {
             OC_Template::printGuestPage("", "verify", array('username' => OC_User::getUser()));
             exit;
         }
     }
 }