Merge pull request #21761 from owncloud/share2_link

Share2 link
This commit is contained in:
Thomas Müller 2016-01-21 15:43:08 +01:00
commit e2f231d051
9 changed files with 622 additions and 269 deletions

View File

@ -47,13 +47,15 @@ class Application extends App {
return new ShareController( return new ShareController(
$c->query('AppName'), $c->query('AppName'),
$c->query('Request'), $c->query('Request'),
$c->query('UserSession'),
$server->getAppConfig(),
$server->getConfig(), $server->getConfig(),
$c->query('URLGenerator'), $server->getURLGenerator(),
$c->query('UserManager'), $server->getUserManager(),
$server->getLogger(), $server->getLogger(),
$server->getActivityManager() $server->getActivityManager(),
$server->getShareManager(),
$server->getSession(),
$server->getPreviewManager(),
$server->getRootFolder()
); );
}); });
$container->registerService('ExternalSharesController', function (SimpleContainer $c) { $container->registerService('ExternalSharesController', function (SimpleContainer $c) {
@ -68,15 +70,6 @@ class Application extends App {
/** /**
* Core class wrappers * Core class wrappers
*/ */
$container->registerService('UserSession', function (SimpleContainer $c) use ($server) {
return $server->getUserSession();
});
$container->registerService('URLGenerator', function (SimpleContainer $c) use ($server) {
return $server->getUrlGenerator();
});
$container->registerService('UserManager', function (SimpleContainer $c) use ($server) {
return $server->getUserManager();
});
$container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) { $container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) {
return $server->getHTTPClientService(); return $server->getHTTPClientService();
}); });

View File

@ -41,14 +41,18 @@ use OCP\IRequest;
use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\NotFoundResponse; use OCP\AppFramework\Http\NotFoundResponse;
use OC\URLGenerator; use OCP\IURLGenerator;
use OC\AppConfig; use OCP\IConfig;
use OCP\ILogger; use OCP\ILogger;
use OCP\IUserManager;
use OCP\ISession;
use OCP\IPreview;
use OCA\Files_Sharing\Helper; use OCA\Files_Sharing\Helper;
use OCP\User;
use OCP\Util; use OCP\Util;
use OCA\Files_Sharing\Activity; use OCA\Files_Sharing\Activity;
use \OCP\Files\NotFoundException; use \OCP\Files\NotFoundException;
use \OC\Share20\IShare;
use OCP\Files\IRootFolder;
/** /**
* Class ShareController * Class ShareController
@ -57,50 +61,60 @@ use \OCP\Files\NotFoundException;
*/ */
class ShareController extends Controller { class ShareController extends Controller {
/** @var \OC\User\Session */ /** @var IConfig */
protected $userSession;
/** @var \OC\AppConfig */
protected $appConfig;
/** @var \OCP\IConfig */
protected $config; protected $config;
/** @var \OC\URLGenerator */ /** @var IURLGenerator */
protected $urlGenerator; protected $urlGenerator;
/** @var \OC\User\Manager */ /** @var IUserManager */
protected $userManager; protected $userManager;
/** @var \OCP\ILogger */ /** @var ILogger */
protected $logger; protected $logger;
/** @var OCP\Activity\IManager */ /** @var OCP\Activity\IManager */
protected $activityManager; protected $activityManager;
/** @var OC\Share20\Manager */
protected $shareManager;
/** @var ISession */
protected $session;
/** @var IPreview */
protected $previewManager;
/** @var IRootFolder */
protected $rootFolder;
/** /**
* @param string $appName * @param string $appName
* @param IRequest $request * @param IRequest $request
* @param OC\User\Session $userSession * @param IConfig $config
* @param AppConfig $appConfig * @param IURLGenerator $urlGenerator
* @param OCP\IConfig $config * @param IUserManager $userManager
* @param URLGenerator $urlGenerator
* @param OCP\IUserManager $userManager
* @param ILogger $logger * @param ILogger $logger
* @param OCP\Activity\IManager $activityManager * @param OCP\Activity\IManager $activityManager
* @param \OC\Share20\Manager $shareManager
* @param ISession $session
* @param IPreview $previewManager
* @param IRootFolder $rootFolder
*/ */
public function __construct($appName, public function __construct($appName,
IRequest $request, IRequest $request,
OC\User\Session $userSession, IConfig $config,
AppConfig $appConfig, IURLGenerator $urlGenerator,
OCP\IConfig $config, IUserManager $userManager,
URLGenerator $urlGenerator,
OCP\IUserManager $userManager,
ILogger $logger, ILogger $logger,
OCP\Activity\IManager $activityManager) { \OCP\Activity\IManager $activityManager,
\OC\Share20\Manager $shareManager,
ISession $session,
IPreview $previewManager,
IRootFolder $rootFolder) {
parent::__construct($appName, $request); parent::__construct($appName, $request);
$this->userSession = $userSession;
$this->appConfig = $appConfig;
$this->config = $config; $this->config = $config;
$this->urlGenerator = $urlGenerator; $this->urlGenerator = $urlGenerator;
$this->userManager = $userManager; $this->userManager = $userManager;
$this->logger = $logger; $this->logger = $logger;
$this->activityManager = $activityManager; $this->activityManager = $activityManager;
$this->shareManager = $shareManager;
$this->session = $session;
$this->previewManager = $previewManager;
$this->rootFolder = $rootFolder;
} }
/** /**
@ -111,9 +125,9 @@ class ShareController extends Controller {
* @return TemplateResponse|RedirectResponse * @return TemplateResponse|RedirectResponse
*/ */
public function showAuthenticate($token) { public function showAuthenticate($token) {
$linkItem = Share::getShareByToken($token, false); $share = $this->shareManager->getShareByToken($token);
if(Helper::authenticate($linkItem)) { if($this->linkShareAuth($share)) {
return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token))); return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
} }
@ -130,12 +144,15 @@ class ShareController extends Controller {
* @return RedirectResponse|TemplateResponse * @return RedirectResponse|TemplateResponse
*/ */
public function authenticate($token, $password = '') { public function authenticate($token, $password = '') {
$linkItem = Share::getShareByToken($token, false);
if($linkItem === false) { // Check whether share exists
try {
$share = $this->shareManager->getShareByToken($token);
} catch (\OC\Share20\Exception\ShareNotFound $e) {
return new NotFoundResponse(); return new NotFoundResponse();
} }
$authenticate = Helper::authenticate($linkItem, $password); $authenticate = $this->linkShareAuth($share, $password);
if($authenticate === true) { if($authenticate === true) {
return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token))); return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
@ -144,6 +161,34 @@ class ShareController extends Controller {
return new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest'); return new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
} }
/**
* Authenticate a link item with the given password.
* Or use the session if no password is provided.
*
* This is a modified version of Helper::authenticate
* TODO: Try to merge back eventually with Helper::authenticate
*
* @param IShare $share
* @param string|null $password
* @return bool
*/
private function linkShareAuth(IShare $share, $password = null) {
if ($password !== null) {
if ($this->shareManager->checkPassword($share, $password)) {
$this->session->set('public_link_authenticated', (string)$share->getId());
} else {
return false;
}
} else {
// not authenticated ?
if ( ! $this->session->exists('public_link_authenticated')
|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
return false;
}
}
return true;
}
/** /**
* @PublicPage * @PublicPage
* @NoCSRFRequired * @NoCSRFRequired
@ -157,54 +202,70 @@ class ShareController extends Controller {
\OC_User::setIncognitoMode(true); \OC_User::setIncognitoMode(true);
// Check whether share exists // Check whether share exists
$linkItem = Share::getShareByToken($token, false); try {
if($linkItem === false) { $share = $this->shareManager->getShareByToken($token);
} catch (\OC\Share20\Exception\ShareNotFound $e) {
return new NotFoundResponse(); return new NotFoundResponse();
} }
$shareOwner = $linkItem['uid_owner'];
$originalSharePath = $this->getPath($token);
// Share is password protected - check whether the user is permitted to access the share // Share is password protected - check whether the user is permitted to access the share
if (isset($linkItem['share_with']) && !Helper::authenticate($linkItem)) { if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
array('token' => $token))); array('token' => $token)));
} }
if (Filesystem::isReadable($originalSharePath . $path)) { // We can't get the path of a file share
$getPath = Filesystem::normalizePath($path); if ($share->getPath() instanceof \OCP\Files\File && $path !== '') {
$originalSharePath .= $path;
} else {
throw new NotFoundException(); throw new NotFoundException();
} }
$file = basename($originalSharePath); $rootFolder = null;
if ($share->getPath() instanceof \OCP\Files\Folder) {
/** @var \OCP\Files\Folder $rootFolder */
$rootFolder = $share->getPath();
try {
$path = $rootFolder->get($path);
} catch (\OCP\Files\NotFoundException $e) {
throw new NotFoundException();
}
}
$shareTmpl = []; $shareTmpl = [];
$shareTmpl['displayName'] = User::getDisplayName($shareOwner); $shareTmpl['displayName'] = $share->getShareOwner()->getDisplayName();
$shareTmpl['owner'] = $shareOwner; $shareTmpl['owner'] = $share->getShareOwner()->getUID();
$shareTmpl['filename'] = $file; $shareTmpl['filename'] = $share->getPath()->getName();
$shareTmpl['directory_path'] = $linkItem['file_target']; $shareTmpl['directory_path'] = $share->getTarget();
$shareTmpl['mimetype'] = Filesystem::getMimeType($originalSharePath); $shareTmpl['mimetype'] = $share->getPath()->getMimetype();
$shareTmpl['previewSupported'] = \OC::$server->getPreviewManager()->isMimeSupported($shareTmpl['mimetype']); $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getPath()->getMimetype());
$shareTmpl['dirToken'] = $linkItem['token']; $shareTmpl['dirToken'] = $token;
$shareTmpl['sharingToken'] = $token; $shareTmpl['sharingToken'] = $token;
$shareTmpl['server2serversharing'] = Helper::isOutgoingServer2serverShareEnabled(); $shareTmpl['server2serversharing'] = Helper::isOutgoingServer2serverShareEnabled();
$shareTmpl['protected'] = isset($linkItem['share_with']) ? 'true' : 'false'; $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
$shareTmpl['dir'] = ''; $shareTmpl['dir'] = '';
$nonHumanFileSize = \OC\Files\Filesystem::filesize($originalSharePath); $shareTmpl['nonHumanFileSize'] = $share->getPath()->getSize();
$shareTmpl['nonHumanFileSize'] = $nonHumanFileSize; $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getPath()->getSize());
$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($nonHumanFileSize);
// Show file list // Show file list
if (Filesystem::is_dir($originalSharePath)) { if ($share->getPath() instanceof \OCP\Files\Folder) {
$shareTmpl['dir'] = $getPath; $shareTmpl['dir'] = $rootFolder->getRelativePath($path->getPath());
$maxUploadFilesize = Util::maxUploadFilesize($originalSharePath);
$freeSpace = Util::freeSpace($originalSharePath); /*
* The OC_Util methods require a view. This just uses the node API
*/
$freeSpace = $share->getPath()->getStorage()->free_space($share->getPath()->getInternalPath());
if ($freeSpace !== \OCP\Files\FileInfo::SPACE_UNKNOWN) {
$freeSpace = max($freeSpace, 0);
} else {
$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
}
$uploadLimit = Util::uploadLimit(); $uploadLimit = Util::uploadLimit();
$maxUploadFilesize = min($freeSpace, $uploadLimit);
$folder = new Template('files', 'list', ''); $folder = new Template('files', 'list', '');
$folder->assign('dir', $getPath); $folder->assign('dir', $rootFolder->getRelativePath($path->getPath()));
$folder->assign('dirToken', $linkItem['token']); $folder->assign('dirToken', $token);
$folder->assign('permissions', \OCP\Constants::PERMISSION_READ); $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
$folder->assign('isPublic', true); $folder->assign('isPublic', true);
$folder->assign('publicUploadEnabled', 'no'); $folder->assign('publicUploadEnabled', 'no');
@ -242,14 +303,12 @@ class ShareController extends Controller {
public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') { public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
\OC_User::setIncognitoMode(true); \OC_User::setIncognitoMode(true);
$linkItem = OCP\Share::getShareByToken($token, false); $share = $this->shareManager->getShareByToken($token);
// Share is password protected - check whether the user is permitted to access the share // Share is password protected - check whether the user is permitted to access the share
if (isset($linkItem['share_with'])) { if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
if(!Helper::authenticate($linkItem)) { return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', ['token' => $token]));
array('token' => $token)));
}
} }
$files_list = null; $files_list = null;
@ -257,41 +316,86 @@ class ShareController extends Controller {
$files_list = json_decode($files); $files_list = json_decode($files);
// in case we get only a single file // in case we get only a single file
if ($files_list === null) { if ($files_list === null) {
$files_list = array($files); $files_list = [$files];
} }
} }
$originalSharePath = self::getPath($token); $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner()->getUID());
$originalSharePath = $userFolder->getRelativePath($share->getPath()->getPath());
// Create the activities // Single file share
if (isset($originalSharePath) && Filesystem::isReadable($originalSharePath . $path)) { if ($share->getPath() instanceof \OCP\Files\File) {
$originalSharePath = Filesystem::normalizePath($originalSharePath . $path); // Single file download
$isDir = \OC\Files\Filesystem::is_dir($originalSharePath); $event = $this->activityManager->generateEvent();
$event->setApp('files_sharing')
->setType(Activity::TYPE_PUBLIC_LINKS)
->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($share->getPath()->getPath())])
->setAffectedUser($share->getShareOwner()->getUID())
->setObject('files', $share->getPath()->getId(), $userFolder->getRelativePath($share->getPath()->getPath()));
$this->activityManager->publish($event);
}
// Directory share
else {
/** @var \OCP\Files\Folder $node */
$node = $share->getPath();
$activities = []; // Try to get the path
if (!$isDir) { if ($path !== '') {
// Single file public share try {
$activities[$originalSharePath] = Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED; $node = $node->get($path);
} catch (NotFoundException $e) {
return new NotFoundResponse();
}
}
$originalSharePath = $userFolder->getRelativePath($node->getPath());
if ($node instanceof \OCP\Files\File) {
// Single file download
$event = $this->activityManager->generateEvent();
$event->setApp('files_sharing')
->setType(Activity::TYPE_PUBLIC_LINKS)
->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($node->getPath())])
->setAffectedUser($share->getShareOwner()->getUID())
->setObject('files', $node->getId(), $userFolder->getRelativePath($node->getPath()));
$this->activityManager->publish($event);
} else if (!empty($files_list)) { } else if (!empty($files_list)) {
// Only some files are downloaded /** @var \OCP\Files\Folder $node */
// Subset of files is downloaded
foreach ($files_list as $file) { foreach ($files_list as $file) {
$filePath = Filesystem::normalizePath($originalSharePath . '/' . $file); $subNode = $node->get($file);
$isDir = \OC\Files\Filesystem::is_dir($filePath);
$activities[$filePath] = ($isDir) ? Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED : Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED; $event = $this->activityManager->generateEvent();
$event->setApp('files_sharing')
->setType(Activity::TYPE_PUBLIC_LINKS)
->setAffectedUser($share->getShareOwner()->getUID())
->setObject('files', $subNode->getId(), $userFolder->getRelativePath($subNode->getPath()));
if ($subNode instanceof \OCP\Files\File) {
$event->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($subNode->getPath())]);
} else {
$event->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED, [$userFolder->getRelativePath($subNode->getPath())]);
}
$this->activityManager->publish($event);
} }
} else { } else {
// The folder is downloaded // The folder is downloaded
$activities[$originalSharePath] = Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED; $event = $this->activityManager->generateEvent();
} $event->setApp('files_sharing')
->setType(Activity::TYPE_PUBLIC_LINKS)
foreach ($activities as $filePath => $subject) { ->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED, [$userFolder->getRelativePath($node->getPath())])
$this->activityManager->publishActivity( ->setAffectedUser($share->getShareOwner()->getUID())
'files_sharing', $subject, array($filePath), '', array(), ->setObject('files', $node->getId(), $userFolder->getRelativePath($node->getPath()));
$filePath, '', $linkItem['uid_owner'], Activity::TYPE_PUBLIC_LINKS, Activity::PRIORITY_MEDIUM $this->activityManager->publish($event);
);
} }
} }
/* FIXME: We should do this all nicely in OCP */
OC_Util::tearDownFS();
OC_Util::setupFS($share->getShareOwner()->getUID());
/** /**
* this sets a cookie to be able to recognize the start of the download * this sets a cookie to be able to recognize the start of the download
* the content must not be longer than 32 characters and must only contain * the content must not be longer than 32 characters and must only contain
@ -318,30 +422,4 @@ class ShareController extends Controller {
exit(); exit();
} }
} }
/**
* @param string $token
* @return string Resolved file path of the token
* @throws NotFoundException In case share could not get properly resolved
*/
private function getPath($token) {
$linkItem = Share::getShareByToken($token, false);
if (is_array($linkItem) && isset($linkItem['uid_owner'])) {
// seems to be a valid share
$rootLinkItem = Share::resolveReShare($linkItem);
if (isset($rootLinkItem['uid_owner'])) {
if(!$this->userManager->userExists($rootLinkItem['uid_owner'])) {
throw new NotFoundException('Owner of the share does not exist anymore');
}
OC_Util::tearDownFS();
OC_Util::setupFS($rootLinkItem['uid_owner']);
$path = Filesystem::getPath($linkItem['file_source']);
if(Filesystem::isReadable($path)) {
return $path;
}
}
}
throw new NotFoundException('No file found belonging to file.');
}
} }

