Exemple #1
0
 public static function sendEmail($args)
 {
     if (OC_User::userExists($_POST['user'])) {
         $token = hash('sha256', OC_Util::generate_random_bytes(30) . OC_Config::getValue('passwordsalt', ''));
         OC_Preferences::setValue($_POST['user'], 'owncloud', 'lostpassword', hash('sha256', $token));
         // Hash the token again to prevent timing attacks
         $email = OC_Preferences::getValue($_POST['user'], 'settings', 'email', '');
         if (!empty($email)) {
             $link = OC_Helper::linkToRoute('core_lostpassword_reset', array('user' => $_POST['user'], 'token' => $token));
             $link = OC_Helper::makeURLAbsolute($link);
             $tmpl = new OC_Template('core/lostpassword', 'email');
             $tmpl->assign('link', $link, false);
             $msg = $tmpl->fetchPage();
             $l = OC_L10N::get('core');
             $from = 'lostpassword-noreply@' . OCP\Util::getServerHost();
             OC_Mail::send($email, $_POST['user'], $l->t('ownCloud password reset'), $msg, $from, 'ownCloud');
             echo 'Mailsent';
             self::displayLostPasswordPage(false, true);
         } else {
             self::displayLostPasswordPage(true, false);
         }
     } else {
         self::displayLostPasswordPage(true, false);
     }
 }
Exemple #2
0
 public static function sendEmail($args)
 {
     $isEncrypted = OC_App::isEnabled('files_encryption');
     if (!$isEncrypted || isset($_POST['continue'])) {
         $continue = true;
     } else {
         $continue = false;
     }
     if (OC_User::userExists($_POST['user']) && $continue) {
         $token = hash('sha256', OC_Util::generate_random_bytes(30) . OC_Config::getValue('passwordsalt', ''));
         OC_Preferences::setValue($_POST['user'], 'owncloud', 'lostpassword', hash('sha256', $token));
         // Hash the token again to prevent timing attacks
         $email = OC_Preferences::getValue($_POST['user'], 'settings', 'email', '');
         if (!empty($email)) {
             $link = OC_Helper::linkToRoute('core_lostpassword_reset', array('user' => $_POST['user'], 'token' => $token));
             $link = OC_Helper::makeURLAbsolute($link);
             $tmpl = new OC_Template('core/lostpassword', 'email');
             $tmpl->assign('link', $link, false);
             $msg = $tmpl->fetchPage();
             $l = OC_L10N::get('core');
             $from = OCP\Util::getDefaultEmailAddress('lostpassword-noreply');
             try {
                 OC_Mail::send($email, $_POST['user'], $l->t('ownCloud password reset'), $msg, $from, 'ownCloud');
             } catch (Exception $e) {
                 OC_Template::printErrorPage('A problem occurs during sending the e-mail please contact your administrator.');
             }
             self::displayLostPasswordPage(false, true);
         } else {
             self::displayLostPasswordPage(true, false);
         }
     } else {
         self::displayLostPasswordPage(true, false);
     }
 }
 /**
  * Share an item, adds an entry into the database
  * @param $source The source location of the item
  * @param $uid_shared_with The user or group to share the item with
  * @param $permissions The permissions, use the constants WRITE and DELETE
  */
 public function __construct($source, $uid_shared_with, $permissions)
 {
     $uid_owner = OC_User::getUser();
     $query = OC_DB::prepare("INSERT INTO *PREFIX*sharing VALUES(?,?,?,?,?)");
     if ($uid_shared_with == self::PUBLICLINK) {
         $token = sha1("{$uid_shared_with}-{$source}");
         $query->execute(array($uid_owner, self::PUBLICLINK, $source, $token, $permissions));
         $this->token = $token;
     } else {
         if (OC_Group::groupExists($uid_shared_with)) {
             $gid = $uid_shared_with;
             $uid_shared_with = OC_Group::usersInGroup($gid);
             // Remove the owner from the list of users in the group
             $uid_shared_with = array_diff($uid_shared_with, array($uid_owner));
         } else {
             if (OC_User::userExists($uid_shared_with)) {
                 $gid = null;
                 $uid_shared_with = array($uid_shared_with);
             } else {
                 throw new Exception($uid_shared_with . " is not a user");
             }
         }
         foreach ($uid_shared_with as $uid) {
             // Check if this item is already shared with the user
             $checkSource = OC_DB::prepare("SELECT source FROM *PREFIX*sharing WHERE source = ? AND uid_shared_with " . self::getUsersAndGroups($uid));
             $resultCheckSource = $checkSource->execute(array($source, $uid))->fetchAll();
             // TODO Check if the source is inside a folder
             if (count($resultCheckSource) > 0 && !isset($gid)) {
                 throw new Exception("This item is already shared with " . $uid);
             }
             // Check if the target already exists for the user, if it does append a number to the name
             $sharedFolder = "/" . $uid . "/files/Shared";
             $target = $sharedFolder . "/" . basename($source);
             if (self::getSource($target)) {
                 if ($pos = strrpos($target, ".")) {
                     $name = substr($target, 0, $pos);
                     $ext = substr($target, $pos);
                 } else {
                     $name = $target;
                     $ext = "";
                 }
                 $counter = 1;
                 while ($checkTarget !== false) {
                     $newTarget = $name . "_" . $counter . $ext;
                     $checkTarget = self::getSource($newTarget);
                     $counter++;
                 }
                 $target = $newTarget;
             }
             if (isset($gid)) {
                 $uid = $uid . "@" . $gid;
             }
             $query->execute(array($uid_owner, $uid, $source, $target, $permissions));
             // Clear the folder size cache for the 'Shared' folder
             $clearFolderSize = OC_DB::prepare("DELETE FROM *PREFIX*foldersize WHERE path = ?");
             $clearFolderSize->execute(array($sharedFolder));
         }
     }
 }
 /**
  * Returns a specific principal, specified by it's path.
  * The returned structure should be the exact same as from
  * getPrincipalsByPrefix.
  *
  * @param string $path
  * @return array
  */
 public function getPrincipalByPath($path)
 {
     list($prefix, $name) = explode('/', $path);
     if ($prefix == 'principals' && OC_User::userExists($name)) {
         return array('uri' => 'principals/' . $name, '{DAV:}displayname' => $name);
     }
     return null;
 }
