Skip to content
This repository has been archived by the owner on Nov 25, 2020. It is now read-only.

Commit

Permalink
Re-setting admin auth for Websocket authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
ghecquet committed Jun 6, 2016
2 parents a1b4abb + 2a77d7b commit 8212433
Show file tree
Hide file tree
Showing 136 changed files with 2,582 additions and 1,699 deletions.
68 changes: 28 additions & 40 deletions core/src/core/src/pydio/Core/Controller/Controller.php
Expand Up @@ -26,6 +26,8 @@
use Pydio\Core\Exception\AuthRequiredException;
use Pydio\Core\Exception\PydioException;
use Pydio\Auth\Core\AJXP_Safe;
use Pydio\Core\Model\Context;
use Pydio\Core\Model\ContextInterface;
use Pydio\Core\Services;
use Pydio\Core\Services\AuthService;
use Pydio\Core\Services\ConfService;
Expand All @@ -35,6 +37,7 @@
use Pydio\Tasks\Task;
use Pydio\Tasks\TaskService;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequestFactory;

defined('AJXP_EXEC') or die( 'Access not allowed');
/**
Expand Down Expand Up @@ -69,7 +72,8 @@ class Controller
private static function initXPath($useCache = false)
{
if (!isSet(self::$xPath)) {
$registry = ConfService::getFilteredXMLRegistry(false, false, $useCache);
$ctx = Context::fromGlobalServices();
$registry = PluginsService::getInstance($ctx)->getFilteredXMLRegistry(false, false, $useCache);
self::$xPath = new \DOMXPath($registry);
}
return self::$xPath;
Expand Down Expand Up @@ -245,11 +249,31 @@ public static function run(ServerRequestInterface $request, &$actionNode = null)
return $response;
}

/**
* @param Task $task
*/
public static function applyTaskInBackground(Task $task){

$parameters = $task->getParameters();
$task->setStatus(Task::STATUS_RUNNING);
TaskService::getInstance()->updateTask($task);
self::applyActionInBackground($task->getWsId(), $task->getAction(), $parameters, $task->getUserId(), "", $task->getId());

}

/**
* @param ContextInterface $context
* @param string $action
* @param array $parameters
* @return ServerRequestInterface
*/
public static function executableRequest(ContextInterface $context, $action, $parameters = []){
$request = ServerRequestFactory::fromGlobals();
$request = $request
->withAttribute("ctx", $context)
->withAttribute("action", $action)
->withParsedBody($parameters);
return $request;
}

/**
Expand All @@ -265,24 +289,6 @@ public static function applyTaskInBackground(Task $task){
*/
public static function applyActionInBackground($currentRepositoryId, $actionName, $parameters, $user ="", $statusFile = "", $taskId = null)
{
/*
if (empty($user)) {
if(AuthService::usersEnabled() && AuthService::getLoggedUser() !== null) $user = AuthService::getLoggedUser()->getId();
else $user = "shared";
}
$fName = AJXP_DATA_PATH."/plugins/mq.serial/worker-queue";
$fData = file_get_contents($fName);
$data = json_decode($fData, true);
$data[] = array(
"userId" => $user,
"repoId" => $currentRepositoryId,
"actionName" => $actionName,
"parameters" => $parameters
);
file_put_contents($fName, json_encode($data));
return ;
*/


$token = md5(time());
$logDir = AJXP_CACHE_DIR."/cmd_outputs";
Expand All @@ -295,22 +301,7 @@ public static function applyActionInBackground($currentRepositoryId, $actionName
$user = "shared";
}
}
/*
require_once(AJXP_INSTALL_PATH."/".AJXP_PLUGINS_FOLDER."/core.mq/vendor/autoload.php");
$nsq = new nsqphp\nsqphp;
$nsq->publishTo("localhost", 1);
$payload = array(
'msg' => 'bg',
'data' => [
'repository_id' => $currentRepositoryId,
'user_id' => $user,
'action' => $actionName,
'parameters' => $parameters
]);
$nsq->publish('pydio', new nsqphp\Message\Message(json_encode($payload)));
return;
*/

