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(
$c->query('AppName'),
$c->query('Request'),
$c->query('UserSession'),
$server->getAppConfig(),
$server->getConfig(),
$c->query('URLGenerator'),
$c->query('UserManager'),
$server->getURLGenerator(),
$server->getUserManager(),
$server->getLogger(),
$server->getActivityManager()
$server->getActivityManager(),
$server->getShareManager(),
$server->getSession(),
$server->getPreviewManager(),
$server->getRootFolder()
);
});
$container->registerService('ExternalSharesController', function (SimpleContainer $c) {
@ -68,15 +70,6 @@ class Application extends App {
/**
* 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) {
return $server->getHTTPClientService();
});

View File

@ -41,14 +41,18 @@ use OCP\IRequest;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\NotFoundResponse;
use OC\URLGenerator;
use OC\AppConfig;
use OCP\IURLGenerator;
use OCP\IConfig;
use OCP\ILogger;
use OCP\IUserManager;
use OCP\ISession;
use OCP\IPreview;
use OCA\Files_Sharing\Helper;
use OCP\User;
use OCP\Util;
use OCA\Files_Sharing\Activity;
use \OCP\Files\NotFoundException;
use \OC\Share20\IShare;
use OCP\Files\IRootFolder;
/**
* Class ShareController
@ -57,50 +61,60 @@ use \OCP\Files\NotFoundException;
*/
class ShareController extends Controller {
/** @var \OC\User\Session */
protected $userSession;
/** @var \OC\AppConfig */
protected $appConfig;
/** @var \OCP\IConfig */
/** @var IConfig */
protected $config;
/** @var \OC\URLGenerator */
/** @var IURLGenerator */
protected $urlGenerator;
/** @var \OC\User\Manager */
/** @var IUserManager */
protected $userManager;
/** @var \OCP\ILogger */
/** @var ILogger */
protected $logger;
/** @var OCP\Activity\IManager */
protected $activityManager;
/** @var OC\Share20\Manager */
protected $shareManager;
/** @var ISession */
protected $session;
/** @var IPreview */
protected $previewManager;
/** @var IRootFolder */
protected $rootFolder;
/**
* @param string $appName
* @param IRequest $request
* @param OC\User\Session $userSession
* @param AppConfig $appConfig
* @param OCP\IConfig $config
* @param URLGenerator $urlGenerator
* @param OCP\IUserManager $userManager
* @param IConfig $config
* @param IURLGenerator $urlGenerator
* @param IUserManager $userManager
* @param ILogger $logger
* @param OCP\Activity\IManager $activityManager
* @param \OC\Share20\Manager $shareManager
* @param ISession $session
* @param IPreview $previewManager
* @param IRootFolder $rootFolder
*/
public function __construct($appName,
IRequest $request,
OC\User\Session $userSession,
AppConfig $appConfig,
OCP\IConfig $config,
URLGenerator $urlGenerator,
OCP\IUserManager $userManager,
IConfig $config,
IURLGenerator $urlGenerator,
IUserManager $userManager,
ILogger $logger,
OCP\Activity\IManager $activityManager) {
\OCP\Activity\IManager $activityManager,
\OC\Share20\Manager $shareManager,
ISession $session,
IPreview $previewManager,
IRootFolder $rootFolder) {
parent::__construct($appName, $request);
$this->userSession = $userSession;
$this->appConfig = $appConfig;
$this->config = $config;
$this->urlGenerator = $urlGenerator;
$this->userManager = $userManager;
$this->logger = $logger;
$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
*/
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)));
}
@ -130,12 +144,15 @@ class ShareController extends Controller {
* @return RedirectResponse|TemplateResponse
*/
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();
}
$authenticate = Helper::authenticate($linkItem, $password);
$authenticate = $this->linkShareAuth($share, $password);
if($authenticate === true) {
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');
}
/**
* 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
* @NoCSRFRequired
@ -157,54 +202,70 @@ class ShareController extends Controller {
\OC_User::setIncognitoMode(true);
// Check whether share exists
$linkItem = Share::getShareByToken($token, false);
if($linkItem === false) {
try {
$share = $this->shareManager->getShareByToken($token);
} catch (\OC\Share20\Exception\ShareNotFound $e) {
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
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',
array('token' => $token)));
}
if (Filesystem::isReadable($originalSharePath . $path)) {
$getPath = Filesystem::normalizePath($path);
$originalSharePath .= $path;
} else {
// We can't get the path of a file share
if ($share->getPath() instanceof \OCP\Files\File && $path !== '') {
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['displayName'] = User::getDisplayName($shareOwner);
$shareTmpl['owner'] = $shareOwner;
$shareTmpl['filename'] = $file;
$shareTmpl['directory_path'] = $linkItem['file_target'];
$shareTmpl['mimetype'] = Filesystem::getMimeType($originalSharePath);
$shareTmpl['previewSupported'] = \OC::$server->getPreviewManager()->isMimeSupported($shareTmpl['mimetype']);
$shareTmpl['dirToken'] = $linkItem['token'];
$shareTmpl['displayName'] = $share->getShareOwner()->getDisplayName();
$shareTmpl['owner'] = $share->getShareOwner()->getUID();
$shareTmpl['filename'] = $share->getPath()->getName();
$shareTmpl['directory_path'] = $share->getTarget();
$shareTmpl['mimetype'] = $share->getPath()->getMimetype();
$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getPath()->getMimetype());
$shareTmpl['dirToken'] = $token;
$shareTmpl['sharingToken'] = $token;
$shareTmpl['server2serversharing'] = Helper::isOutgoingServer2serverShareEnabled();
$shareTmpl['protected'] = isset($linkItem['share_with']) ? 'true' : 'false';
$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
$shareTmpl['dir'] = '';
$nonHumanFileSize = \OC\Files\Filesystem::filesize($originalSharePath);
$shareTmpl['nonHumanFileSize'] = $nonHumanFileSize;
$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($nonHumanFileSize);
$shareTmpl['nonHumanFileSize'] = $share->getPath()->getSize();
$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getPath()->getSize());
// Show file list
if (Filesystem::is_dir($originalSharePath)) {
$shareTmpl['dir'] = $getPath;
$maxUploadFilesize = Util::maxUploadFilesize($originalSharePath);
$freeSpace = Util::freeSpace($originalSharePath);
if ($share->getPath() instanceof \OCP\Files\Folder) {
$shareTmpl['dir'] = $rootFolder->getRelativePath($path->getPath());
/*
* 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();
$maxUploadFilesize = min($freeSpace, $uploadLimit);
$folder = new Template('files', 'list', '');
$folder->assign('dir', $getPath);
$folder->assign('dirToken', $linkItem['token']);
$folder->assign('dir', $rootFolder->getRelativePath($path->getPath()));
$folder->assign('dirToken', $token);
$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
$folder->assign('isPublic', true);
$folder->assign('publicUploadEnabled', 'no');
@ -242,14 +303,12 @@ class ShareController extends Controller {
public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
\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
if (isset($linkItem['share_with'])) {
if(!Helper::authenticate($linkItem)) {
return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
array('token' => $token)));
}
if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
['token' => $token]));
}
$files_list = null;
@ -257,41 +316,86 @@ class ShareController extends Controller {
$files_list = json_decode($files);
// in case we get only a single file
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
if (isset($originalSharePath) && Filesystem::isReadable($originalSharePath . $path)) {
$originalSharePath = Filesystem::normalizePath($originalSharePath . $path);
$isDir = \OC\Files\Filesystem::is_dir($originalSharePath);
// Single file share
if ($share->getPath() 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($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 = [];
if (!$isDir) {
// Single file public share
$activities[$originalSharePath] = Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
// Try to get the path
if ($path !== '') {
try {
$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)) {
// Only some files are downloaded
/** @var \OCP\Files\Folder $node */
// Subset of files is downloaded
foreach ($files_list as $file) {
$filePath = Filesystem::normalizePath($originalSharePath . '/' . $file);
$isDir = \OC\Files\Filesystem::is_dir($filePath);
$activities[$filePath] = ($isDir) ? Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED : Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
$subNode = $node->get($file);
$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 {
// The folder is downloaded
$activities[$originalSharePath] = Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
}
foreach ($activities as $filePath => $subject) {
$this->activityManager->publishActivity(
'files_sharing', $subject, array($filePath), '', array(),
$filePath, '', $linkItem['uid_owner'], Activity::TYPE_PUBLIC_LINKS, Activity::PRIORITY_MEDIUM
);
$event = $this->activityManager->generateEvent();
$event->setApp('files_sharing')
->setType(Activity::TYPE_PUBLIC_LINKS)
->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED, [$userFolder->getRelativePath($node->getPath())])
->setAffectedUser($share->getShareOwner()->getUID())
->setObject('files', $node->getId(), $userFolder->getRelativePath($node->getPath()));
$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
* the content must not be longer than 32 characters and must only contain
@ -318,30 +422,4 @@ class ShareController extends Controller {
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+, ...)*/?>
<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; ?>
<div id="notification-container">

View File

@ -30,15 +30,13 @@
namespace OCA\Files_Sharing\Controllers;
use OC\Files\Filesystem;
use OCA\Files_Sharing\AppInfo\Application;
use OC\Share20\Exception\ShareNotFound;
use OCP\AppFramework\Http\NotFoundResponse;
use OCP\AppFramework\IAppContainer;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\ISession;
use OCP\Security\ISecureRandom;
use OC\Files\View;
use OCP\Share;
use OC\URLGenerator;
use OCP\IURLGenerator;
/**
* @group DB
@ -47,33 +45,49 @@ use OC\URLGenerator;
*/
class ShareControllerTest extends \Test\TestCase {
/** @var IAppContainer */
private $container;
/** @var string */
private $user;
/** @var string */
private $token;
/** @var string */
private $oldUser;
/** @var string */
private $appName = 'files_sharing';
/** @var ShareController */
private $shareController;
/** @var URLGenerator */
/** @var IURLGenerator | \PHPUnit_Framework_MockObject_MockObject */
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() {
$app = new Application();
$this->container = $app->getContainer();
$this->container['Config'] = $this->getMockBuilder('\OCP\IConfig')
->disableOriginalConstructor()->getMock();
$this->container['AppName'] = 'files_sharing';
$this->container['UserSession'] = $this->getMockBuilder('\OC\User\Session')
->disableOriginalConstructor()->getMock();
$this->container['URLGenerator'] = $this->getMockBuilder('\OC\URLGenerator')
->disableOriginalConstructor()->getMock();
$this->container['UserManager'] = $this->getMockBuilder('\OCP\IUserManager')
->disableOriginalConstructor()->getMock();
$this->urlGenerator = $this->container['URLGenerator'];
$this->shareController = $this->container['ShareController'];
$this->appName = 'files_sharing';
$this->shareManager = $this->getMockBuilder('\OC\Share20\Manager')->disableOriginalConstructor()->getMock();
$this->urlGenerator = $this->getMock('\OCP\IURLGenerator');
$this->session = $this->getMock('\OCP\ISession');
$this->previewManager = $this->getMock('\OCP\IPreview');
$this->config = $this->getMock('\OCP\IConfig');
$this->shareController = new \OCA\Files_Sharing\Controllers\ShareController(
$this->appName,
$this->getMock('\OCP\IRequest'),
$this->config,
$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
$this->oldUser = \OC_User::getUser();
@ -84,17 +98,6 @@ class ShareControllerTest extends \Test\TestCase {
\OC::$server->getUserManager()->createUser($this->user, $this->user);
\OC_Util::tearDownFS();
$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() {
@ -112,72 +115,211 @@ class ShareControllerTest extends \Test\TestCase {
\OC_Util::setupFS($this->oldUser);
}
public function testShowAuthenticate() {
$linkItem = \OCP\Share::getShareByToken($this->token, false);
public function testShowAuthenticateNotAuthenticated() {
$share = $this->getMock('\OC\Share20\IShare');
// Test without being authenticated
$response = $this->shareController->showAuthenticate($this->token);
$expectedResponse = new TemplateResponse($this->container['AppName'], 'authenticate', array(), 'guest');
$this->assertEquals($expectedResponse, $response);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
// Test with being authenticated for another file
\OC::$server->getSession()->set('public_link_authenticated', $linkItem['id']-1);
$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)));
$response = $this->shareController->showAuthenticate('token');
$expectedResponse = new TemplateResponse($this->appName, 'authenticate', [], 'guest');
$this->assertEquals($expectedResponse, $response);
}
public function testAuthenticate() {
// Test without a not existing token
$response = $this->shareController->authenticate('ThisTokenShouldHopefullyNeverExistSoThatTheUnitTestWillAlwaysPass :)');
public function testShowAuthenticateAuthenticatedForDifferentShare() {
$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('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();
$this->assertEquals($expectedResponse, $response);
}
// Test with a valid password
$response = $this->shareController->authenticate($this->token, 'IAmPasswordProtected!');
$expectedResponse = new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $this->token)));
$this->assertEquals($expectedResponse, $response);
public function testAuthenticateValidPassword() {
$share = $this->getMock('\OC\Share20\IShare');
$share->method('getId')->willReturn(42);
// Test with a invalid password
$response = $this->shareController->authenticate($this->token, 'WrongPw!');
$expectedResponse = new TemplateResponse($this->container['AppName'], 'authenticate', array('wrongpw' => true), 'guest');
$this->shareManager
->expects($this->once())
->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);
}
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() {
$this->container['UserManager']->expects($this->exactly(2))
->method('userExists')
->with($this->user)
->will($this->returnValue(true));
$owner = $this->getMock('OCP\IUser');
$owner->method('getDisplayName')->willReturn('ownerDisplay');
$owner->method('getUID')->willReturn('ownerUID');
// Test without a not existing token
$response = $this->shareController->showShare('ThisTokenShouldHopefullyNeverExistSoThatTheUnitTestWillAlwaysPass :)');
$expectedResponse = new NotFoundResponse();
$this->assertEquals($expectedResponse, $response);
$file = $this->getMock('OCP\Files\File');
$file->method('getName')->willReturn('file1.txt');
$file->method('getMimetype')->willReturn('text/plain');
$file->method('getSize')->willReturn(33);
// Test with a password protected share and no authentication
$response = $this->shareController->showShare($this->token);
$expectedResponse = new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', array('token' => $this->token)));
$this->assertEquals($expectedResponse, $response);
$share = $this->getMock('\OC\Share20\IShare');
$share->method('getId')->willReturn('42');
$share->method('getPassword')->willReturn('password');
$share->method('getShareOwner')->willReturn($owner);
$share->method('getPath')->willReturn($file);
$share->method('getTarget')->willReturn('/file1.txt');
// Test with password protected share and authentication
$linkItem = Share::getShareByToken($this->token, false);
\OC::$server->getSession()->set('public_link_authenticated', $linkItem['id']);
$response = $this->shareController->showShare($this->token);
$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
$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(
'displayName' => $this->user,
'owner' => $this->user,
'displayName' => 'ownerDisplay',
'owner' => 'ownerUID',
'filename' => 'file1.txt',
'directory_path' => '/file1.txt',
'mimetype' => 'text/plain',
'dirToken' => $this->token,
'sharingToken' => $this->token,
'dirToken' => 'token',
'sharingToken' => 'token',
'server2serversharing' => true,
'protected' => 'true',
'dir' => '',
@ -191,65 +333,31 @@ class ShareControllerTest extends \Test\TestCase {
$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
$csp->addAllowedFrameDomain('\'self\'');
$expectedResponse = new TemplateResponse($this->container['AppName'], 'public', $sharedTmplParams, 'base');
$expectedResponse = new TemplateResponse($this->appName, 'public', $sharedTmplParams, 'base');
$expectedResponse->setContentSecurityPolicy($csp);
$this->assertEquals($expectedResponse, $response);
}
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
$response = $this->shareController->downloadShare($this->token);
$expectedResponse = new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
array('token' => $this->token)));
$response = $this->shareController->downloadShare('validtoken');
$expectedResponse = new RedirectResponse('redirect');
$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();
}
$share = $this->createShare($data);
try {
$share = $this->createShare($data);
} catch (InvalidShare $e) {
throw new ShareNotFound();
}
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 $password
* @param Share
* @return IShare
* @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);
/**
* Get a share by token and if present verify the password
* Get a share by token
*
* @param string $token
* @param string $password
* @param Share
* @return IShare
* @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
*
* @param string $token
* @param string $password
*
* @return Share
*
* @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->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);
}
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 {