Exemple #5
0
 public static function post_login($parameters)
 {
     $uid = $parameters['uid'];
     $samlBackend = new OC_USER_SAML();
     if ($samlBackend->auth->isAuthenticated()) {
         $attributes = $samlBackend->auth->getAttributes();
         if (array_key_exists($samlBackend->usernameMapping, $attributes) && $attributes[$samlBackend->usernameMapping][0] == $uid) {
             $attributes = $samlBackend->auth->getAttributes();
             if (array_key_exists($samlBackend->mailMapping, $attributes)) {
                 $saml_email = $attributes[$samlBackend->mailMapping][0];
             }
             if (array_key_exists($samlBackend->groupMapping, $attributes)) {
                 $saml_groups = $attributes[$samlBackend->groupMapping];
             } else {
                 if (!empty($samlBackend->defaultGroup)) {
                     $saml_groups = array($samlBackend->defaultGroup);
                     OC_Log::write('saml', 'Using default group "' . $samlBackend->defaultGroup . '" for the user: '******'/[^a-zA-Z0-9 _\\.@\\-]/', $uid)) {
                     OC_Log::write('saml', 'Invalid username "' . $uid . '", allowed chars "a-zA-Z0-9" and "_.@-" ', OC_Log::DEBUG);
                     return false;
                 } else {
                     $random_password = random_password();
                     OC_Log::write('saml', 'Creating new user: '******'saml', 'Updating data of the user: ' . $uid, OC_Log::DEBUG);
                     if (isset($saml_email)) {
                         update_mail($uid, $saml_email);
                     }
                     if (isset($saml_groups)) {
                         update_groups($uid, $saml_groups, $samlBackend->protectedGroups, false);
                     }
                 }
             }
             return true;
         }
     }
     return false;
 }
Exemple #6
0
 /**
  * Returns a specific principal, specified by it's path.
  * The returned structure should be the exact same as from
  * getPrincipalsByPrefix.
  *
  * @param string $path
  * @return array
  */
 public function getPrincipalByPath($path)
 {
     list($prefix, $name) = explode('/', $path);
     if ($prefix == 'principals' && OC_User::userExists($name)) {
         $principal = array('uri' => 'principals/' . $name, '{DAV:}displayname' => $name);
         $email = \OCP\Config::getUserValue($user, 'settings', 'email');
         if ($email) {
             $principal['{http://sabredav.org/ns}email-address'] = $email;
         }
         return $principal;
     }
     return null;
 }
 protected function loginWithEncryption($user = '')
 {
     \OC_Util::tearDownFS();
     \OC_User::setUserId('');
     // needed for fully logout
     \OC::$server->getUserSession()->setUser(null);
     Filesystem::tearDown();
     \OC_User::setUserId($user);
     $this->postLogin();
     \OC_Util::setupFS($user);
     if (\OC_User::userExists($user)) {
         \OC::$server->getUserFolder($user);
     }
 }
Exemple #8
0
 public static function getUserPrivatekey($parameters)
 {
     $user = OC_User::getUser();
     if (OC_User::isAdminUser($user) or $user == $parameters['user']) {
         if (OC_User::userExists($user)) {
             // calculate the disc space
             $txt = 'this is the private key of ' . $parameters['user'];
             echo $txt;
         } else {
             return new OC_OCS_Result(null, 300, 'User does not exist');
         }
     } else {
         return new OC_OCS_Result('null', 300, 'You don´t have permission to access this ressource.');
     }
 }
Exemple #9
0
 public function testGetUserOnNonExistingUser()
 {
     $user = $this->generateUsers();
     \OC_Group::addToGroup($user, 'admin');
     self::loginAsUser($user);
     $params = array();
     $params['userid'] = $this->getUniqueID();
     while (\OC_User::userExists($params['userid'])) {
         $params['userid'] = $this->getUniqueID();
     }
     $result = \OCA\provisioning_API\Users::getUser($params);
     $this->assertInstanceOf('OC_OCS_Result', $result);
     $this->assertFalse($result->succeeded());
     $this->assertEquals(\OCP\API::RESPOND_NOT_FOUND, $result->getStatusCode());
 }
 public static function webDavLogin($userID, $password)
 {
     $config = \OC::$server->getSystemConfig();
     RequestManager::init($config->getValue("sso_portal_url"), $config->getValue("sso_requests"));
     $authInfo = WebDavAuthInfo::get($userID, $password);
     $userInfo = RequestManager::getRequest(ISingleSignOnRequest::INFO);
     $userInfo->setup(array("action" => "webDavLogin"));
     if (!$userInfo->send($authInfo)) {
         return;
     }
     if ($config->getValue("sso_multiple_region")) {
         self::redirectRegion($userInfo, $config->getValue("sso_regions"), $config->getValue("sso_owncloud_url"));
     }
     if (!\OC_User::userExists($userInfo->getUserId())) {
         return self::firstLogin($userInfo, $authInfo);
     }
     if ($authInfo) {
         return self::login($userInfo, $authInfo);
     }
     return false;
 }
Exemple #11
0
 /**
  * gets user info
  *
  * exposes the quota of an user:
  * <data>
  *   <quota>
  *      <free>1234</free>
  *      <used>4321</used>
  *      <total>5555</total>
  *      <ralative>0.78</ralative>
  *   </quota>
  * </data>
  *
  * @param array $parameters should contain parameter 'userid' which identifies
  *                          the user from whom the information will be returned
  */
 public static function getUser($parameters)
 {
     $return = array();
     // Check if they are viewing information on themselves
     if ($parameters['userid'] === OC_User::getUser()) {
         // Self lookup
         $storage = OC_Helper::getStorageInfo('/');
         $return['quota'] = array('free' => $storage['free'], 'used' => $storage['used'], 'total' => $storage['total'], 'relative' => $storage['relative']);
     }
     if (OC_User::isAdminUser(OC_User::getUser()) || OC_Subadmin::isUserAccessible(OC_User::getUser(), $parameters['userid'])) {
         if (OC_User::userExists($parameters['userid'])) {
             // Is an admin/subadmin so can see display name
             $return['displayname'] = OC_User::getDisplayName($parameters['userid']);
         } else {
             return new OC_OCS_Result(null, 101);
         }
     }
     if (count($return)) {
         return new OC_OCS_Result($return);
     } else {
         // No permission to view this user data
         return new OC_OCS_Result(null, 997);
     }
 }