if (Services\AuthService::usersEnabled()) {
$cKey = ConfService::getCoreConf("AJXP_CLI_SECRET_KEY", "conf");
if(empty($cKey)){
Expand Down Expand Up @@ -343,10 +334,7 @@ public static function applyActionInBackground($currentRepositoryId, $actionName
}
}

$repoObject = ConfService::getRepository();
if(empty($repoObject)){
$repoObject = ConfService::getRepositoryById($currentRepositoryId);
}
$repoObject = ConfService::getRepositoryById($currentRepositoryId);
$clearEnv = false;
if($repoObject->getOption("USE_SESSION_CREDENTIALS")){
$encodedCreds = AJXP_Safe::getEncodedCredentialString();
Expand Down Expand Up @@ -504,7 +492,7 @@ private static function handleRequest($callback, ServerRequestInterface &$reques
}else{

$httpVars = $request->getParsedBody();
$result = $plugInstance->$methodName($request->getAttribute("action"), $httpVars, $_FILES);
$result = $plugInstance->$methodName($request->getAttribute("action"), $httpVars, $_FILES, $request->getAttribute("ctx"));
// May have been modified
$request = $request->withParsedBody($httpVars);

Expand Down
6 changes: 4 additions & 2 deletions core/src/core/src/pydio/Core/Controller/XMLWriter.php
Expand Up @@ -22,6 +22,7 @@

use Pydio\Access\Core\Model\AJXP_Node;
use Pydio\Access\Core\IAjxpWrapperProvider;
use Pydio\Core\Model\RepositoryInterface;
use Pydio\Core\Utils\Utils;
use Pydio\Core\Services;
use Pydio\Core\Services\AuthService;
Expand Down Expand Up @@ -420,15 +421,16 @@ public static function triggerBgJSAction($jsCode, $messageId, $print=true, $dela
* List all bookmmarks as XML
* @static
* @param $allBookmarks
* @param RepositoryInterface $repository
* @param bool $print
* @param string $format legacy|node_list
* @return string
*/
public static function writeBookmarks($allBookmarks, $print = true, $format = "legacy")
public static function writeBookmarks($allBookmarks, $repository, $print = true, $format = "legacy")
{
$driver = false;
if ($format == "node_list") {
$driver = ConfService::loadRepositoryDriver();
$driver = $repository->getDriverInstance();
if (!($driver instanceof IAjxpWrapperProvider)) {
$driver = false;
}
Expand Down
49 changes: 49 additions & 0 deletions core/src/core/src/pydio/Core/Exception/RepositoryLoadException.php
@@ -0,0 +1,49 @@
<?php
/*
* Copyright 2007-2016 Abstrium <contact (at) pydio.com>
* This file is part of Pydio.
*
* Pydio is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com/>.
*/
namespace Pydio\Core\Exception;

use Pydio\Core\Model\RepositoryInterface;

defined('AJXP_EXEC') or die('Access not allowed');


class RepositoryLoadException extends PydioException
{
/**
* @var RepositoryInterface
*/
private $repository;
/**
* RepositoryLoadException constructor.
* @param RepositoryInterface $repository
* @param array $errors
*/
public function __construct($repository, $errors)
{
$message = "Error while loading workspace ".$repository->getDisplay()." : ".implode("\n-", $errors);
$this->repository = $repository;
parent::__construct($message, false, 5000);
}

public function getRepository(){
return $this->repository;
}
}
18 changes: 16 additions & 2 deletions core/src/core/src/pydio/Core/Http/Cli/AuthCliMiddleware.php
Expand Up @@ -23,8 +23,11 @@
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Pydio\Auth\Core\AJXP_Safe;
use Pydio\Core\Controller\Controller;
use Pydio\Core\Exception\AuthRequiredException;
use Pydio\Core\Http\Server;
use Pydio\Core\Model\Context;
use Pydio\Core\PluginFramework\PluginsService;
use Pydio\Core\Services\AuthService;
use Pydio\Core\Services\ConfService;
use Zend\Diactoros\Response;
Expand All @@ -43,6 +46,8 @@ class AuthCliMiddleware
*/
public static function handleRequest(ServerRequestInterface $requestInterface, ResponseInterface $responseInterface, callable $next = null){

$driverImpl = ConfService::getAuthDriverImpl();
PluginsService::getInstance()->setPluginUniqueActiveForType("auth", $driverImpl->getName(), $driverImpl);

$options = $requestInterface->getAttribute("cli-options");
$optUser = $options["u"];
Expand Down Expand Up @@ -156,8 +161,12 @@ public static function handleRequest(ServerRequestInterface $requestInterface, R
$loggedUser = AuthService::getLoggedUser();
if($loggedUser == null) continue;
ConfService::switchRootDir($optRepoId, true);
ConfService::reloadServicesAndActivePlugins();
Controller::registryReset();
$subResponse = new Response();
$ctx = new Context();
$ctx->setUserObject($loggedUser);
$ctx->setRepositoryId($optRepoId);
$requestInterface = $requestInterface->withAttribute("ctx", $ctx);

$subResponse = Server::callNextMiddleWareAndRewind(function($middleware){
return (is_array($middleware) && $middleware["0"] == "Pydio\\Core\\Http\\Cli\\AuthCliMiddleware" && $middleware[1] == "handleRequest");
Expand All @@ -179,7 +188,12 @@ public static function handleRequest(ServerRequestInterface $requestInterface, R
}else{

ConfService::switchRootDir($optRepoId, true);
ConfService::reloadServicesAndActivePlugins();

$ctx = new Context();
$ctx->setUserObject($loggedUser);
$ctx->setRepositoryId($optRepoId);
$requestInterface = $requestInterface->withAttribute("ctx", $ctx);

return Server::callNextMiddleWare($requestInterface, $responseInterface, $next);

}
Expand Down
32 changes: 23 additions & 9 deletions core/src/core/src/pydio/Core/Http/Middleware/AuthMiddleware.php
Expand Up @@ -26,7 +26,10 @@
use Pydio\Core\Exception\AuthRequiredException;
use Pydio\Core\Exception\NoActiveWorkspaceException;
use Pydio\Core\Exception\PydioException;
use Pydio\Core\Exception\RepositoryLoadException;
use Pydio\Core\Http\Server;
use Pydio\Core\Model\Context;
use Pydio\Core\PluginFramework\PluginsService;
use Pydio\Core\Services\AuthService;
use Pydio\Core\Services\ConfService;
use Zend\Diactoros\Response\EmptyResponse;
Expand All @@ -46,27 +49,33 @@ class AuthMiddleware
*/
public static function handleRequest(\Psr\Http\Message\ServerRequestInterface &$requestInterface, \Psr\Http\Message\ResponseInterface &$responseInterface, callable $next = null){

$response = FrontendsLoader::frontendsAsAuthMiddlewares($requestInterface, $responseInterface);
if($response != null){
return $response;
}

self::bootSessionServer($requestInterface);

try{
$driverImpl = ConfService::getAuthDriverImpl();
PluginsService::getInstance()->setPluginUniqueActiveForType("auth", $driverImpl->getName(), $driverImpl);

ConfService::reloadServicesAndActivePlugins();
$response = FrontendsLoader::frontendsAsAuthMiddlewares($requestInterface, $responseInterface);
if($response != null){
return $response;
}
self::bootSessionServer($requestInterface);

}catch (NoActiveWorkspaceException $ex){
} catch (NoActiveWorkspaceException $ex){

$logged = AuthService::getLoggedUser();
if($logged !== null) $lock = $logged->getLock();
if(empty($lock)){
throw new AuthRequiredException();
}

} catch (RepositoryLoadException $r){

ConfService::switchBackAfterRepositoryError($r->getRepository());
throw $r;

}

$requestInterface = $requestInterface->withAttribute("ctx", Context::fromGlobalServices());
try{

return Server::callNextMiddleWare($requestInterface, $responseInterface, $next);
Expand All @@ -78,6 +87,11 @@ public static function handleRequest(\Psr\Http\Message\ServerRequestInterface &$
}else{
return new EmptyResponse();
}
} catch (RepositoryLoadException $r){

ConfService::switchBackAfterRepositoryError($r->getRepository());
throw $r;

}

}
Expand All @@ -99,7 +113,7 @@ protected static function bootSessionServer(ServerRequestInterface $request){
if ($loggedUser != null) {
$res = ConfService::switchUserToActiveRepository($loggedUser, (isSet($parameters["tmp_repository_id"])?$parameters["tmp_repository_id"]:"-1"));
if (!$res) {
AuthService::disconnect();
throw new NoActiveWorkspaceException();
}
}
}
Expand Down
22 changes: 14 additions & 8 deletions core/src/core/src/pydio/Core/Http/Rest/RestAuthMiddleware.php
Expand Up @@ -24,6 +24,8 @@
use Pydio\Authfront\Core\FrontendsLoader;
use Pydio\Core\Exception\PydioException;
use Pydio\Core\Exception\WorkspaceNotFoundException;
use Pydio\Core\Model\Context;
use Pydio\Core\PluginFramework\PluginsService;
use Pydio\Core\Services\AuthService;
use Pydio\Core\Services\ConfService;

Expand All @@ -42,35 +44,39 @@ class RestAuthMiddleware
*/
public static function handleRequest(\Psr\Http\Message\ServerRequestInterface &$requestInterface, \Psr\Http\Message\ResponseInterface &$responseInterface, callable $next = null){

$driverImpl = ConfService::getAuthDriverImpl();
PluginsService::getInstance()->setPluginUniqueActiveForType("auth", $driverImpl->getName(), $driverImpl);

$response = FrontendsLoader::frontendsAsAuthMiddlewares($requestInterface, $responseInterface);
if($response != null){
return $response;
}

if(AuthService::getLoggedUser() == null){
header('HTTP/1.0 401 Unauthorized');
echo 'You are not authorized to access this API.';
exit;
$responseInterface = $responseInterface->withStatus(401);
$responseInterface->getBody()->write('You are not authorized to access this API.');
return $responseInterface;
}

$repoID = $requestInterface->getAttribute("repository_id");
if($repoID == 'pydio'){
ConfService::switchRootDir();
ConfService::getRepository();
$repo = ConfService::getRepository();
}else{
$repo = ConfService::findRepositoryByIdOrAlias($repoID);
if ($repo == null) {
throw new WorkspaceNotFoundException($repoID);
}
if(!ConfService::repositoryIsAccessible($repo->getId(), $repo, AuthService::getLoggedUser(), false, true)){
header('HTTP/1.0 401 Unauthorized');
echo 'You are not authorized to access this workspace.';
exit;
$responseInterface = $responseInterface->withStatus(401);
$responseInterface->getBody()->write('You are not authorized to access this API.');
return $responseInterface;
}
ConfService::switchRootDir($repo->getId());
}

ConfService::reloadServicesAndActivePlugins();
$context = Context::contextWithObjects(AuthService::getLoggedUser(), $repo);
$requestInterface = $requestInterface->withAttribute("ctx", $context);

return RestServer::callNextMiddleWare($requestInterface, $responseInterface, $next);

Expand Down
Expand Up @@ -185,7 +185,7 @@ protected function bodyHandler($callback, ServerRequestInterface &$request, Resp
*
* @param string|object $destination
* @param object $sourceObject
* @return object
* @return mixed
*/
public static function cast($destination, $sourceObject)
{
Expand Down

0 comments on commit 8212433

Please sign in to comment.