View File

@ -26,7 +26,7 @@ $thumbSize = 1024;
?> ?>
<?php if ($_['previewSupported']): /* This enables preview images for links (e.g. on Facebook, Google+, ...)*/?> <?php if ($_['previewSupported']): /* This enables preview images for links (e.g. on Facebook, Google+, ...)*/?>
<link rel="image_src" href="<?php p(OCP\Util::linkToRoute( 'core_ajax_public_preview', array('x' => $thumbSize, 'y' => $thumbSize, 'file' => $_['directory_path'], 't' => $_['dirToken']))); ?>" /> <link rel="image_src" href="<?php p(\OC::$server->getURLGenerator()->linkToRoute( 'core_ajax_public_preview', array('x' => $thumbSize, 'y' => $thumbSize, 'file' => $_['directory_path'], 't' => $_['dirToken']))); ?>" />
<?php endif; ?> <?php endif; ?>
<div id="notification-container"> <div id="notification-container">

View File

@ -30,15 +30,13 @@
namespace OCA\Files_Sharing\Controllers; namespace OCA\Files_Sharing\Controllers;
use OC\Files\Filesystem; use OC\Files\Filesystem;
use OCA\Files_Sharing\AppInfo\Application; use OC\Share20\Exception\ShareNotFound;
use OCP\AppFramework\Http\NotFoundResponse; use OCP\AppFramework\Http\NotFoundResponse;
use OCP\AppFramework\IAppContainer;
use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Http\TemplateResponse;
use OCP\ISession;
use OCP\Security\ISecureRandom; use OCP\Security\ISecureRandom;
use OC\Files\View; use OCP\IURLGenerator;
use OCP\Share;
use OC\URLGenerator;
/** /**
* @group DB * @group DB
@ -47,33 +45,49 @@ use OC\URLGenerator;
*/ */
class ShareControllerTest extends \Test\TestCase { class ShareControllerTest extends \Test\TestCase {
/** @var IAppContainer */
private $container;
/** @var string */ /** @var string */
private $user; private $user;
/** @var string */ /** @var string */
private $token;
/** @var string */
private $oldUser; private $oldUser;
/** @var string */
private $appName = 'files_sharing';
/** @var ShareController */ /** @var ShareController */
private $shareController; private $shareController;
/** @var URLGenerator */ /** @var IURLGenerator | \PHPUnit_Framework_MockObject_MockObject */
private $urlGenerator; private $urlGenerator;
/** @var ISession | \PHPUnit_Framework_MockObject_MockObject */
private $session;
/** @var \OCP\IPreview | \PHPUnit_Framework_MockObject_MockObject */
private $previewManager;
/** @var \OCP\IConfig | \PHPUnit_Framework_MockObject_MockObject */
private $config;
/** @var \OC\Share20\Manager | \PHPUnit_Framework_MockObject_MockObject */
private $shareManager;
protected function setUp() { protected function setUp() {
$app = new Application(); $this->appName = 'files_sharing';
$this->container = $app->getContainer();
$this->container['Config'] = $this->getMockBuilder('\OCP\IConfig') $this->shareManager = $this->getMockBuilder('\OC\Share20\Manager')->disableOriginalConstructor()->getMock();
->disableOriginalConstructor()->getMock(); $this->urlGenerator = $this->getMock('\OCP\IURLGenerator');
$this->container['AppName'] = 'files_sharing'; $this->session = $this->getMock('\OCP\ISession');
$this->container['UserSession'] = $this->getMockBuilder('\OC\User\Session') $this->previewManager = $this->getMock('\OCP\IPreview');
->disableOriginalConstructor()->getMock(); $this->config = $this->getMock('\OCP\IConfig');
$this->container['URLGenerator'] = $this->getMockBuilder('\OC\URLGenerator')
->disableOriginalConstructor()->getMock(); $this->shareController = new \OCA\Files_Sharing\Controllers\ShareController(
$this->container['UserManager'] = $this->getMockBuilder('\OCP\IUserManager') $this->appName,
->disableOriginalConstructor()->getMock(); $this->getMock('\OCP\IRequest'),
$this->urlGenerator = $this->container['URLGenerator']; $this->config,
$this->shareController = $this->container['ShareController']; $this->urlGenerator,
$this->getMock('\OCP\IUserManager'),
$this->getMock('\OCP\ILogger'),
$this->getMock('\OCP\Activity\IManager'),
$this->shareManager,
$this->session,
$this->previewManager,
$this->getMock('\OCP\Files\IRootFolder')
);
// Store current user // Store current user
$this->oldUser = \OC_User::getUser(); $this->oldUser = \OC_User::getUser();
@ -84,17 +98,6 @@ class ShareControllerTest extends \Test\TestCase {
\OC::$server->getUserManager()->createUser($this->user, $this->user); \OC::$server->getUserManager()->createUser($this->user, $this->user);
\OC_Util::tearDownFS(); \OC_Util::tearDownFS();
$this->loginAsUser($this->user); $this->loginAsUser($this->user);
// Create a dummy shared file
$view = new View('/'. $this->user . '/files');
$view->file_put_contents('file1.txt', 'I am such an awesome shared file!');
$this->token = \OCP\Share::shareItem(
Filesystem::getFileInfo('file1.txt')->getType(),
Filesystem::getFileInfo('file1.txt')->getId(),
\OCP\Share::SHARE_TYPE_LINK,
'IAmPasswordProtected!',
1
);
} }
protected function tearDown() { protected function tearDown() {
@ -112,72 +115,211 @@ class ShareControllerTest extends \Test\TestCase {
\OC_Util::setupFS($this->oldUser); \OC_Util::setupFS($this->oldUser);
} }
public function testShowAuthenticate() { public function testShowAuthenticateNotAuthenticated() {
$linkItem = \OCP\Share::getShareByToken($this->token, false); $share = $this->getMock('\OC\Share20\IShare');
// Test without being authenticated $this->shareManager
$response = $this->shareController->showAuthenticate($this->token); ->expects($this->once())
$expectedResponse = new TemplateResponse($this->container['AppName'], 'authenticate', array(), 'guest'); ->method('getShareByToken')
$this->assertEquals($expectedResponse, $response); ->with('token')
->willReturn($share);
// Test with being authenticated for another file $response = $this->shareController->showAuthenticate('token');
\OC::$server->getSession()->set('public_link_authenticated', $linkItem['id']-1); $expectedResponse = new TemplateResponse($this->appName, 'authenticate', [], 'guest');
$response = $this->shareController->showAuthenticate($this->token);
$expectedResponse = new TemplateResponse($this->container['AppName'], 'authenticate', array(), 'guest');
$this->assertEquals($expectedResponse, $response);
// Test with being authenticated for the correct file
\OC::$server->getSession()->set('public_link_authenticated', $linkItem['id']);
$response = $this->shareController->showAuthenticate($this->token);
$expectedResponse = new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $this->token)));
$this->assertEquals($expectedResponse, $response); $this->assertEquals($expectedResponse, $response);
} }
public function testAuthenticate() { public function testShowAuthenticateAuthenticatedForDifferentShare() {
// Test without a not existing token $share = $this->getMock('\OC\Share20\IShare');
$response = $this->shareController->authenticate('ThisTokenShouldHopefullyNeverExistSoThatTheUnitTestWillAlwaysPass :)'); $share->method('getId')->willReturn(1);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
$this->session->method('get')->with('public_link_authenticated')->willReturn('2');
$response = $this->shareController->showAuthenticate('token');
$expectedResponse = new TemplateResponse($this->appName, 'authenticate', [], 'guest');
$this->assertEquals($expectedResponse, $response);
}
public function testShowAuthenticateCorrectShare() {
$share = $this->getMock('\OC\Share20\IShare');
$share->method('getId')->willReturn(1);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
$this->session->method('get')->with('public_link_authenticated')->willReturn('1');
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with('files_sharing.sharecontroller.showShare', ['token' => 'token'])
->willReturn('redirect');
$response = $this->shareController->showAuthenticate('token');
$expectedResponse = new RedirectResponse('redirect');
$this->assertEquals($expectedResponse, $response);
}
public function testAutehnticateInvalidToken() {
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->will($this->throwException(new \OC\Share20\Exception\ShareNotFound()));
$response = $this->shareController->authenticate('token');
$expectedResponse = new NotFoundResponse(); $expectedResponse = new NotFoundResponse();
$this->assertEquals($expectedResponse, $response); $this->assertEquals($expectedResponse, $response);
}
// Test with a valid password public function testAuthenticateValidPassword() {
$response = $this->shareController->authenticate($this->token, 'IAmPasswordProtected!'); $share = $this->getMock('\OC\Share20\IShare');
$expectedResponse = new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $this->token))); $share->method('getId')->willReturn(42);
$this->assertEquals($expectedResponse, $response);
// Test with a invalid password $this->shareManager
$response = $this->shareController->authenticate($this->token, 'WrongPw!'); ->expects($this->once())
$expectedResponse = new TemplateResponse($this->container['AppName'], 'authenticate', array('wrongpw' => true), 'guest'); ->method('getShareByToken')
->with('token')
->willReturn($share);
$this->shareManager
->expects($this->once())
->method('checkPassword')
->with($share, 'validpassword')
->willReturn(true);
$this->session
->expects($this->once())
->method('set')
->with('public_link_authenticated', '42');
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with('files_sharing.sharecontroller.showShare', ['token'=>'token'])
->willReturn('redirect');
$response = $this->shareController->authenticate('token', 'validpassword');
$expectedResponse = new RedirectResponse('redirect');
$this->assertEquals($expectedResponse, $response); $this->assertEquals($expectedResponse, $response);
} }
public function testAuthenticateInvalidPassword() {
$share = $this->getMock('\OC\Share20\IShare');
$share->method('getId')->willReturn(42);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$this->shareManager
->expects($this->once())
->method('checkPassword')
->with($share, 'invalidpassword')
->willReturn(false);
$this->session
->expects($this->never())
->method('set');
$response = $this->shareController->authenticate('token', 'invalidpassword');
$expectedResponse = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
$this->assertEquals($expectedResponse, $response);
}
public function testShowShareInvalidToken() {
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('invalidtoken')
->will($this->throwException(new ShareNotFound()));
// Test without a not existing token
$response = $this->shareController->showShare('invalidtoken');
$expectedResponse = new NotFoundResponse();
$this->assertEquals($expectedResponse, $response);
}
public function testShowShareNotAuthenticated() {
$share = $this->getMock('\OC\Share20\IShare');
$share->method('getPassword')->willReturn('password');
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('validtoken')
->willReturn($share);
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with('files_sharing.sharecontroller.authenticate', ['token' => 'validtoken'])
->willReturn('redirect');
// Test without a not existing token
$response = $this->shareController->showShare('validtoken');
$expectedResponse = new RedirectResponse('redirect');
$this->assertEquals($expectedResponse, $response);
}
public function testShowShare() { public function testShowShare() {
$this->container['UserManager']->expects($this->exactly(2)) $owner = $this->getMock('OCP\IUser');
->method('userExists') $owner->method('getDisplayName')->willReturn('ownerDisplay');
->with($this->user) $owner->method('getUID')->willReturn('ownerUID');
->will($this->returnValue(true));
// Test without a not existing token $file = $this->getMock('OCP\Files\File');
$response = $this->shareController->showShare('ThisTokenShouldHopefullyNeverExistSoThatTheUnitTestWillAlwaysPass :)'); $file->method('getName')->willReturn('file1.txt');
$expectedResponse = new NotFoundResponse(); $file->method('getMimetype')->willReturn('text/plain');
$this->assertEquals($expectedResponse, $response); $file->method('getSize')->willReturn(33);
// Test with a password protected share and no authentication $share = $this->getMock('\OC\Share20\IShare');
$response = $this->shareController->showShare($this->token); $share->method('getId')->willReturn('42');
$expectedResponse = new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', array('token' => $this->token))); $share->method('getPassword')->willReturn('password');
$this->assertEquals($expectedResponse, $response); $share->method('getShareOwner')->willReturn($owner);
$share->method('getPath')->willReturn($file);
$share->method('getTarget')->willReturn('/file1.txt');
// Test with password protected share and authentication $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
$linkItem = Share::getShareByToken($this->token, false); $this->session->method('get')->with('public_link_authenticated')->willReturn('42');
\OC::$server->getSession()->set('public_link_authenticated', $linkItem['id']);
$response = $this->shareController->showShare($this->token); $this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
$this->config->method('getSystemValue')
->willReturnMap(
[
['max_filesize_animated_gifs_public_sharing', 10, 10],
['enable_previews', true, true],
]
);
$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$response = $this->shareController->showShare('token');
$sharedTmplParams = array( $sharedTmplParams = array(
'displayName' => $this->user, 'displayName' => 'ownerDisplay',
'owner' => $this->user, 'owner' => 'ownerUID',
'filename' => 'file1.txt', 'filename' => 'file1.txt',
'directory_path' => '/file1.txt', 'directory_path' => '/file1.txt',
'mimetype' => 'text/plain', 'mimetype' => 'text/plain',
'dirToken' => $this->token, 'dirToken' => 'token',
'sharingToken' => $this->token, 'sharingToken' => 'token',
'server2serversharing' => true, 'server2serversharing' => true,
'protected' => 'true', 'protected' => 'true',
'dir' => '', 'dir' => '',
@ -191,65 +333,31 @@ class ShareControllerTest extends \Test\TestCase {
$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy(); $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
$csp->addAllowedFrameDomain('\'self\''); $csp->addAllowedFrameDomain('\'self\'');
$expectedResponse = new TemplateResponse($this->container['AppName'], 'public', $sharedTmplParams, 'base'); $expectedResponse = new TemplateResponse($this->appName, 'public', $sharedTmplParams, 'base');
$expectedResponse->setContentSecurityPolicy($csp); $expectedResponse->setContentSecurityPolicy($csp);
$this->assertEquals($expectedResponse, $response); $this->assertEquals($expectedResponse, $response);
} }
public function testDownloadShare() { public function testDownloadShare() {
$share = $this->getMock('\OC\Share20\IShare');
$share->method('getPassword')->willReturn('password');
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('validtoken')
->willReturn($share);
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with('files_sharing.sharecontroller.authenticate', ['token' => 'validtoken'])
->willReturn('redirect');
// Test with a password protected share and no authentication // Test with a password protected share and no authentication
$response = $this->shareController->downloadShare($this->token); $response = $this->shareController->downloadShare('validtoken');
$expectedResponse = new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', $expectedResponse = new RedirectResponse('redirect');
array('token' => $this->token)));
$this->assertEquals($expectedResponse, $response); $this->assertEquals($expectedResponse, $response);
} }
/**
* @expectedException \OCP\Files\NotFoundException
*/
public function testShowShareWithDeletedFile() {
$this->container['UserManager']->expects($this->once())
->method('userExists')
->with($this->user)
->will($this->returnValue(true));
$view = new View('/'. $this->user . '/files');
$view->unlink('file1.txt');
$linkItem = Share::getShareByToken($this->token, false);
\OC::$server->getSession()->set('public_link_authenticated', $linkItem['id']);
$this->shareController->showShare($this->token);
}
/**
* @expectedException \OCP\Files\NotFoundException
*/
public function testDownloadShareWithDeletedFile() {
$this->container['UserManager']->expects($this->once())
->method('userExists')
->with($this->user)
->will($this->returnValue(true));
$view = new View('/'. $this->user . '/files');
$view->unlink('file1.txt');
$linkItem = Share::getShareByToken($this->token, false);
\OC::$server->getSession()->set('public_link_authenticated', $linkItem['id']);
$this->shareController->downloadShare($this->token);
}
/**
* @expectedException \Exception
* @expectedExceptionMessage Owner of the share does not exist anymore
*/
public function testShowShareWithNotExistingUser() {
$this->container['UserManager']->expects($this->once())
->method('userExists')
->with($this->user)
->will($this->returnValue(false));
$linkItem = Share::getShareByToken($this->token, false);
\OC::$server->getSession()->set('public_link_authenticated', $linkItem['id']);
$this->shareController->showShare($this->token);
}
} }