Exemple #12
0
 protected static function tryRememberLogin()
 {
     if (!isset($_COOKIE["oc_remember_login"]) || !isset($_COOKIE["oc_token"]) || !isset($_COOKIE["oc_username"]) || !$_COOKIE["oc_remember_login"]) {
         return false;
     }
     OC_App::loadApps(array('authentication'));
     if (defined("DEBUG") && DEBUG) {
         OC_Log::write('core', 'Trying to login from cookie', OC_Log::DEBUG);
     }
     // confirm credentials in cookie
     if (isset($_COOKIE['oc_token']) && OC_User::userExists($_COOKIE['oc_username'])) {
         // delete outdated cookies
         self::cleanupLoginTokens($_COOKIE['oc_username']);
         // get stored tokens
         $tokens = OC_Preferences::getKeys($_COOKIE['oc_username'], 'login_token');
         // test cookies token against stored tokens
         if (in_array($_COOKIE['oc_token'], $tokens, true)) {
             // replace successfully used token with a new one
             OC_Preferences::deleteKey($_COOKIE['oc_username'], 'login_token', $_COOKIE['oc_token']);
             $token = OC_Util::generate_random_bytes(32);
             OC_Preferences::setValue($_COOKIE['oc_username'], 'login_token', $token, time());
             OC_User::setMagicInCookie($_COOKIE['oc_username'], $token);
             // login
             OC_User::setUserId($_COOKIE['oc_username']);
             OC_Util::redirectToDefaultPage();
             // doesn't return
         }
         // if you reach this point you have changed your password
         // or you are an attacker
         // we can not delete tokens here because users may reach
         // this point multiple times after a password change
         OC_Log::write('core', 'Authentication cookie rejected for user ' . $_COOKIE['oc_username'], OC_Log::WARN);
     }
     OC_User::unsetMagicInCookie();
     return true;
 }
 /**
  * @brief Add a user to a group
  * @param $uid Name of the user to add to group
  * @param $gid Name of the group in which add the user
  * @returns true/false
  *
  * Adds a user to a group.
  */
 public static function addToGroup($uid, $gid)
 {
     // Does the user exist?
     if (!OC_User::userExists($uid)) {
         return false;
     }
     // Does the group exist?
     if (!OC_Group::groupExists($gid)) {
         return false;
     }
     // Go go go
     $run = true;
     OC_Hook::emit("OC_Group", "pre_addToGroup", array("run" => &$run, "uid" => $uid, "gid" => $gid));
     if ($run && self::$_backend->addToGroup($uid, $gid)) {
         OC_Hook::emit("OC_Group", "post_addToGroup", array("uid" => $uid, "gid" => $gid));
         return true;
     } else {
         return false;
     }
 }
Exemple #14
0
 /**
  * Share an item with a user, group, or via private link
  * @param string $itemType
  * @param string $itemSource
  * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  * @param string $shareWith User or group the item is being shared with
  * @param int $permissions CRUDS
  * @param string $itemSourceName
  * @param \DateTime $expirationDate
  * @return boolean|string Returns true on success or false on failure, Returns token on success for links
  * @throws \Exception
  */
 public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null)
 {
     $uidOwner = \OC_User::getUser();
     $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
     $l = \OC_L10N::get('lib');
     if (is_null($itemSourceName)) {
         $itemSourceName = $itemSource;
     }
     // check if file can be shared
     if ($itemType === 'file' or $itemType === 'folder') {
         $path = \OC\Files\Filesystem::getPath($itemSource);
         // verify that the file exists before we try to share it
         if (!$path) {
             $message = 'Sharing %s failed, because the file does not exist';
             $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
         // verify that the user has share permission
         if (!\OC\Files\Filesystem::isSharable($path)) {
             $message = 'You are not allowed to share %s';
             $message_t = $l->t('You are not allowed to share %s', array($itemSourceName));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
     }
     //verify that we don't share a folder which already contains a share mount point
     if ($itemType === 'folder') {
         $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
         $mountManager = \OC\Files\Filesystem::getMountManager();
         $mounts = $mountManager->findIn($path);
         foreach ($mounts as $mount) {
             if ($mount->getStorage()->instanceOfStorage('\\OCA\\Files_Sharing\\ISharedStorage')) {
                 $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
     }
     // single file shares should never have delete permissions
     if ($itemType === 'file') {
         $permissions = (int) $permissions & ~\OCP\PERMISSION_DELETE;
     }
     // Verify share type and sharing conditions are met
     if ($shareType === self::SHARE_TYPE_USER) {
         if ($shareWith == $uidOwner) {
             $message = 'Sharing %s failed, because the user %s is the item owner';
             $message_t = $l->t('Sharing %s failed, because the user %s is the item owner', array($itemSourceName, $shareWith));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
         if (!\OC_User::userExists($shareWith)) {
             $message = 'Sharing %s failed, because the user %s does not exist';
             $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
         if ($shareWithinGroupOnly) {
             $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
             if (empty($inGroup)) {
                 $message = 'Sharing %s failed, because the user ' . '%s is not a member of any groups that %s is a member of';
                 $message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', array($itemSourceName, $shareWith, $uidOwner));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith, $uidOwner), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
         }
         // Check if the item source is already shared with the user, either from the same owner or a different user
         if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
             // Only allow the same share to occur again if it is the same
             // owner and is not a user share, this use case is for increasing
             // permissions for a specific user
             if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                 $message = 'Sharing %s failed, because this item is already shared with %s';
                 $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
         }
     } else {
         if ($shareType === self::SHARE_TYPE_GROUP) {
             if (!\OC_Group::groupExists($shareWith)) {
                 $message = 'Sharing %s failed, because the group %s does not exist';
                 $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
             if ($shareWithinGroupOnly && !\OC_Group::inGroup($uidOwner, $shareWith)) {
                 $message = 'Sharing %s failed, because ' . '%s is not a member of the group %s';
                 $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
             // Check if the item source is already shared with the group, either from the same owner or a different user
             // The check for each user in the group is done inside the put() function
             if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
                 // Only allow the same share to occur again if it is the same
                 // owner and is not a group share, this use case is for increasing
                 // permissions for a specific user
                 if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                     $message = 'Sharing %s failed, because this item is already shared with %s';
                     $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                     \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
                     throw new \Exception($message_t);
                 }
             }
             // Convert share with into an array with the keys group and users
             $group = $shareWith;
             $shareWith = array();
             $shareWith['group'] = $group;
             $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
         } else {
             if ($shareType === self::SHARE_TYPE_LINK) {
                 $updateExistingShare = false;
                 if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
                     // when updating a link share
                     // FIXME Don't delete link if we update it
                     if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1)) {
                         // remember old token
                         $oldToken = $checkExists['token'];
                         $oldPermissions = $checkExists['permissions'];
                         //delete the old share
                         Helper::delete($checkExists['id']);
                         $updateExistingShare = true;
                     }
                     // Generate hash of password - same method as user passwords
                     if (!empty($shareWith)) {
                         $forcePortable = CRYPT_BLOWFISH != 1;
                         $hasher = new \PasswordHash(8, $forcePortable);
                         $shareWith = $hasher->HashPassword($shareWith . \OC_Config::getValue('passwordsalt', ''));
                     } else {
                         // reuse the already set password, but only if we change permissions
                         // otherwise the user disabled the password protection
                         if ($checkExists && (int) $permissions !== (int) $oldPermissions) {
                             $shareWith = $checkExists['share_with'];
                         }
                     }
                     if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
                         $message = 'You need to provide a password to create a public link, only protected links are allowed';
                         $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
                         \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                         throw new \Exception($message_t);
                     }
                     if ($updateExistingShare === false && self::isDefaultExpireDateEnabled() && empty($expirationDate)) {
                         $expirationDate = Helper::calcExpireDate();
                     }
                     // Generate token
                     if (isset($oldToken)) {
                         $token = $oldToken;
                     } else {
                         $token = \OC_Util::generateRandomBytes(self::TOKEN_LENGTH);
                     }
                     $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName, $expirationDate);
                     if ($result) {
                         return $token;
                     } else {
                         return false;
                     }
                 }
                 $message = 'Sharing %s failed, because sharing with links is not allowed';
                 $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
                 throw new \Exception($message_t);
                 return false;
             } else {
                 // Future share types need to include their own conditions
                 $message = 'Share type %s is not valid for %s';
                 $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
                 \OC_Log::write('OCP\\Share', sprintf($message, $shareType, $itemSource), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
         }
     }
     // Put the item into the database
     return self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
 }
Exemple #15
0
 /**
  * Share an item with a user, group, or via private link
  * @param string $itemType
  * @param string $itemSource
  * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  * @param string $shareWith User or group the item is being shared with
  * @param int $permissions CRUDS
  * @param string $itemSourceName
  * @param \DateTime $expirationDate
  * @param bool $passwordChanged
  * @return boolean|string Returns true on success or false on failure, Returns token on success for links
  * @throws \OC\HintException when the share type is remote and the shareWith is invalid
  * @throws \Exception
  */
 public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null)
 {
     $backend = self::getBackend($itemType);
     $l = \OC::$server->getL10N('lib');
     if ($backend->isShareTypeAllowed($shareType) === false) {
         $message = 'Sharing %s failed, because the backend does not allow shares from type %i';
         $message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
         \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
         throw new \Exception($message_t);
     }
     $uidOwner = \OC_User::getUser();
     $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
     if (is_null($itemSourceName)) {
         $itemSourceName = $itemSource;
     }
     $itemName = $itemSourceName;
     // check if file can be shared
     if ($itemType === 'file' or $itemType === 'folder') {
         $path = \OC\Files\Filesystem::getPath($itemSource);
         $itemName = $path;
         // verify that the file exists before we try to share it
         if (!$path) {
             $message = 'Sharing %s failed, because the file does not exist';
             $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
             \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
             throw new \Exception($message_t);
         }
         // verify that the user has share permission
         if (!\OC\Files\Filesystem::isSharable($path)) {
             $message = 'You are not allowed to share %s';
             $message_t = $l->t('You are not allowed to share %s', [$path]);
             \OCP\Util::writeLog('OCP\\Share', sprintf($message, $path), \OCP\Util::DEBUG);
             throw new \Exception($message_t);
         }
     }
     //verify that we don't share a folder which already contains a share mount point
     if ($itemType === 'folder') {
         $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
         $mountManager = \OC\Files\Filesystem::getMountManager();
         $mounts = $mountManager->findIn($path);
         foreach ($mounts as $mount) {
             if ($mount->getStorage()->instanceOfStorage('\\OCA\\Files_Sharing\\ISharedStorage')) {
                 $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
                 \OCP\Util::writeLog('OCP\\Share', $message, \OCP\Util::DEBUG);
                 throw new \Exception($message);
             }
         }
     }
     // single file shares should never have delete permissions
     if ($itemType === 'file') {
         $permissions = (int) $permissions & ~\OCP\Constants::PERMISSION_DELETE;
     }
     //Validate expirationDate
     if ($expirationDate !== null) {
         try {
             /*
              * Reuse the validateExpireDate.
              * We have to pass time() since the second arg is the time
              * the file was shared, since it is not shared yet we just use
              * the current time.
              */
             $expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
         } catch (\Exception $e) {
             throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
         }
     }
     // Verify share type and sharing conditions are met
     if ($shareType === self::SHARE_TYPE_USER) {
         if ($shareWith == $uidOwner) {
             $message = 'Sharing %s failed, because you can not share with yourself';
             $message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
             \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
             throw new \Exception($message_t);
         }
         if (!\OC_User::userExists($shareWith)) {
             $message = 'Sharing %s failed, because the user %s does not exist';
             $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
             \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
             throw new \Exception($message_t);
         }
         if ($shareWithinGroupOnly) {
             $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
             if (empty($inGroup)) {
                 $message = 'Sharing %s failed, because the user ' . '%s is not a member of any groups that %s is a member of';
                 $message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', array($itemName, $shareWith, $uidOwner));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             }
         }
         // Check if the item source is already shared with the user, either from the same owner or a different user
         if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
             // Only allow the same share to occur again if it is the same
             // owner and is not a user share, this use case is for increasing
             // permissions for a specific user
             if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                 $message = 'Sharing %s failed, because this item is already shared with %s';
                 $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             }
         }
         if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
             // Only allow the same share to occur again if it is the same
             // owner and is not a user share, this use case is for increasing
             // permissions for a specific user
             if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                 $message = 'Sharing %s failed, because this item is already shared with user %s';
                 $message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
                 throw new \Exception($message_t);
             }
         }
     } else {
         if ($shareType === self::SHARE_TYPE_GROUP) {
             if (!\OC_Group::groupExists($shareWith)) {
                 $message = 'Sharing %s failed, because the group %s does not exist';
                 $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             }
             if ($shareWithinGroupOnly && !\OC_Group::inGroup($uidOwner, $shareWith)) {
                 $message = 'Sharing %s failed, because ' . '%s is not a member of the group %s';
                 $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             }
             // Check if the item source is already shared with the group, either from the same owner or a different user
             // The check for each user in the group is done inside the put() function
             if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
                 // Only allow the same share to occur again if it is the same
                 // owner and is not a group share, this use case is for increasing
                 // permissions for a specific user
                 if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                     $message = 'Sharing %s failed, because this item is already shared with %s';
                     $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                     \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
                     throw new \Exception($message_t);
                 }
             }
             // Convert share with into an array with the keys group and users
             $group = $shareWith;
             $shareWith = array();
             $shareWith['group'] = $group;
             $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
         } else {
             if ($shareType === self::SHARE_TYPE_LINK) {
                 $updateExistingShare = false;
                 if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
                     // when updating a link share
                     // FIXME Don't delete link if we update it
                     if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1)) {
                         // remember old token
                         $oldToken = $checkExists['token'];
                         $oldPermissions = $checkExists['permissions'];
                         //delete the old share
                         Helper::delete($checkExists['id']);
                         $updateExistingShare = true;
                     }
                     if ($passwordChanged === null) {
                         // Generate hash of password - same method as user passwords
                         if (is_string($shareWith) && $shareWith !== '') {
                             self::verifyPassword($shareWith);
                             $shareWith = \OC::$server->getHasher()->hash($shareWith);
                         } else {
                             // reuse the already set password, but only if we change permissions
                             // otherwise the user disabled the password protection
                             if ($checkExists && (int) $permissions !== (int) $oldPermissions) {
                                 $shareWith = $checkExists['share_with'];
                             }
                         }
                     } else {
                         if ($passwordChanged === true) {
                             if (is_string($shareWith) && $shareWith !== '') {
                                 self::verifyPassword($shareWith);
                                 $shareWith = \OC::$server->getHasher()->hash($shareWith);
                             }
                         } else {
                             if ($updateExistingShare) {
                                 $shareWith = $checkExists['share_with'];
                             }
                         }
                     }
                     if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
                         $message = 'You need to provide a password to create a public link, only protected links are allowed';
                         $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
                         \OCP\Util::writeLog('OCP\\Share', $message, \OCP\Util::DEBUG);
                         throw new \Exception($message_t);
                     }
                     if ($updateExistingShare === false && self::isDefaultExpireDateEnabled() && empty($expirationDate)) {
                         $expirationDate = Helper::calcExpireDate();
                     }
                     // Generate token
                     if (isset($oldToken)) {
                         $token = $oldToken;
                     } else {
                         $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
                     }
                     $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName, $expirationDate);
                     if ($result) {
                         return $token;
                     } else {
                         return false;
                     }
                 }
                 $message = 'Sharing %s failed, because sharing with links is not allowed';
                 $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
                 \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
                 throw new \Exception($message_t);
             } else {
                 if ($shareType === self::SHARE_TYPE_REMOTE) {
                     /*
                      * Check if file is not already shared with the remote user
                      */
                     if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE, $shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
                         $message = 'Sharing %s failed, because this item is already shared with %s';
                         $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                         \OCP\Util::writeLog('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
                         throw new \Exception($message_t);
                     }
                     $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER . \OCP\Security\ISecureRandom::CHAR_DIGITS);
                     list($user, $remote) = Helper::splitUserRemote($shareWith);
                     $shareWith = $user . '@' . $remote;
                     $shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
                     $send = false;
                     if ($shareId) {
                         $send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
                     }
                     if ($send === false) {
                         $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
                         self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
                         $message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
                         throw new \Exception($message_t);
                     }
                     return $send;
                 } else {
                     // Future share types need to include their own conditions
                     $message = 'Share type %s is not valid for %s';
                     $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
                     \OCP\Util::writeLog('OCP\\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
                     throw new \Exception($message_t);
                 }
             }
         }
     }
     // Put the item into the database
     $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
     return $result ? true : false;
 }