View File

@ -284,7 +284,11 @@ class DefaultShareProvider implements IShareProvider {
throw new ShareNotFound(); throw new ShareNotFound();
} }
$share = $this->createShare($data); try {
$share = $this->createShare($data);
} catch (InvalidShare $e) {
throw new ShareNotFound();
}
return $share; return $share;
} }
@ -328,13 +332,34 @@ class DefaultShareProvider implements IShareProvider {
} }
/** /**
* Get a share by token and if present verify the password * Get a share by token
* *
* @param string $token * @param string $token
* @param string $password * @return IShare
* @param Share * @throws ShareNotFound
*/ */
public function getShareByToken($token, $password = null) { public function getShareByToken($token) {
$qb = $this->dbConn->getQueryBuilder();
$cursor = $qb->select('*')
->from('share')
->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
->execute();
$data = $cursor->fetch();
if ($data === false) {
throw new ShareNotFound();
}
try {
$share = $this->createShare($data);
} catch (InvalidShare $e) {
throw new ShareNotFound();
}
return $share;
} }
/** /**

View File

@ -103,11 +103,11 @@ interface IShareProvider {
public function getSharedWithMe(IUser $user, $shareType = null); public function getSharedWithMe(IUser $user, $shareType = null);
/** /**
* Get a share by token and if present verify the password * Get a share by token
* *
* @param string $token * @param string $token
* @param string $password * @return IShare
* @param Share * @throws ShareNotFound
*/ */
public function getShareByToken($token, $password = null); public function getShareByToken($token);
} }