Exemple #16
0
 /**
  * Try to login a user using the remember me cookie.
  * @return bool Whether the provided cookie was valid
  */
 protected static function tryRememberLogin()
 {
     if (!isset($_COOKIE["oc_remember_login"]) || !isset($_COOKIE["oc_token"]) || !isset($_COOKIE["oc_username"]) || !$_COOKIE["oc_remember_login"] || !OC_Util::rememberLoginAllowed()) {
         return false;
     }
     if (\OC::$server->getConfig()->getSystemValue('debug', false)) {
         \OCP\Util::writeLog('core', 'Trying to login from cookie', \OCP\Util::DEBUG);
     }
     if (OC_User::userExists($_COOKIE['oc_username'])) {
         self::cleanupLoginTokens($_COOKIE['oc_username']);
         // verify whether the supplied "remember me" token was valid
         $granted = OC_User::loginWithCookie($_COOKIE['oc_username'], $_COOKIE['oc_token']);
         if ($granted === true) {
             OC_Util::redirectToDefaultPage();
             // doesn't return
         }
         \OCP\Util::writeLog('core', 'Authentication cookie rejected for user ' . $_COOKIE['oc_username'], \OCP\Util::WARN);
         // if you reach this point you have changed your password
         // or you are an attacker
         // we can not delete tokens here because users may reach
         // this point multiple times after a password change
     }
     OC_User::unsetMagicInCookie();
     return true;
 }
Exemple #17
0
 /**
  * Check if a user exists
  * @param string $uid the username
  * @param string $excludingBackend (default none)
  * @return boolean
  */
 public static function userExists($uid, $excludingBackend = null)
 {
     return \OC_User::userExists($uid, $excludingBackend);
 }
Exemple #18
0
<?php

# Create local user account.
#
# Author: Jakub T. Moscicki, 2013, CERN/IT
#
# License: AGPL
#
# To be placed and run on the owncloud application server:
#
#  php -f create_user.php USER PASSWORD
#
# Example: create test accounts
#
#   for i in {1..100}; do sudo -u apache php -f create_user.php test`printf "%03d\n" $i` "password" ; done
#
set_include_path(get_include_path() . PATH_SEPARATOR . '/var/www/html/owncloud');
require_once 'lib/base.php';
$login = $argv[1];
if (OC_User::userExists($login)) {
    print "user account exists:" . $login . "\n";
    exit(0);
} else {
    print "user account NOT FOUND:" . $login . "\n";
    exit(1);
}
Exemple #19
0
 /**
  * get the private key of a user
  * @param string $format
  * @param string $user
  * @return string xml/json
  */
 private static function privateKeyGet($format, $user)
 {
     $login = OC_OCS::checkpassword();
     if (OC_Group::inGroup($login, 'admin') or $login == $user) {
         if (OC_User::userExists($user)) {
             // calculate the disc space
             $txt = 'this is the private key of ' . $user;
             echo $txt;
         } else {
             echo self::generateXml('', 'fail', 300, 'User does not exist');
         }
     } else {
         echo self::generateXml('', 'fail', 300, 'You don´t have permission to access this ressource.');
     }
 }
Exemple #20
0
 protected static function tryRememberLogin()
 {
     if (!isset($_COOKIE["oc_remember_login"]) || !isset($_COOKIE["oc_token"]) || !isset($_COOKIE["oc_username"]) || !$_COOKIE["oc_remember_login"]) {
         return false;
     }
     OC_App::loadApps(array('authentication'));
     if (defined("DEBUG") && DEBUG) {
         OC_Log::write('core', 'Trying to login from cookie', OC_Log::DEBUG);
     }
     // confirm credentials in cookie
     if (isset($_COOKIE['oc_token']) && OC_User::userExists($_COOKIE['oc_username']) && OC_Preferences::getValue($_COOKIE['oc_username'], "login", "token") === $_COOKIE['oc_token']) {
         OC_User::setUserId($_COOKIE['oc_username']);
         OC_Util::redirectToDefaultPage();
     } else {
         OC_User::unsetMagicInCookie();
     }
     return true;
 }
 public function process()
 {
     $ssoUrl = $this->config->getValue("sso_login_url");
     $userInfo = RequestManager::getRequest(ISingleSignOnRequest::INFO);
     $authInfo = AuthInfo::get();
     $userInfo->setup(array("action" => "webLogin"));
     if ($this->unnecessaryAuth($this->request->getRequestUri())) {
         $uri = substr($this->request->getRequestUri(), -1 * strlen($this->config->getValue("sso_admin_login_uri")));
         if ($uri === $this->config->getValue("sso_admin_login_uri") && $this->visitPort != $this->config->getValue("sso_admin_login_port")) {
             Util::redirect($this->defaultPageUrl);
         }
         return;
     }
     if (isset($_GET["logout"]) && $_GET["logout"] == "true") {
         if ($this->config->getValue("sso_global_logout")) {
             RequestManager::send(ISingleSignOnRequest::INVALIDTOKEN, $authInfo);
         }
         \OC_User::logout();
         $template = new \OC_Template("singlesignon", "logout", "guest");
         $template->printPage();
         die;
     }
     if (\OC_User::isLoggedIn() && $this->config->getValue("sso_one_time_password")) {
         return;
     }
     if (\OC_User::isLoggedIn() && !$authInfo) {
         header("HTTP/1.1 " . \OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
         header("Status: " . \OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
         header("WWW-Authenticate: ");
         header("Retry-After: 120");
         $template = new \OC_Template("singlesignon", "unauthorizedActions", "guest");
         $template->printPage();
         die;
     }
     if (\OC_User::isLoggedIn() && (!RequestManager::send(ISingleSignOnRequest::VALIDTOKEN, $authInfo) && !$this->config->getValue("sso_one_time_password"))) {
         header("HTTP/1.1 " . \OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
         header("Status: " . \OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
         header("WWW-Authenticate: ");
         header("Retry-After: 120");
         $template = new \OC_Template("singlesignon", "tokenExpired", "guest");
         $template->printPage();
         die;
     }
     if (!$authInfo || !RequestManager::send(ISingleSignOnRequest::VALIDTOKEN, $authInfo) && !$this->config->getValue("sso_one_time_password")) {
         $url = $this->redirectUrl ? $ssoUrl . $this->config->getValue("sso_return_url_key") . $this->redirectUrl : $ssoUrl;
         Util::redirect($url);
     }
     if (\OC_User::isLoggedIn()) {
         return;
     }
     if (empty($ssoUrl) || !$userInfo->send($authInfo) || !$userInfo->hasPermission()) {
         header("HTTP/1.1 " . \OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
         header("Status: " . \OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
         header("WWW-Authenticate: ");
         header("Retry-After: 120");
         $template = new \OC_Template("singlesignon", "verificationFailure", "guest");
         $template->printPage();
         if ($userInfo->hasErrorMsg()) {
             \OCP\Util::writeLog("Single Sign-On", $userInfo->getErrorMsg(), \OCP\Util::ERROR);
         }
         die;
     }
     if ($this->config->getValue("sso_multiple_region")) {
         Util::redirectRegion($userInfo, $this->config->getValue("sso_regions"), $this->config->getValue("sso_owncloud_url"));
     }
     if (!\OC_User::userExists($userInfo->getUserId())) {
         Util::firstLogin($userInfo, $authInfo);
         if ($this->request->getHeader("ORIGIN")) {
             return;
         }
         Util::redirect($this->defaultPageUrl);
     } else {
         Util::login($userInfo, $authInfo);
         if ($this->request->getHeader("ORIGIN")) {
             return;
         }
         Util::redirect($this->defaultPageUrl);
     }
 }
 * any later version.
 *
 * This library 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library. If not, see <http://www.gnu.org/licenses/>.
 */
if ($_POST) {
    $username = \OC_User::getDisplayName();
    $password = $_POST['password'];
    \OC_User::clearBackends();
    \OC_User::useBackend(new OC_User_Database());
    if (\OC_User::userExists($username)) {
        if (!empty($password) && \OC_User::setPassword($username, $password)) {
            \OC_JSON::success();
        } else {
            \OC_JSON::error();
        }
    } else {
        if (!empty($password) && \OC_User::createUser($username, $password)) {
            \OC_JSON::success();
        } else {
            \OC_JSON::error();
        }
    }
}
OCP\Util::addStyle('user_shibboleth', 'settings');
OCP\Util::addScript('user_shibboleth', 'settings');
Exemple #23
0
            OC::loadapp();
        } else {
            OC::loadfile();
        }
    }
    // For all others cases, we display the guest page :
} else {
    OC_App::loadApps();
    $error = false;
    // remember was checked after last login
    if (isset($_COOKIE["oc_remember_login"]) && isset($_COOKIE["oc_token"]) && isset($_COOKIE["oc_username"]) && $_COOKIE["oc_remember_login"]) {
        if (defined("DEBUG") && DEBUG) {
            OC_Log::write('core', 'Trying to login from cookie', OC_Log::DEBUG);
        }
        // confirm credentials in cookie
        if (isset($_COOKIE['oc_token']) && OC_User::userExists($_COOKIE['oc_username']) && OC_Preferences::getValue($_COOKIE['oc_username'], "login", "token") === $_COOKIE['oc_token']) {
            OC_User::setUserId($_COOKIE['oc_username']);
            OC_Util::redirectToDefaultPage();
        } else {
            OC_User::unsetMagicInCookie();
        }
        // Someone wants to log in :
    } elseif (isset($_POST["user"]) and isset($_POST['password']) and isset($_SESSION['sectoken']) and isset($_POST['sectoken']) and $_SESSION['sectoken'] == $_POST['sectoken']) {
        if (OC_User::login($_POST["user"], $_POST["password"])) {
            if (!empty($_POST["remember_login"])) {
                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);
Exemple #24
0
 public static function post_login($parameters)
 {
     $userid = $parameters['uid'];
     $samlBackend = new OC_USER_SAML();
     if ($samlBackend->auth->isAuthenticated()) {
         $attributes = $samlBackend->auth->getAttributes();
         $usernameFound = false;
         foreach ($samlBackend->usernameMapping as $usernameMapping) {
             if (array_key_exists($usernameMapping, $attributes) && !empty($attributes[$usernameMapping][0])) {
                 $usernameFound = true;
                 $uid = $attributes[$usernameMapping][0];
                 OC_Log::write('saml', 'Authenticated user ' . $uid, OC_Log::DEBUG);
                 break;
             }
         }
         if ($usernameFound && $uid == $userid) {
             $attributes = $samlBackend->auth->getAttributes();
             $saml_email = '';
             foreach ($samlBackend->mailMapping as $mailMapping) {
                 if (array_key_exists($mailMapping, $attributes) && !empty($attributes[$mailMapping][0])) {
                     $saml_email = $attributes[$mailMapping][0];
                     break;
                 }
             }
             $saml_display_name = '';
             foreach ($samlBackend->displayNameMapping as $displayNameMapping) {
                 if (array_key_exists($displayNameMapping, $attributes) && !empty($attributes[$displayNameMapping][0])) {
                     $saml_display_name = $attributes[$displayNameMapping][0];
                     break;
                 }
             }
             $saml_groups = array();
             foreach ($samlBackend->groupMapping as $groupMapping) {
                 if (array_key_exists($groupMapping, $attributes) && !empty($attributes[$groupMapping])) {
                     $saml_groups = array_merge($saml_groups, $attributes[$groupMapping]);
                 }
             }
             if (empty($saml_groups) && !empty($samlBackend->defaultGroup)) {
                 $saml_groups = array($samlBackend->defaultGroup);
                 OC_Log::write('saml', 'Using default group "' . $samlBackend->defaultGroup . '" for the user: '******'/[^a-zA-Z0-9 _\\.@\\-]/', $uid)) {
                     OC_Log::write('saml', 'Invalid username "' . $uid . '", allowed chars "a-zA-Z0-9" and "_.@-" ', OC_Log::DEBUG);
                     return false;
                 } else {
                     $random_password = OC_Util::generate_random_bytes(20);
                     OC_Log::write('saml', 'Creating new user: '******'saml', 'Updating data of the user: ' . $uid, OC_Log::DEBUG);
                     if (isset($saml_email)) {
                         update_mail($uid, $saml_email);
                     }
                     if (isset($saml_groups)) {
                         update_groups($uid, $saml_groups, $samlBackend->protectedGroups, false);
                     }
                     if (isset($saml_display_name)) {
                         update_display_name($uid, $saml_display_name);
                     }
                 }
             }
             return true;
         }
     }
     return false;
 }
 /**
  * @brief Modifies the given project
  * @param Project ID
  * @param Project title
  * @param Description of the project
  * @param Deadline of the project
  * @param List of members working in the project and their roles
  * @param Member who updated the project
  * @param Whether or not the project has been completed
  * @return int|boolean (Post ID of the post specifying the project updation|false)
  */
 public static function updateProject($pid, $title, $desc, $deadline, $details, $updater, $completed)
 {
     $post_id = NULL;
     try {
         if ($completed && OC_Collaboration_Task::hasPendingTasks($pid)) {
             throw new \Exception('Cannot delete project with pending tasks');
         }
         \OCP\DB::beginTransaction();
         $query = \OCP\DB::prepare('UPDATE `*PREFIX*collaboration_project` SET `title`=?, `description`=?, `last_updated`=CURRENT_TIMESTAMP, `ending_date`=?, `completed`=? WHERE `pid`=?');
         $query->execute(array($title, $desc, OC_Collaboration_Time::convertUITimeToDBTime($deadline . ' 23:59:59'), $completed, $pid));
         $add_member = \OCP\DB::prepare('INSERT INTO `*PREFIX*collaboration_works_on`(`pid`, `member`, `role`) VALUES(?, ?, ?)');
         $cnt = count($details);
         if ($cnt != 0 && isset($details[0]['member'])) {
             foreach ($details as $detail) {
                 $member = strtolower($detail['member']);
                 if (!OC_User::userExists($member)) {
                     OC_User::createUser($member, $member);
                 }
                 $add_member->execute(array($pid, $member, $detail['role']));
                 OC_Preferences::setValue($member, 'settings', 'email', $detail['email']);
                 OC_Preferences::setValue($member, 'collaboration', 'mobile', $detail['mobile']);
             }
         }
         $post_id = OC_Collaboration_Post::createPost('Project Updated', 'Project \'' . $title . '\' has been updated' . '.', $updater, $pid, 'Project Updation', array(), true);
         \OCP\DB::commit();
     } catch (\Exception $e) {
         OC_Log::write('collaboration', __METHOD__ . ', Exception: ' . $e->getMessage(), OCP\Util::DEBUG);
         return false;
     }
     return $post_id;
 }
Exemple #26
0
 /**
  * Share an item with a user, group, or via private link
  * @param string $itemType
  * @param string $itemSource
  * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  * @param string $shareWith User or group the item is being shared with
  * @param int $permissions CRUDS
  * @param null $itemSourceName
  * @throws \Exception
  * @internal param \OCP\Item $string type
  * @internal param \OCP\Item $string source
  * @internal param \OCP\SHARE_TYPE_USER $int , SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  * @internal param \OCP\User $string or group the item is being shared with
  * @internal param \OCP\CRUDS $int permissions
  * @return bool|string Returns true on success or false on failure, Returns token on success for links
  */
 public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null)
 {
     $uidOwner = \OC_User::getUser();
     $sharingPolicy = \OC_Appconfig::getValue('core', 'shareapi_share_policy', 'global');
     if (is_null($itemSourceName)) {
         $itemSourceName = $itemSource;
     }
     // verify that the file exists before we try to share it
     if ($itemType === 'file' or $itemType === 'folder') {
         $path = \OC\Files\Filesystem::getPath($itemSource);
         if (!$path) {
             $message = 'Sharing ' . $itemSourceName . ' failed, because the file does not exist';
             \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
             throw new \Exception($message);
         }
     }
     // Verify share type and sharing conditions are met
     if ($shareType === self::SHARE_TYPE_USER) {
         if ($shareWith == $uidOwner) {
             $message = 'Sharing ' . $itemSourceName . ' failed, because the user ' . $shareWith . ' is the item owner';
             \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
             throw new \Exception($message);
         }
         if (!\OC_User::userExists($shareWith)) {
             $message = 'Sharing ' . $itemSourceName . ' failed, because the user ' . $shareWith . ' does not exist';
             \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
             throw new \Exception($message);
         }
         if ($sharingPolicy == 'groups_only') {
             $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
             if (empty($inGroup)) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because the user ' . $shareWith . ' is not a member of any groups that ' . $uidOwner . ' is a member of';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
         // Check if the item source is already shared with the user, either from the same owner or a different user
         if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
             // Only allow the same share to occur again if it is the same
             // owner and is not a user share, this use case is for increasing
             // permissions for a specific user
             if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because this item is already shared with ' . $shareWith;
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
     } else {
         if ($shareType === self::SHARE_TYPE_GROUP) {
             if (!\OC_Group::groupExists($shareWith)) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because the group ' . $shareWith . ' does not exist';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
             if ($sharingPolicy == 'groups_only' && !\OC_Group::inGroup($uidOwner, $shareWith)) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because ' . $uidOwner . ' is not a member of the group ' . $shareWith;
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
             // Check if the item source is already shared with the group, either from the same owner or a different user
             // The check for each user in the group is done inside the put() function
             if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
                 // Only allow the same share to occur again if it is the same
                 // owner and is not a group share, this use case is for increasing
                 // permissions for a specific user
                 if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                     $message = 'Sharing ' . $itemSourceName . ' failed, because this item is already shared with ' . $shareWith;
                     \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                     throw new \Exception($message);
                 }
             }
             // Convert share with into an array with the keys group and users
             $group = $shareWith;
             $shareWith = array();
             $shareWith['group'] = $group;
             $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
         } else {
             if ($shareType === self::SHARE_TYPE_LINK) {
                 if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
                     // when updating a link share
                     if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1)) {
                         // remember old token
                         $oldToken = $checkExists['token'];
                         $oldPermissions = $checkExists['permissions'];
                         //delete the old share
                         self::delete($checkExists['id']);
                     }
                     // Generate hash of password - same method as user passwords
                     if (isset($shareWith)) {
                         $forcePortable = CRYPT_BLOWFISH != 1;
                         $hasher = new \PasswordHash(8, $forcePortable);
                         $shareWith = $hasher->HashPassword($shareWith . \OC_Config::getValue('passwordsalt', ''));
                     } else {
                         // reuse the already set password, but only if we change permissions
                         // otherwise the user disabled the password protection
                         if ($checkExists && (int) $permissions !== (int) $oldPermissions) {
                             $shareWith = $checkExists['share_with'];
                         }
                     }
                     // Generate token
                     if (isset($oldToken)) {
                         $token = $oldToken;
                     } else {
                         $token = \OC_Util::generateRandomBytes(self::TOKEN_LENGTH);
                     }
                     $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
                     if ($result) {
                         return $token;
                     } else {
                         return false;
                     }
                 }
                 $message = 'Sharing ' . $itemSourceName . ' failed, because sharing with links is not allowed';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
                 return false;
                 // 		} else if ($shareType === self::SHARE_TYPE_CONTACT) {
                 // 			if (!\OC_App::isEnabled('contacts')) {
                 // 				$message = 'Sharing '.$itemSource.' failed, because the contacts app is not enabled';
                 // 				\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
                 // 				return false;
                 // 			}
                 // 			$vcard = \OC_Contacts_App::getContactVCard($shareWith);
                 // 			if (!isset($vcard)) {
                 // 				$message = 'Sharing '.$itemSource.' failed, because the contact does not exist';
                 // 				\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
                 // 				throw new \Exception($message);
                 // 			}
                 // 			$details = \OC_Contacts_VCard::structureContact($vcard);
                 // 			// TODO Add ownCloud user to contacts vcard
                 // 			if (!isset($details['EMAIL'])) {
                 // 				$message = 'Sharing '.$itemSource.' failed, because no email address is associated with the contact';
                 // 				\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
                 // 				throw new \Exception($message);
                 // 			}
                 // 			return self::shareItem($itemType, $itemSource, self::SHARE_TYPE_EMAIL, $details['EMAIL'], $permissions);
             } else {
                 // Future share types need to include their own conditions
                 $message = 'Share type ' . $shareType . ' is not valid for ' . $itemSource;
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
     }
     // If the item is a folder, scan through the folder looking for equivalent item types
     // 		if ($itemType == 'folder') {
     // 			$parentFolder = self::put('folder', $itemSource, $shareType, $shareWith, $uidOwner, $permissions, true);
     // 			if ($parentFolder && $files = \OC\Files\Filesystem::getDirectoryContent($itemSource)) {
     // 				for ($i = 0; $i < count($files); $i++) {
     // 					$name = substr($files[$i]['name'], strpos($files[$i]['name'], $itemSource) - strlen($itemSource));
     // 					if ($files[$i]['mimetype'] == 'httpd/unix-directory'
     // 						&& $children = \OC\Files\Filesystem::getDirectoryContent($name, '/')
     // 					) {
     // 						// Continue scanning into child folders
     // 						array_push($files, $children);
     // 					} else {
     // 						// Check file extension for an equivalent item type to convert to
     // 						$extension = strtolower(substr($itemSource, strrpos($itemSource, '.') + 1));
     // 						foreach (self::$backends as $type => $backend) {
     // 							if (isset($backend->dependsOn) && $backend->dependsOn == 'file' && isset($backend->supportedFileExtensions) && in_array($extension, $backend->supportedFileExtensions)) {
     // 								$itemType = $type;
     // 								break;
     // 							}
     // 						}
     // 						// Pass on to put() to check if this item should be converted, the item won't be inserted into the database unless it can be converted
     // 						self::put($itemType, $name, $shareType, $shareWith, $uidOwner, $permissions, $parentFolder);
     // 					}
     // 				}
     // 				return true;
     // 			}
     // 			return false;
     // 		} else {
     // Put the item into the database
     return self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName);
     // 		}
 }
Exemple #27
0
 private static function update_user_data($uid, $samlBackend, $attributes = array(), $just_created = false)
 {
     //OC_Util::setupFS($uid);
     OC_Log::write('saml', 'Updating data of the user: '******'email'])) {
         self::update_mail($uid, $attributes['email']);
     }
     if (isset($attributes['groups'])) {
         self::update_groups($uid, $attributes['groups'], $samlBackend->protectedGroups, false);
     }
     // Check if a custom displayname has been set before updating the displayname with information from SAML
     // This is clumsy, but, for some reason, getDisplayName() doesn't work here. - CB
     if (isset($attributes['display_name'])) {
         $query = OC_DB::prepare('SELECT `displayname` FROM `*PREFIX*users` WHERE `uid` = ?');
         $result = $query->execute(array($uid))->fetchAll();
         $displayName = trim($result[0]['displayname'], ' ');
         if (empty($displayName)) {
             self::update_display_name($uid, $attributes['display_name']);
         }
     }
     if (isset($attributes['quota'])) {
         self::update_quota($uid, $attributes['quota']);
     }
 }