View File

@ -665,13 +665,47 @@ class Manager {
* Get the share by token possible with password * Get the share by token possible with password
* *
* @param string $token * @param string $token
* @param string $password
*
* @return Share * @return Share
* *
* @throws ShareNotFound * @throws ShareNotFound
*/ */
public function getShareByToken($token, $password=null) { public function getShareByToken($token) {
$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
$share = $provider->getShareByToken($token);
//TODO check if share expired
return $share;
}
/**
* Verify the password of a public share
*
* @param IShare $share
* @param string $password
* @return bool
*/
public function checkPassword(IShare $share, $password) {
if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK) {
//TODO maybe exception?
return false;
}
if ($password === null || $share->getPassword() === null) {
return false;
}
$newHash = '';
if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
return false;
}
if (!empty($newHash)) {
//TODO update hash!
}
return true;
} }
/** /**

View File

@ -721,4 +721,54 @@ class DefaultShareProviderTest extends \Test\TestCase {
$this->assertSame('token', $share2->getToken()); $this->assertSame('token', $share2->getToken());
$this->assertEquals($expireDate, $share2->getExpirationDate()); $this->assertEquals($expireDate, $share2->getExpirationDate());
} }
public function testGetShareByToken() {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->values([
'share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_LINK),
'share_with' => $qb->expr()->literal('password'),
'uid_owner' => $qb->expr()->literal('shareOwner'),
'uid_initiator' => $qb->expr()->literal('sharedBy'),
'item_type' => $qb->expr()->literal('file'),
'file_source' => $qb->expr()->literal(42),
'file_target' => $qb->expr()->literal('myTarget'),
'permissions' => $qb->expr()->literal(13),
'token' => $qb->expr()->literal('secrettoken'),
]);
$qb->execute();
$id = $qb->getLastInsertId();
$owner = $this->getMock('\OCP\IUser');
$owner->method('getUID')->willReturn('shareOwner');
$initiator = $this->getMock('\OCP\IUser');
$initiator->method('getUID')->willReturn('sharedBy');
$this->userManager->method('get')
->will($this->returnValueMap([
['sharedBy', $initiator],
['shareOwner', $owner],
]));
$file = $this->getMock('\OCP\Files\File');
$this->rootFolder->method('getUserFolder')->with('shareOwner')->will($this->returnSelf());
$this->rootFolder->method('getById')->with(42)->willReturn([$file]);
$share = $this->provider->getShareByToken('secrettoken');
$this->assertEquals($id, $share->getId());
$this->assertSame($owner, $share->getShareOwner());
$this->assertSame($initiator, $share->getSharedBy());
$this->assertSame('secrettoken', $share->getToken());
$this->assertSame('password', $share->getPassword());
$this->assertSame(null, $share->getSharedWith());
}
/**
* @expectedException \OC\Share20\Exception\ShareNotFound
*/
public function testGetShareByTokenNotFound() {
$this->provider->getShareByToken('invalidtoken');
}
} }

View File

@ -1478,6 +1478,71 @@ class ManagerTest extends \Test\TestCase {
$manager->createShare($share); $manager->createShare($share);
} }
public function testGetShareByToken() {
$factory = $this->getMock('\OC\Share20\IProviderFactory');
$manager = new Manager(
$this->logger,
$this->config,
$this->secureRandom,
$this->hasher,
$this->mountManager,
$this->groupManager,
$this->l,
$factory
);
$share = $this->getMock('\OC\Share20\IShare');
$factory->expects($this->once())
->method('getProviderForType')
->with(\OCP\Share::SHARE_TYPE_LINK)
->willReturn($this->defaultProvider);
$this->defaultProvider->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
$ret = $manager->getShareByToken('token');
$this->assertSame($share, $ret);
}
public function testCheckPasswordNoLinkShare() {
$share = $this->getMock('\OC\Share20\IShare');
$share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_USER);
$this->assertFalse($this->manager->checkPassword($share, 'password'));
}
public function testCheckPasswordNoPassword() {
$share = $this->getMock('\OC\Share20\IShare');
$share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK);
$this->assertFalse($this->manager->checkPassword($share, 'password'));
$share->method('getPassword')->willReturn('password');
$this->assertFalse($this->manager->checkPassword($share, null));
}
public function testCheckPasswordInvalidPassword() {
$share = $this->getMock('\OC\Share20\IShare');
$share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK);
$share->method('getPassword')->willReturn('password');
$this->hasher->method('verify')->with('invalidpassword', 'password', '')->willReturn(false);
$this->assertFalse($this->manager->checkPassword($share, 'invalidpassword'));
}
public function testCheckPasswordValidPassword() {
$share = $this->getMock('\OC\Share20\IShare');
$share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK);
$share->method('getPassword')->willReturn('passwordHash');
$this->hasher->method('verify')->with('password', 'passwordHash', '')->willReturn(true);
$this->assertTrue($this->manager->checkPassword($share, 'password'));
}
} }
class DummyPassword { class DummyPassword {