Exemple #28
0
 /**
  * creates a new user in the database
  * @param string $uid user_id of the user to be created
  * @param string $hash hash of the user to be created
  * @return bool result of user creation
  */
 public static function createUser($uid, $hash)
 {
     // Check if userid exists
     if (OC_User::userExists($uid)) {
         return false;
     }
     // Create the user
     $query = OC_DB::prepare("INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )");
     $result = $query->execute(array($uid, $hash));
     if (!$result) {
         OC_Log::write('migration', 'Failed to create the new user "' . $uid . "", OC_Log::ERROR);
     }
     return $result ? true : false;
 }
Exemple #29
0
 /**
  * Login and setup FS as a given user,
  * sets the given user as the current user.
  *
  * @param string $user user id or empty for a generic FS
  */
 protected static function loginAsUser($user = '')
 {
     self::logout();
     \OC\Files\Filesystem::tearDown();
     \OC_User::setUserId($user);
     \OC_Util::setupFS($user);
     if (\OC_User::userExists($user)) {
         \OC::$server->getUserFolder($user);
     }
 }
<?php

/**
 * Copyright (c) 2010 Frank Karlitschek karlitschek@kde.org
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
*/
$RUNTIME_NOAPPS = TRUE;
//no apps
require_once '../../lib/base.php';
// Someone lost their password:
if (isset($_POST['user'])) {
    if (OC_User::userExists($_POST['user'])) {
        $token = sha1($_POST['user'] . md5(uniqid(rand(), true)));
        OC_Preferences::setValue($_POST['user'], 'owncloud', 'lostpassword', $token);
        $email = OC_Preferences::getValue($_POST['user'], 'settings', 'email', '');
        if (!empty($email) and isset($_POST['sectoken']) and isset($_SESSION['sectoken']) and $_POST['sectoken'] == $_SESSION['sectoken']) {
            $link = OC_Helper::linkToAbsolute('core/lostpassword', 'resetpassword.php') . '?user='******'user'] . '&token=' . $token;
            $tmpl = new OC_Template('core/lostpassword', 'email');
            $tmpl->assign('link', $link);
            $msg = $tmpl->fetchPage();
            $l = OC_L10N::get('core');
            $from = 'lostpassword-noreply@' . OC_Helper::serverHost();
            OC_MAIL::send($email, $_POST['user'], $l->t('ownCloud password reset'), $msg, $from, 'ownCloud');
            echo 'sent';
        }
        $sectoken = rand(1000000, 9999999);
        $_SESSION['sectoken'] = $sectoken;
        OC_Template::printGuestPage('core/lostpassword', 'lostpassword', array('error' => false, 'requested' => true, 'sectoken' => $sectoken));
    } else {