Merge pull request #846 from nextcloud/provisioning_api_ocs

Move Provisioning API to the AppFramework
This commit is contained in:
Joas Schilling 2016-08-17 10:23:13 +02:00 committed by GitHub
commit 027069cbae
15 changed files with 1000 additions and 919 deletions

View file

@ -26,53 +26,40 @@
* *
*/ */
namespace OCA\Provisioning_API\AppInfo;
use OCA\Provisioning_API\Apps; use OCA\Provisioning_API\Apps;
use OCA\Provisioning_API\Groups;
use OCA\Provisioning_API\Users; use OCA\Provisioning_API\Users;
use OCP\API; use OCP\API;
// Users $app = new \OCA\Provisioning_API\AppInfo\Application();
$users = new Users( $app->registerRoutes($this, [
\OC::$server->getUserManager(), 'ocs' => [
\OC::$server->getConfig(), // Apps
\OC::$server->getGroupManager(), ['root' => '/cloud', 'name' => 'Apps#getApps', 'url' => '/apps', 'verb' => 'GET'],
\OC::$server->getUserSession(), ['root' => '/cloud', 'name' => 'Apps#getAppInfo', 'url' => '/apps/{app}', 'verb' => 'GET'],
\OC::$server->getLogger() ['root' => '/cloud', 'name' => 'Apps#enable', 'url' => '/apps/{app}', 'verb' => 'POST'],
); ['root' => '/cloud', 'name' => 'Apps#disable', 'url' => '/apps/{app}', 'verb' => 'DELETE'],
API::register('get', '/cloud/users', [$users, 'getUsers'], 'provisioning_api', API::SUBADMIN_AUTH);
API::register('post', '/cloud/users', [$users, 'addUser'], 'provisioning_api', API::SUBADMIN_AUTH);
API::register('get', '/cloud/users/{userid}', [$users, 'getUser'], 'provisioning_api', API::USER_AUTH);
API::register('put', '/cloud/users/{userid}', [$users, 'editUser'], 'provisioning_api', API::USER_AUTH);
API::register('delete', '/cloud/users/{userid}', [$users, 'deleteUser'], 'provisioning_api', API::SUBADMIN_AUTH);
API::register('put', '/cloud/users/{userid}/enable', [$users, 'enableUser'], 'provisioning_api', API::SUBADMIN_AUTH);
API::register('put', '/cloud/users/{userid}/disable', [$users, 'disableUser'], 'provisioning_api', API::SUBADMIN_AUTH);
API::register('get', '/cloud/users/{userid}/groups', [$users, 'getUsersGroups'], 'provisioning_api', API::USER_AUTH);
API::register('post', '/cloud/users/{userid}/groups', [$users, 'addToGroup'], 'provisioning_api', API::SUBADMIN_AUTH);
API::register('delete', '/cloud/users/{userid}/groups', [$users, 'removeFromGroup'], 'provisioning_api', API::SUBADMIN_AUTH);
API::register('post', '/cloud/users/{userid}/subadmins', [$users, 'addSubAdmin'], 'provisioning_api', API::ADMIN_AUTH);
API::register('delete', '/cloud/users/{userid}/subadmins', [$users, 'removeSubAdmin'], 'provisioning_api', API::ADMIN_AUTH);
API::register('get', '/cloud/users/{userid}/subadmins', [$users, 'getUserSubAdminGroups'], 'provisioning_api', API::ADMIN_AUTH);
// Groups // Groups
$groups = new Groups( ['root' => '/cloud', 'name' => 'Groups#getGroups', 'url' => '/groups', 'verb' => 'GET'],
\OC::$server->getGroupManager(), ['root' => '/cloud', 'name' => 'Groups#getGroup', 'url' => '/groups/{groupId}', 'verb' => 'GET'],
\OC::$server->getUserSession(), ['root' => '/cloud', 'name' => 'Groups#addGroup', 'url' => '/groups', 'verb' => 'POST'],
\OC::$server->getRequest() ['root' => '/cloud', 'name' => 'Groups#deleteGroup', 'url' => '/groups/{groupId}', 'verb' => 'DELETE'],
); ['root' => '/cloud', 'name' => 'Groups#getSubAdminsOfGroup', 'url' => '/groups/{groupId}/subadmins', 'verb' => 'GET'],
API::register('get', '/cloud/groups', [$groups, 'getGroups'], 'provisioning_api', API::SUBADMIN_AUTH);
API::register('post', '/cloud/groups', [$groups, 'addGroup'], 'provisioning_api', API::SUBADMIN_AUTH);
API::register('get', '/cloud/groups/{groupid}', [$groups, 'getGroup'], 'provisioning_api', API::SUBADMIN_AUTH);
API::register('delete', '/cloud/groups/{groupid}', [$groups, 'deleteGroup'], 'provisioning_api', API::ADMIN_AUTH);
API::register('get', '/cloud/groups/{groupid}/subadmins', [$groups, 'getSubAdminsOfGroup'], 'provisioning_api', API::ADMIN_AUTH);
// Apps //Users
$apps = new Apps( ['root' => '/cloud', 'name' => 'Users#getUsers', 'url' => '/users', 'verb' => 'GET'],
\OC::$server->getAppManager(), ['root' => '/cloud', 'name' => 'Users#addUser', 'url' => '/users', 'verb' => 'POST'],
\OC::$server->getOcsClient() ['root' => '/cloud', 'name' => 'Users#getUser', 'url' => '/users/{userId}', 'verb' => 'GET'],
); ['root' => '/cloud', 'name' => 'Users#editUser', 'url' => '/users/{userId}', 'verb' => 'PUT'],
API::register('get', '/cloud/apps', [$apps, 'getApps'], 'provisioning_api', API::ADMIN_AUTH); ['root' => '/cloud', 'name' => 'Users#deleteUser', 'url' => '/users/{userId}', 'verb' => 'DELETE'],
API::register('get', '/cloud/apps/{appid}', [$apps, 'getAppInfo'], 'provisioning_api', API::ADMIN_AUTH); ['root' => '/cloud', 'name' => 'Users#enableUser', 'url' => '/users/{userId}/enable', 'verb' => 'PUT'],
API::register('post', '/cloud/apps/{appid}', [$apps, 'enable'], 'provisioning_api', API::ADMIN_AUTH); ['root' => '/cloud', 'name' => 'Users#disableUser', 'url' => '/users/{userId}/disable', 'verb' => 'PUT'],
API::register('delete', '/cloud/apps/{appid}', [$apps, 'disable'], 'provisioning_api', API::ADMIN_AUTH); ['root' => '/cloud', 'name' => 'Users#getUsersGroups', 'url' => '/users/{userId}/groups', 'verb' => 'GET'],
['root' => '/cloud', 'name' => 'Users#addToGroup', 'url' => '/users/{userId}/groups', 'verb' => 'POST'],
['root' => '/cloud', 'name' => 'Users#removeFromGroup', 'url' => '/users/{userId}/groups', 'verb' => 'DELETE'],
['root' => '/cloud', 'name' => 'Users#getUserSubAdminGroups', 'url' => '/users/{userId}/subadmins', 'verb' => 'GET'],
['root' => '/cloud', 'name' => 'Users#addSubAdmin', 'url' => '/users/{userId}/subadmins', 'verb' => 'POST'],
['root' => '/cloud', 'name' => 'Users#removeSubAdmin', 'url' => '/users/{userId}/subadmins', 'verb' => 'DELETE'],
],
]);

View file

@ -0,0 +1,28 @@
<?php
namespace OCA\Provisioning_API\AppInfo;
use OC\AppFramework\Utility\SimpleContainer;
use OCA\Provisioning_API\Middleware\ProvisioningApiMiddleware;
use OCP\AppFramework\App;
class Application extends App {
public function __construct(array $urlParams = array()) {
parent::__construct('provisioning_api', $urlParams);
$container = $this->getContainer();
$server = $container->getServer();
$container->registerService('ProvisioningApiMiddleware', function(SimpleContainer $c) use ($server) {
$user = $server->getUserManager()->get($c['UserId']);
$isAdmin = $user !== null ? $server->getGroupManager()->isAdmin($user->getUID()) : false;
$isSubAdmin = $user !== null ? $server->getGroupManager()->getSubAdmin()->isSubAdmin($user) : false;
return new ProvisioningApiMiddleware(
$c['ControllerMethodReflector'],
$isAdmin,
$isSubAdmin
);
});
$container->registerMiddleWare('ProvisioningApiMiddleware');
}
}

View file

@ -23,89 +23,101 @@
* *
*/ */
namespace OCA\Provisioning_API; namespace OCA\Provisioning_API\Controller;
use OC\OCSClient; use OC\OCSClient;
use \OC_App; use \OC_App;
use OCP\App\IAppManager;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCS\OCSException;
use OCP\AppFramework\OCS\OCSNotFoundException;
use OCP\AppFramework\OCSController;
use OCP\IRequest;
class Apps { class AppsController extends OCSController {
/** @var \OCP\App\IAppManager */ /** @var \OCP\App\IAppManager */
private $appManager; private $appManager;
/** @var OCSClient */ /** @var OCSClient */
private $ocsClient; private $ocsClient;
/** /**
* @param \OCP\App\IAppManager $appManager * @param string $appName
* @param IRequest $request
* @param IAppManager $appManager
* @param OCSClient $ocsClient
*/ */
public function __construct(\OCP\App\IAppManager $appManager, public function __construct(
OCSClient $ocsClient) { $appName,
IRequest $request,
IAppManager $appManager,
OCSClient $ocsClient
) {
parent::__construct($appName, $request);
$this->appManager = $appManager; $this->appManager = $appManager;
$this->ocsClient = $ocsClient; $this->ocsClient = $ocsClient;
} }
/** /**
* @param array $parameters * @param string $filter
* @return \OC\OCS\Result * @return DataResponse
* @throws OCSException
*/ */
public function getApps($parameters) { public function getApps($filter = null) {
$apps = OC_App::listAllApps(false, true, $this->ocsClient); $apps = OC_App::listAllApps(false, true, $this->ocsClient);
$list = []; $list = [];
foreach($apps as $app) { foreach($apps as $app) {
$list[] = $app['id']; $list[] = $app['id'];
} }
$filter = isset($_GET['filter']) ? $_GET['filter'] : false;
if($filter){ if($filter){
switch($filter){ switch($filter){
case 'enabled': case 'enabled':
return new \OC\OCS\Result(array('apps' => \OC_App::getEnabledApps())); return new DataResponse(['apps' => \OC_App::getEnabledApps()]);
break; break;
case 'disabled': case 'disabled':
$enabled = OC_App::getEnabledApps(); $enabled = OC_App::getEnabledApps();
return new \OC\OCS\Result(array('apps' => array_diff($list, $enabled))); return new DataResponse(['apps' => array_diff($list, $enabled)]);
break; break;
default: default:
// Invalid filter variable // Invalid filter variable
return new \OC\OCS\Result(null, 101); throw new OCSException('', 101);
break;
} }
} else { } else {
return new \OC\OCS\Result(array('apps' => $list)); return new DataResponse(['apps' => $list]);
} }
} }
/** /**
* @param array $parameters * @param string $app
* @return \OC\OCS\Result * @return DataResponse
* @throws OCSNotFoundException
*/ */
public function getAppInfo($parameters) { public function getAppInfo($app) {
$app = $parameters['appid'];
$info = \OCP\App::getAppInfo($app); $info = \OCP\App::getAppInfo($app);
if(!is_null($info)) { if(!is_null($info)) {
return new \OC\OCS\Result(OC_App::getAppInfo($app)); return new DataResponse(OC_App::getAppInfo($app));
} else { } else {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_NOT_FOUND, 'The request app was not found'); throw new OCSException('The request app was not found', \OCP\API::RESPOND_NOT_FOUND);
} }
} }
/** /**
* @param array $parameters * @param string $app
* @return \OC\OCS\Result * @return DataResponse
*/ */
public function enable($parameters) { public function enable($app) {
$app = $parameters['appid'];
$this->appManager->enableApp($app); $this->appManager->enableApp($app);
return new \OC\OCS\Result(null, 100); return new DataResponse();
} }
/** /**
* @param array $parameters * @param string $app
* @return \OC\OCS\Result * @return DataResponse
*/ */
public function disable($parameters) { public function disable($app) {
$app = $parameters['appid'];
$this->appManager->disableApp($app); $this->appManager->disableApp($app);
return new \OC\OCS\Result(null, 100); return new DataResponse();
} }
} }

View file

@ -23,46 +23,54 @@
* *
*/ */
namespace OCA\Provisioning_API; namespace OCA\Provisioning_API\Controller;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCS\OCSException;
use OCP\AppFramework\OCSController;
use OCP\IGroup; use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IRequest;
use OCP\IUserSession;
use OCP\IUser; use OCP\IUser;
class Groups{
/** @var \OCP\IGroupManager */ class GroupsController extends OCSController {
/** @var IGroupManager */
private $groupManager; private $groupManager;
/** @var \OCP\IUserSession */ /** @var IUserSession */
private $userSession; private $userSession;
/** @var \OCP\IRequest */
private $request;
/** /**
* @param \OCP\IGroupManager $groupManager * @param string $appName
* @param \OCP\IUserSession $userSession * @param IRequest $request
* @param \OCP\IRequest $request * @param IGroupManager $groupManager
* @param IUserSession $userSession
*/ */
public function __construct(\OCP\IGroupManager $groupManager, public function __construct(
\OCP\IUserSession $userSession, $appName,
\OCP\IRequest $request) { IRequest $request,
IGroupManager $groupManager,
IUserSession $userSession) {
parent::__construct($appName, $request);
$this->groupManager = $groupManager; $this->groupManager = $groupManager;
$this->userSession = $userSession; $this->userSession = $userSession;
$this->request = $request;
} }
/** /**
* returns a list of groups * returns a list of groups
* *
* @param array $parameters * @NoAdminRequired
* @return \OC\OCS\Result *
* @param string $search
* @param int $limit
* @param int $offset
* @return DataResponse
*/ */
public function getGroups($parameters) { public function getGroups($search = '', $limit = null, $offset = null) {
$search = $this->request->getParam('search', '');
$limit = $this->request->getParam('limit');
$offset = $this->request->getParam('offset');
if ($limit !== null) { if ($limit !== null) {
$limit = (int)$limit; $limit = (int)$limit;
} }
@ -76,27 +84,24 @@ class Groups{
return $group->getGID(); return $group->getGID();
}, $groups); }, $groups);
return new \OC\OCS\Result(['groups' => $groups]); return new DataResponse(['groups' => $groups]);
} }
/** /**
* returns an array of users in the group specified * returns an array of users in the group specified
* *
* @param array $parameters * @NoAdminRequired
* @return \OC\OCS\Result *
* @param string $groupId
* @return DataResponse
* @throws OCSException
*/ */
public function getGroup($parameters) { public function getGroup($groupId) {
// Check if user is logged in
$user = $this->userSession->getUser(); $user = $this->userSession->getUser();
if ($user === null) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED);
}
$groupId = $parameters['groupid'];
// Check the group exists // Check the group exists
if(!$this->groupManager->groupExists($groupId)) { if(!$this->groupManager->groupExists($groupId)) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_NOT_FOUND, 'The requested group could not be found'); throw new OCSException('The requested group could not be found', \OCP\API::RESPOND_NOT_FOUND);
} }
$isSubadminOfGroup = false; $isSubadminOfGroup = false;
@ -114,59 +119,62 @@ class Groups{
return $user->getUID(); return $user->getUID();
}, $users); }, $users);
$users = array_values($users); $users = array_values($users);
return new \OC\OCS\Result(['users' => $users]); return new DataResponse(['users' => $users]);
} else { } else {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED, 'User does not have access to specified group'); throw new OCSException('User does not have access to specified group', \OCP\API::RESPOND_UNAUTHORISED);
} }
} }
/** /**
* creates a new group * creates a new group
* *
* @param array $parameters * @NoAdminRequired
* @return \OC\OCS\Result *
* @param string $groupid
* @return DataResponse
* @throws OCSException
*/ */
public function addGroup($parameters) { public function addGroup($groupid) {
// Validate name // Validate name
$groupId = $this->request->getParam('groupid', ''); if(empty($groupid)){
if(empty($groupId)){
\OCP\Util::writeLog('provisioning_api', 'Group name not supplied', \OCP\Util::ERROR); \OCP\Util::writeLog('provisioning_api', 'Group name not supplied', \OCP\Util::ERROR);
return new \OC\OCS\Result(null, 101, 'Invalid group name'); throw new OCSException('Invalid group name', 101);
} }
// Check if it exists // Check if it exists
if($this->groupManager->groupExists($groupId)){ if($this->groupManager->groupExists($groupid)){
return new \OC\OCS\Result(null, 102); throw new OCSException('', 102);
} }
$this->groupManager->createGroup($groupId); $this->groupManager->createGroup($groupid);
return new \OC\OCS\Result(null, 100); return new DataResponse();
} }
/** /**
* @param array $parameters * @param string $groupId
* @return \OC\OCS\Result * @return DataResponse
* @throws OCSException
*/ */
public function deleteGroup($parameters) { public function deleteGroup($groupId) {
// Check it exists // Check it exists
if(!$this->groupManager->groupExists($parameters['groupid'])){ if(!$this->groupManager->groupExists($groupId)){
return new \OC\OCS\Result(null, 101); throw new OCSException('', 101);
} else if($parameters['groupid'] === 'admin' || !$this->groupManager->get($parameters['groupid'])->delete()){ } else if($groupId === 'admin' || !$this->groupManager->get($groupId)->delete()){
// Cannot delete admin group // Cannot delete admin group
return new \OC\OCS\Result(null, 102); throw new OCSException('', 102);
} else {
return new \OC\OCS\Result(null, 100);
} }
return new DataResponse(null, 100);
} }
/** /**
* @param array $parameters * @param string $groupId
* @return \OC\OCS\Result * @return DataResponse
* @throws OCSException
*/ */
public function getSubAdminsOfGroup($parameters) { public function getSubAdminsOfGroup($groupId) {
$group = $parameters['groupid'];
// Check group exists // Check group exists
$targetGroup = $this->groupManager->get($group); $targetGroup = $this->groupManager->get($groupId);
if($targetGroup === null) { if($targetGroup === null) {
return new \OC\OCS\Result(null, 101, 'Group does not exist'); throw new OCSException('Group does not exist', 101);
} }
$subadmins = $this->groupManager->getSubAdmin()->getGroupsSubAdmins($targetGroup); $subadmins = $this->groupManager->getSubAdmin()->getGroupsSubAdmins($targetGroup);
@ -176,7 +184,7 @@ class Groups{
$uids[] = $user->getUID(); $uids[] = $user->getUID();
} }
return new \OC\OCS\Result($uids); return new DataResponse($uids);
} }
} }

View file

@ -27,17 +27,23 @@
* *
*/ */
namespace OCA\Provisioning_API; namespace OCA\Provisioning_API\Controller;
use \OC_Helper; use \OC_Helper;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCS\OCSException;
use OCP\AppFramework\OCS\OCSForbiddenException;
use OCP\AppFramework\OCS\OCSNotFoundException;
use OCP\AppFramework\OCSController;
use OCP\Files\NotFoundException; use OCP\Files\NotFoundException;
use OCP\IConfig; use OCP\IConfig;
use OCP\IGroupManager; use OCP\IGroupManager;
use OCP\ILogger; use OCP\ILogger;
use OCP\IRequest;
use OCP\IUserManager; use OCP\IUserManager;
use OCP\IUserSession; use OCP\IUserSession;
class Users { class UsersController extends OCSController {
/** @var IUserManager */ /** @var IUserManager */
private $userManager; private $userManager;
@ -51,17 +57,23 @@ class Users {
private $logger; private $logger;
/** /**
* @param string $appName
* @param IRequest $request
* @param IUserManager $userManager * @param IUserManager $userManager
* @param IConfig $config * @param IConfig $config
* @param IGroupManager $groupManager * @param IGroupManager $groupManager
* @param IUserSession $userSession * @param IUserSession $userSession
* @param ILogger $logger * @param ILogger $logger
*/ */
public function __construct(IUserManager $userManager, public function __construct($appName,
IRequest $request,
IUserManager $userManager,
IConfig $config, IConfig $config,
IGroupManager $groupManager, IGroupManager $groupManager,
IUserSession $userSession, IUserSession $userSession,
ILogger $logger) { ILogger $logger) {
parent::__construct($appName, $request);
$this->userManager = $userManager; $this->userManager = $userManager;
$this->config = $config; $this->config = $config;
$this->groupManager = $groupManager; $this->groupManager = $groupManager;
@ -70,20 +82,17 @@ class Users {
} }
/** /**
* @NoAdminRequired
*
* returns a list of users * returns a list of users
* *
* @return \OC\OCS\Result * @param string $search
* @param int $limit
* @param int $offset
* @return DataResponse
*/ */
public function getUsers() { public function getUsers($search = '', $limit = null, $offset = null) {
$search = !empty($_GET['search']) ? $_GET['search'] : '';
$limit = !empty($_GET['limit']) ? $_GET['limit'] : null;
$offset = !empty($_GET['offset']) ? $_GET['offset'] : null;
// Check if user is logged in
$user = $this->userSession->getUser(); $user = $this->userSession->getUser();
if ($user === null) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED);
}
// Admin? Or SubAdmin? // Admin? Or SubAdmin?
$uid = $user->getUID(); $uid = $user->getUID();
@ -106,89 +115,85 @@ class Users {
} }
$users = array_slice($users, $offset, $limit); $users = array_slice($users, $offset, $limit);
} else {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED);
} }
$users = array_keys($users); $users = array_keys($users);
return new \OC\OCS\Result([ return new DataResponse([
'users' => $users 'users' => $users
]); ]);
} }
/** /**
* @return \OC\OCS\Result * @NoAdminRequired
*
* @param string $userid
* @param string $password
* @param array $groups
* @return DataResponse
* @throws OCSException
*/ */
public function addUser() { public function addUser($userid, $password, $groups = null) {
$userId = isset($_POST['userid']) ? $_POST['userid'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
$groups = isset($_POST['groups']) ? $_POST['groups'] : null;
$user = $this->userSession->getUser(); $user = $this->userSession->getUser();
$isAdmin = $this->groupManager->isAdmin($user->getUID()); $isAdmin = $this->groupManager->isAdmin($user->getUID());
$subAdminManager = $this->groupManager->getSubAdmin(); $subAdminManager = $this->groupManager->getSubAdmin();
if (!$isAdmin && !$subAdminManager->isSubAdmin($user)) { if($this->userManager->userExists($userid)) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED);
}
if($this->userManager->userExists($userId)) {
$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']); $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
return new \OC\OCS\Result(null, 102, 'User already exists'); throw new OCSException('User already exists', 102);
} }
if(is_array($groups)) { if(is_array($groups)) {
foreach ($groups as $group) { foreach ($groups as $group) {
if(!$this->groupManager->groupExists($group)){ if(!$this->groupManager->groupExists($group)) {
return new \OC\OCS\Result(null, 104, 'group '.$group.' does not exist'); throw new OCSException('group '.$group.' does not exist', 104);
} }
if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) { if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
return new \OC\OCS\Result(null, 105, 'insufficient privileges for group '. $group); throw new OCSException('insufficient privileges for group '. $group, 105);
} }
} }
} else { } else {
if(!$isAdmin) { if(!$isAdmin) {
return new \OC\OCS\Result(null, 106, 'no group specified (required for subadmins)'); throw new OCSException('no group specified (required for subadmins)', 106);
} }
} }
try { try {
$newUser = $this->userManager->createUser($userId, $password); $newUser = $this->userManager->createUser($userid, $password);
$this->logger->info('Successful addUser call with userid: '.$userId, ['app' => 'ocs_api']); $this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
if (is_array($groups)) { if (is_array($groups)) {
foreach ($groups as $group) { foreach ($groups as $group) {
$this->groupManager->get($group)->addUser($newUser); $this->groupManager->get($group)->addUser($newUser);
$this->logger->info('Added userid '.$userId.' to group '.$group, ['app' => 'ocs_api']); $this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
} }
} }
return new \OC\OCS\Result(null, 100); return new DataResponse();
} catch (\Exception $e) { } catch (\Exception $e) {
$this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']); $this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
return new \OC\OCS\Result(null, 101, 'Bad request'); throw new OCSException('Bad request', 101);
} }
} }
/** /**
* @NoAdminRequired
* @NoSubAdminRequired
*
* gets user info * gets user info
* *
* @param array $parameters * @param string $userId
* @return \OC\OCS\Result * @return DataResponse
* @throws OCSException
*/ */
public function getUser($parameters) { public function getUser($userId) {
$userId = $parameters['userid'];
// Check if user is logged in
$currentLoggedInUser = $this->userSession->getUser(); $currentLoggedInUser = $this->userSession->getUser();
if ($currentLoggedInUser === null) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED);
}
$data = []; $data = [];
// Check if the target user exists // Check if the target user exists
$targetUserObject = $this->userManager->get($userId); $targetUserObject = $this->userManager->get($userId);
if($targetUserObject === null) { if($targetUserObject === null) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_NOT_FOUND, 'The requested user could not be found'); throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
} }
// Admin? Or SubAdmin? // Admin? Or SubAdmin?
@ -198,7 +203,7 @@ class Users {
} else { } else {
// Check they are looking up themselves // Check they are looking up themselves
if($currentLoggedInUser->getUID() !== $userId) { if($currentLoggedInUser->getUID() !== $userId) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED); throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
} }
} }
@ -207,32 +212,32 @@ class Users {
$data['email'] = $targetUserObject->getEMailAddress(); $data['email'] = $targetUserObject->getEMailAddress();
$data['displayname'] = $targetUserObject->getDisplayName(); $data['displayname'] = $targetUserObject->getDisplayName();
return new \OC\OCS\Result($data); return new DataResponse($data);
} }
/** /**
* @NoAdminRequired
* @NoSubAdminRequired
*
* edit users * edit users
* *
* @param array $parameters * @param string $userId
* @return \OC\OCS\Result * @param string $key
* @param string $value
* @return DataResponse
* @throws OCSException
* @throws OCSForbiddenException
*/ */
public function editUser($parameters) { public function editUser($userId, $key, $value) {
/** @var string $targetUserId */
$targetUserId = $parameters['userid'];
// Check if user is logged in
$currentLoggedInUser = $this->userSession->getUser(); $currentLoggedInUser = $this->userSession->getUser();
if ($currentLoggedInUser === null) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED);
}
$targetUser = $this->userManager->get($targetUserId); $targetUser = $this->userManager->get($userId);
if($targetUser === null) { if($targetUser === null) {
return new \OC\OCS\Result(null, 997); throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
} }
$permittedFields = []; $permittedFields = [];
if($targetUserId === $currentLoggedInUser->getUID()) { if($userId === $currentLoggedInUser->getUID()) {
// Editing self (display, email) // Editing self (display, email)
$permittedFields[] = 'display'; $permittedFields[] = 'display';
$permittedFields[] = 'email'; $permittedFields[] = 'email';
@ -253,20 +258,20 @@ class Users {
$permittedFields[] = 'email'; $permittedFields[] = 'email';
} else { } else {
// No rights // No rights
return new \OC\OCS\Result(null, 997); throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
} }
} }
// Check if permitted to edit this field // Check if permitted to edit this field
if(!in_array($parameters['_put']['key'], $permittedFields)) { if(!in_array($key, $permittedFields)) {
return new \OC\OCS\Result(null, 997); throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
} }
// Process the edit // Process the edit
switch($parameters['_put']['key']) { switch($key) {
case 'display': case 'display':
$targetUser->setDisplayName($parameters['_put']['value']); $targetUser->setDisplayName($value);
break; break;
case 'quota': case 'quota':
$quota = $parameters['_put']['value']; $quota = $value;
if($quota !== 'none' and $quota !== 'default') { if($quota !== 'none' and $quota !== 'default') {
if (is_numeric($quota)) { if (is_numeric($quota)) {
$quota = floatval($quota); $quota = floatval($quota);
@ -274,7 +279,7 @@ class Users {
$quota = \OCP\Util::computerFileSize($quota); $quota = \OCP\Util::computerFileSize($quota);
} }
if ($quota === false) { if ($quota === false) {
return new \OC\OCS\Result(null, 103, "Invalid quota value {$parameters['_put']['value']}"); throw new OCSException('Invalid quota value '.$value, 103);
} }
if($quota === 0) { if($quota === 0) {
$quota = 'default'; $quota = 'default';
@ -287,115 +292,118 @@ class Users {
$targetUser->setQuota($quota); $targetUser->setQuota($quota);
break; break;
case 'password': case 'password':
$targetUser->setPassword($parameters['_put']['value']); $targetUser->setPassword($value);
break; break;
case 'email': case 'email':
if(filter_var($parameters['_put']['value'], FILTER_VALIDATE_EMAIL)) { if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
$targetUser->setEMailAddress($parameters['_put']['value']); $targetUser->setEMailAddress($value);
} else { } else {
return new \OC\OCS\Result(null, 102); throw new OCSException('', 102);
} }
break; break;
default: default:
return new \OC\OCS\Result(null, 103); throw new OCSException('', 103);
} }
return new \OC\OCS\Result(null, 100); return new DataResponse();
} }
/** /**
* @param array $parameters * @NoAdminRequired
* @return \OC\OCS\Result *
* @param string $userId
* @return DataResponse
* @throws OCSException
* @throws OCSForbiddenException
*/ */
public function deleteUser($parameters) { public function deleteUser($userId) {
// Check if user is logged in
$currentLoggedInUser = $this->userSession->getUser(); $currentLoggedInUser = $this->userSession->getUser();
if ($currentLoggedInUser === null) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED);
}
$targetUser = $this->userManager->get($parameters['userid']); $targetUser = $this->userManager->get($userId);
if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) { if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
return new \OC\OCS\Result(null, 101); throw new OCSException('', 101);
} }
// If not permitted // If not permitted
$subAdminManager = $this->groupManager->getSubAdmin(); $subAdminManager = $this->groupManager->getSubAdmin();
if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
return new \OC\OCS\Result(null, 997); throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
} }
// Go ahead with the delete // Go ahead with the delete
if($targetUser->delete()) { if($targetUser->delete()) {
return new \OC\OCS\Result(null, 100); return new DataResponse();
} else { } else {
return new \OC\OCS\Result(null, 101); throw new OCSException('', 101);
} }
} }
/** /**
* @param array $parameters * @NoAdminRequired
* @return \OC\OCS\Result *
* @param string $userId
* @return DataResponse
*/ */
public function disableUser($parameters) { public function disableUser($userId) {
return $this->setEnabled($parameters, false); return $this->setEnabled($userId, false);
} }
/** /**
* @param array $parameters * @NoAdminRequired
* @return \OC\OCS\Result *
* @param string $userId
* @return DataResponse
*/ */
public function enableUser($parameters) { public function enableUser($userId) {
return $this->setEnabled($parameters, true); return $this->setEnabled($userId, true);
} }
/** /**
* @param array $parameters * @param string $userId
* @param bool $value * @param bool $value
* @return \OC\OCS\Result * @return DataResponse
* @throws OCSException
* @throws OCSForbiddenException
*/ */
private function setEnabled($parameters, $value) { private function setEnabled($userId, $value) {
// Check if user is logged in
$currentLoggedInUser = $this->userSession->getUser(); $currentLoggedInUser = $this->userSession->getUser();
if ($currentLoggedInUser === null) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED);
}
$targetUser = $this->userManager->get($parameters['userid']); $targetUser = $this->userManager->get($userId);
if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) { if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
return new \OC\OCS\Result(null, 101); throw new OCSException('', 101);
} }
// If not permitted // If not permitted
$subAdminManager = $this->groupManager->getSubAdmin(); $subAdminManager = $this->groupManager->getSubAdmin();
if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
return new \OC\OCS\Result(null, 997); throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
} }
// enable/disable the user now // enable/disable the user now
$targetUser->setEnabled($value); $targetUser->setEnabled($value);
return new \OC\OCS\Result(null, 100); return new DataResponse();
} }
/** /**
* @param array $parameters * @NoAdminRequired
* @return \OC\OCS\Result * @NoSubAdminRequired
*
* @param string $userId
* @return DataResponse
* @throws OCSForbiddenException
* @throws OCSNotFoundException
*/ */
public function getUsersGroups($parameters) { public function getUsersGroups($userId) {
// Check if user is logged in
$loggedInUser = $this->userSession->getUser(); $loggedInUser = $this->userSession->getUser();
if ($loggedInUser === null) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED);
}
$targetUser = $this->userManager->get($parameters['userid']); $targetUser = $this->userManager->get($userId);
if($targetUser === null) { if($targetUser === null) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_NOT_FOUND); throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
} }
if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) { if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
// Self lookup or admin lookup // Self lookup or admin lookup
return new \OC\OCS\Result([ return new DataResponse([
'groups' => $this->groupManager->getUserGroupIds($targetUser) 'groups' => $this->groupManager->getUserGroupIds($targetUser)
]); ]);
} else { } else {
@ -412,87 +420,75 @@ class Users {
$getSubAdminsGroups, $getSubAdminsGroups,
$this->groupManager->getUserGroupIds($targetUser) $this->groupManager->getUserGroupIds($targetUser)
); );
return new \OC\OCS\Result(array('groups' => $groups)); return new DataResponse(['groups' => $groups]);
} else { } else {
// Not permitted // Not permitted
return new \OC\OCS\Result(null, 997); throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
} }
} }
} }
/** /**
* @param array $parameters * @param string $userId
* @return \OC\OCS\Result * @param string $groupid
* @return DataResponse
* @throws OCSException
*/ */
public function addToGroup($parameters) { public function addToGroup($userId, $groupid = '') {
// Check if user is logged in if($groupid === '') {
$user = $this->userSession->getUser(); throw new OCSException('', 101);
if ($user === null) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED);
} }
// Check they're an admin $group = $this->groupManager->get($groupid);
if(!$this->groupManager->isAdmin($user->getUID())) { $targetUser = $this->userManager->get($userId);
// This user doesn't have rights to add a user to this group
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED);
}
$groupId = !empty($_POST['groupid']) ? $_POST['groupid'] : null;
if($groupId === null) {
return new \OC\OCS\Result(null, 101);
}
$group = $this->groupManager->get($groupId);
$targetUser = $this->userManager->get($parameters['userid']);
if($group === null) { if($group === null) {
return new \OC\OCS\Result(null, 102); throw new OCSException('', 102);
} }
if($targetUser === null) { if($targetUser === null) {
return new \OC\OCS\Result(null, 103); throw new OCSException('', 103);
} }
// Add user to group // Add user to group
$group->addUser($targetUser); $group->addUser($targetUser);
return new \OC\OCS\Result(null, 100); return new DataResponse();
} }
/** /**
* @param array $parameters * @NoAdminRequired
* @return \OC\OCS\Result *
* @param string userId
* @param string $groupid
* @return DataResponse
* @throws OCSException
*/ */
public function removeFromGroup($parameters) { public function removeFromGroup($userId, $groupid) {
// Check if user is logged in
$loggedInUser = $this->userSession->getUser(); $loggedInUser = $this->userSession->getUser();
if ($loggedInUser === null) {
return new \OC\OCS\Result(null, \OCP\API::RESPOND_UNAUTHORISED); if($groupid === null) {
throw new OCSException('', 101);
} }
$group = !empty($parameters['_delete']['groupid']) ? $parameters['_delete']['groupid'] : null; $group = $this->groupManager->get($groupid);
if($group === null) { if($group === null) {
return new \OC\OCS\Result(null, 101); throw new OCSException('', 102);
} }
$group = $this->groupManager->get($group); $targetUser = $this->userManager->get($userId);
if($group === null) {
return new \OC\OCS\Result(null, 102);
}
$targetUser = $this->userManager->get($parameters['userid']);
if($targetUser === null) { if($targetUser === null) {
return new \OC\OCS\Result(null, 103); throw new OCSException('', 103);
} }
// If they're not an admin, check they are a subadmin of the group in question // If they're not an admin, check they are a subadmin of the group in question
$subAdminManager = $this->groupManager->getSubAdmin(); $subAdminManager = $this->groupManager->getSubAdmin();
if(!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminofGroup($loggedInUser, $group)) { if(!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminofGroup($loggedInUser, $group)) {
return new \OC\OCS\Result(null, 104); throw new OCSException('', 104);
} }
// Check they aren't removing themselves from 'admin' or their 'subadmin; group // Check they aren't removing themselves from 'admin' or their 'subadmin; group
if($parameters['userid'] === $loggedInUser->getUID()) { if($userId === $loggedInUser->getUID()) {
if($this->groupManager->isAdmin($loggedInUser->getUID())) { if($this->groupManager->isAdmin($loggedInUser->getUID())) {
if($group->getGID() === 'admin') { if($group->getGID() === 'admin') {
return new \OC\OCS\Result(null, 105, 'Cannot remove yourself from the admin group'); throw new OCSException('Cannot remove yourself from the admin group', 105);
} }
} else { } else {
// Not an admin, check they are not removing themself from their subadmin group // Not an admin, check they are not removing themself from their subadmin group
@ -502,96 +498,101 @@ class Users {
} }
if(in_array($group->getGID(), $subAdminGroups, true)) { if(in_array($group->getGID(), $subAdminGroups, true)) {
return new \OC\OCS\Result(null, 105, 'Cannot remove yourself from this group as you are a SubAdmin'); throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
} }
} }
} }
// Remove user from group // Remove user from group
$group->removeUser($targetUser); $group->removeUser($targetUser);
return new \OC\OCS\Result(null, 100); return new DataResponse();
} }
/** /**
* Creates a subadmin * Creates a subadmin
* *
* @param array $parameters * @param string $userId
* @return \OC\OCS\Result * @param string $groupid
* @return DataResponse
* @throws OCSException
*/ */
public function addSubAdmin($parameters) { public function addSubAdmin($userId, $groupid) {
$group = $this->groupManager->get($_POST['groupid']); $group = $this->groupManager->get($groupid);
$user = $this->userManager->get($parameters['userid']); $user = $this->userManager->get($userId);
// Check if the user exists // Check if the user exists
if($user === null) { if($user === null) {
return new \OC\OCS\Result(null, 101, 'User does not exist'); throw new OCSException('User does not exist', 101);
} }
// Check if group exists // Check if group exists
if($group === null) { if($group === null) {
return new \OC\OCS\Result(null, 102, 'Group:'.$_POST['groupid'].' does not exist'); throw new OCSException('Group:'.$groupid.' does not exist', 102);
} }
// Check if trying to make subadmin of admin group // Check if trying to make subadmin of admin group
if(strtolower($_POST['groupid']) === 'admin') { if(strtolower($groupid) === 'admin') {
return new \OC\OCS\Result(null, 103, 'Cannot create subadmins for admin group'); throw new OCSException('Cannot create subadmins for admin group', 103);
} }
$subAdminManager = $this->groupManager->getSubAdmin(); $subAdminManager = $this->groupManager->getSubAdmin();
// We cannot be subadmin twice // We cannot be subadmin twice
if ($subAdminManager->isSubAdminofGroup($user, $group)) { if ($subAdminManager->isSubAdminofGroup($user, $group)) {
return new \OC\OCS\Result(null, 100); return new DataResponse();
} }
// Go // Go
if($subAdminManager->createSubAdmin($user, $group)) { if($subAdminManager->createSubAdmin($user, $group)) {
return new \OC\OCS\Result(null, 100); return new DataResponse();
} else { } else {
return new \OC\OCS\Result(null, 103, 'Unknown error occurred'); throw new OCSException('Unknown error occurred', 103);
} }
} }
/** /**
* Removes a subadmin from a group * Removes a subadmin from a group
* *
* @param array $parameters * @param string $userId
* @return \OC\OCS\Result * @param string $groupid
* @return DataResponse
* @throws OCSException
*/ */
public function removeSubAdmin($parameters) { public function removeSubAdmin($userId, $groupid) {
$group = $this->groupManager->get($parameters['_delete']['groupid']); $group = $this->groupManager->get($groupid);
$user = $this->userManager->get($parameters['userid']); $user = $this->userManager->get($userId);
$subAdminManager = $this->groupManager->getSubAdmin(); $subAdminManager = $this->groupManager->getSubAdmin();
// Check if the user exists // Check if the user exists
if($user === null) { if($user === null) {
return new \OC\OCS\Result(null, 101, 'User does not exist'); throw new OCSException('User does not exist', 101);
} }
// Check if the group exists // Check if the group exists
if($group === null) { if($group === null) {
return new \OC\OCS\Result(null, 101, 'Group does not exist'); throw new OCSException('Group does not exist', 101);
} }
// Check if they are a subadmin of this said group // Check if they are a subadmin of this said group
if(!$subAdminManager->isSubAdminofGroup($user, $group)) { if(!$subAdminManager->isSubAdminofGroup($user, $group)) {
return new \OC\OCS\Result(null, 102, 'User is not a subadmin of this group'); throw new OCSException('User is not a subadmin of this group', 102);
} }
// Go // Go
if($subAdminManager->deleteSubAdmin($user, $group)) { if($subAdminManager->deleteSubAdmin($user, $group)) {
return new \OC\OCS\Result(null, 100); return new DataResponse();
} else { } else {
return new \OC\OCS\Result(null, 103, 'Unknown error occurred'); throw new OCSException('Unknown error occurred', 103);
} }
} }
/** /**
* Get the groups a user is a subadmin of * Get the groups a user is a subadmin of
* *
* @param array $parameters * @param string $userId
* @return \OC\OCS\Result * @return DataResponse
* @throws OCSException
*/ */
public function getUserSubAdminGroups($parameters) { public function getUserSubAdminGroups($userId) {
$user = $this->userManager->get($parameters['userid']); $user = $this->userManager->get($userId);
// Check if the user exists // Check if the user exists
if($user === null) { if($user === null) {
return new \OC\OCS\Result(null, 101, 'User does not exist'); throw new OCSException('User does not exist', 101);
} }
// Get the subadmin groups // Get the subadmin groups
@ -601,9 +602,9 @@ class Users {
} }
if(!$groups) { if(!$groups) {
return new \OC\OCS\Result(null, 102, 'Unknown error occurred'); throw new OCSException('Unknown error occurred', 102);
} else { } else {
return new \OC\OCS\Result($groups); return new DataResponse($groups);
} }
} }

View file

@ -0,0 +1,11 @@
<?php
namespace OCA\Provisioning_API\Middleware\Exceptions;
use OCP\AppFramework\Http;
class NotSubAdminException extends \Exception {
public function __construct() {
parent::__construct('Logged in user must be at least a sub admin', Http::STATUS_FORBIDDEN);
}
}

View file

@ -0,0 +1,64 @@
<?php
namespace OCA\Provisioning_API\Middleware;
use OCA\Provisioning_API\Middleware\Exceptions\NotSubAdminException;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Middleware;
use OCP\AppFramework\OCS\OCSException;
use OCP\AppFramework\Utility\IControllerMethodReflector;
class ProvisioningApiMiddleware extends Middleware {
/** @var IControllerMethodReflector */
private $reflector;
/** @var bool */
private $isAdmin;
/** @var bool */
private $isSubAdmin;
/**
* ProvisioningApiMiddleware constructor.
*
* @param IControllerMethodReflector $reflector
* @param bool $isAdmin
* @param bool $isSubAdmin
*/
public function __construct(
IControllerMethodReflector $reflector,
$isAdmin,
$isSubAdmin) {
$this->reflector = $reflector;
$this->isAdmin = $isAdmin;
$this->isSubAdmin = $isSubAdmin;
}
/**
* @param \OCP\AppFramework\Controller $controller
* @param string $methodName
*
* @throws NotSubAdminException
*/
public function beforeController($controller, $methodName) {
if (!$this->isAdmin && !$this->reflector->hasAnnotation('NoSubAdminRequired') && !$this->isSubAdmin) {
throw new NotSubAdminException();
}
}
/**
* @param \OCP\AppFramework\Controller $controller
* @param string $methodName
* @param \Exception $exception
* @throws \Exception
* @return Response
*/
public function afterException($controller, $methodName, \Exception $exception) {
if ($exception instanceof NotSubAdminException) {
throw new OCSException($exception->getMessage(), \OCP\API::RESPOND_UNAUTHORISED);
}
throw $exception;
}
}

View file

@ -25,11 +25,11 @@
* *
*/ */
namespace OCA\Provisioning_API\Tests; namespace OCA\Provisioning_API\Tests\Controller;
use OC\OCSClient; use OC\OCSClient;
use OCA\Provisioning_API\Apps; use OCA\Provisioning_API\Controller\AppsController;
use OCP\API; use OCP\API;
use OCP\App\IAppManager; use OCP\App\IAppManager;
use OCP\IUserSession; use OCP\IUserSession;
@ -41,10 +41,10 @@ use OCP\IUserSession;
* *
* @package OCA\Provisioning_API\Tests * @package OCA\Provisioning_API\Tests
*/ */
class AppsTest extends TestCase { class AppsControllerTest extends \OCA\Provisioning_API\Tests\TestCase {
/** @var IAppManager */ /** @var IAppManager */
private $appManager; private $appManager;
/** @var Apps */ /** @var AppsController */
private $api; private $api;
/** @var IUserSession */ /** @var IUserSession */
private $userSession; private $userSession;
@ -61,20 +61,30 @@ class AppsTest extends TestCase {
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$this->api = new Apps($this->appManager, $this->ocsClient); $request = $this->getMockBuilder('OCP\IRequest')
->disableOriginalConstructor()
->getMock();
$this->api = new AppsController(
'provisioning_api',
$request,
$this->appManager,
$this->ocsClient
);
} }
public function testGetAppInfo() { public function testGetAppInfo() {
$result = $this->api->getAppInfo(['appid' => 'provisioning_api']); $result = $this->api->getAppInfo('provisioning_api');
$this->assertInstanceOf('\OC\OCS\Result', $result); $expected = \OC_App::getAppInfo('provisioning_api');
$this->assertTrue($result->succeeded()); $this->assertEquals($expected, $result->getData());
} }
/**
* @expectedException \OCP\AppFramework\OCS\OCSException
* @expectedExceptionCode 998
*/
public function testGetAppInfoOnBadAppID() { public function testGetAppInfoOnBadAppID() {
$result = $this->api->getAppInfo(['appid' => 'not_provisioning_api']); $this->api->getAppInfo('not_provisioning_api');
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertFalse($result->succeeded());
$this->assertEquals(API::RESPOND_NOT_FOUND, $result->getStatusCode());
} }
public function testGetApps() { public function testGetApps() {
@ -86,17 +96,14 @@ class AppsTest extends TestCase {
$this->groupManager->get('admin')->addUser($user); $this->groupManager->get('admin')->addUser($user);
$this->userSession->setUser($user); $this->userSession->setUser($user);
$result = $this->api->getApps([]); $result = $this->api->getApps();
$this->assertTrue($result->succeeded());
$data = $result->getData(); $data = $result->getData();
$this->assertEquals(count(\OC_App::listAllApps(false, true, $this->ocsClient)), count($data['apps'])); $this->assertEquals(count(\OC_App::listAllApps(false, true, $this->ocsClient)), count($data['apps']));
} }
public function testGetAppsEnabled() { public function testGetAppsEnabled() {
$_GET['filter'] = 'enabled'; $result = $this->api->getApps('enabled');
$result = $this->api->getApps(['filter' => 'enabled']);
$this->assertTrue($result->succeeded());
$data = $result->getData(); $data = $result->getData();
$this->assertEquals(count(\OC_App::getEnabledApps()), count($data['apps'])); $this->assertEquals(count(\OC_App::getEnabledApps()), count($data['apps']));
} }
@ -106,9 +113,7 @@ class AppsTest extends TestCase {
->expects($this->any()) ->expects($this->any())
->method($this->anything()) ->method($this->anything())
->will($this->returnValue(null)); ->will($this->returnValue(null));
$_GET['filter'] = 'disabled'; $result = $this->api->getApps('disabled');
$result = $this->api->getApps(['filter' => 'disabled']);
$this->assertTrue($result->succeeded());
$data = $result->getData(); $data = $result->getData();
$apps = \OC_App::listAllApps(false, true, $this->ocsClient); $apps = \OC_App::listAllApps(false, true, $this->ocsClient);
$list = array(); $list = array();
@ -119,10 +124,11 @@ class AppsTest extends TestCase {
$this->assertEquals(count($disabled), count($data['apps'])); $this->assertEquals(count($disabled), count($data['apps']));
} }
/**
* @expectedException \OCP\AppFramework\OCS\OCSException
* @expectedExceptionCode 101
*/
public function testGetAppsInvalidFilter() { public function testGetAppsInvalidFilter() {
$_GET['filter'] = 'foo'; $this->api->getApps('foo');
$result = $this->api->getApps([]);
$this->assertFalse($result->succeeded());
$this->assertEquals(101, $result->getStatusCode());
} }
} }

View file

@ -24,24 +24,20 @@
* *
*/ */
namespace OCA\Provisioning_API\Tests; namespace OCA\Provisioning_API\Tests\Controller;
use OCA\Provisioning_API\Groups; use OCA\Provisioning_API\Controller\GroupsController;
use OCP\API;
use OCP\IGroupManager; use OCP\IGroupManager;
use OCP\IUserSession; use OCP\IUserSession;
use OCP\IRequest;
class GroupsTest extends \Test\TestCase { class GroupsControllerTest extends \Test\TestCase {
/** @var IGroupManager|\PHPUnit_Framework_MockObject_MockObject */ /** @var IGroupManager|\PHPUnit_Framework_MockObject_MockObject */
protected $groupManager; protected $groupManager;
/** @var IUserSession|\PHPUnit_Framework_MockObject_MockObject */ /** @var IUserSession|\PHPUnit_Framework_MockObject_MockObject */
protected $userSession; protected $userSession;
/** @var IRequest|\PHPUnit_Framework_MockObject_MockObject */
protected $request;
/** @var \OC\SubAdmin|\PHPUnit_Framework_MockObject_MockObject */ /** @var \OC\SubAdmin|\PHPUnit_Framework_MockObject_MockObject */
protected $subAdminManager; protected $subAdminManager;
/** @var Groups */ /** @var GroupsController */
protected $api; protected $api;
protected function setUp() { protected function setUp() {
@ -61,13 +57,14 @@ class GroupsTest extends \Test\TestCase {
$this->userSession = $this->getMockBuilder('OCP\IUserSession') $this->userSession = $this->getMockBuilder('OCP\IUserSession')
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$this->request = $this->getMockBuilder('OCP\IRequest') $request = $this->getMockBuilder('OCP\IRequest')
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$this->api = new Groups( $this->api = new GroupsController(
'provisioning_api',
$request,
$this->groupManager, $this->groupManager,
$this->userSession, $this->userSession
$this->request
); );
} }
@ -148,15 +145,6 @@ class GroupsTest extends \Test\TestCase {
* @param int|null $offset * @param int|null $offset
*/ */
public function testGetGroups($search, $limit, $offset) { public function testGetGroups($search, $limit, $offset) {
$this->request
->expects($this->exactly(3))
->method('getParam')
->will($this->returnValueMap([
['search', '', $search],
['limit', null, $limit],
['offset', null, $offset],
]));
$groups = [$this->createGroup('group1'), $this->createGroup('group2')]; $groups = [$this->createGroup('group1'), $this->createGroup('group2')];
$search = $search === null ? '' : $search; $search = $search === null ? '' : $search;
@ -167,19 +155,8 @@ class GroupsTest extends \Test\TestCase {
->with($search, $limit, $offset) ->with($search, $limit, $offset)
->willReturn($groups); ->willReturn($groups);
$result = $this->api->getGroups([]); $result = $this->api->getGroups($search, $limit, $offset);
$this->assertInstanceOf('\OC\OCS\Result', $result); $this->assertEquals(['groups' => ['group1', 'group2']], $result->getData());
$this->assertTrue($result->succeeded());
$this->assertEquals(['group1', 'group2'], $result->getData()['groups']);
}
public function testGetGroupAsUser() {
$result = $this->api->getGroup([]);
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertFalse($result->succeeded());
$this->assertEquals(API::RESPOND_UNAUTHORISED, $result->getStatusCode());
} }
public function testGetGroupAsSubadmin() { public function testGetGroupAsSubadmin() {
@ -201,17 +178,15 @@ class GroupsTest extends \Test\TestCase {
$this->createUser('user2') $this->createUser('user2')
]); ]);
$result = $this->api->getGroup([ $result = $this->api->getGroup('group');
'groupid' => 'group',
]);
$this->assertInstanceOf('\OC\OCS\Result', $result); $this->assertEquals(['users' => ['user1', 'user2']], $result->getData());
$this->assertTrue($result->succeeded());
$this->assertEquals(1, sizeof($result->getData()), 'Asserting the result data array only has the "users" key');
$this->assertArrayHasKey('users', $result->getData());
$this->assertEquals(['user1', 'user2'], $result->getData()['users']);
} }
/**
* @expectedException \OCP\AppFramework\OCS\OCSException
* @expectedExceptionCode 997
*/
public function testGetGroupAsIrrelevantSubadmin() { public function testGetGroupAsIrrelevantSubadmin() {
$group = $this->createGroup('group'); $group = $this->createGroup('group');
$otherGroup = $this->createGroup('otherGroup'); $otherGroup = $this->createGroup('otherGroup');
@ -226,13 +201,7 @@ class GroupsTest extends \Test\TestCase {
->with('group') ->with('group')
->willReturn(true); ->willReturn(true);
$result = $this->api->getGroup([ $this->api->getGroup('group');
'groupid' => 'group',
]);
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertFalse($result->succeeded());
$this->assertEquals(API::RESPOND_UNAUTHORISED, $result->getStatusCode());
} }
public function testGetGroupAsAdmin() { public function testGetGroupAsAdmin() {
@ -254,39 +223,29 @@ class GroupsTest extends \Test\TestCase {
$this->createUser('user2') $this->createUser('user2')
]); ]);
$result = $this->api->getGroup([ $result = $this->api->getGroup('group');
'groupid' => 'group',
]);
$this->assertInstanceOf('\OC\OCS\Result', $result); $this->assertEquals(['users' => ['user1', 'user2']], $result->getData());
$this->assertTrue($result->succeeded());
$this->assertEquals(1, sizeof($result->getData()), 'Asserting the result data array only has the "users" key');
$this->assertArrayHasKey('users', $result->getData());
$this->assertEquals(['user1', 'user2'], $result->getData()['users']);
} }
/**
* @expectedException \OCP\AppFramework\OCS\OCSException
* @expectedExceptionCode 998
* @expectedExceptionMessage The requested group could not be found
*/
public function testGetGroupNonExisting() { public function testGetGroupNonExisting() {
$this->asUser(); $this->asUser();
$result = $this->api->getGroup([ $this->api->getGroup($this->getUniqueID());
'groupid' => $this->getUniqueID()
]);
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertFalse($result->succeeded());
$this->assertEquals(API::RESPOND_NOT_FOUND, $result->getStatusCode());
$this->assertEquals('The requested group could not be found', $result->getMeta()['message']);
} }
/**
* @expectedException \OCP\AppFramework\OCS\OCSException
* @expectedExceptionCode 101
* @expectedExceptionMessage Group does not exist
*/
public function testGetSubAdminsOfGroupsNotExists() { public function testGetSubAdminsOfGroupsNotExists() {
$result = $this->api->getSubAdminsOfGroup([ $this->api->getSubAdminsOfGroup('NonExistingGroup');
'groupid' => 'NonExistingGroup',
]);
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertFalse($result->succeeded());
$this->assertEquals(101, $result->getStatusCode());
$this->assertEquals('Group does not exist', $result->getMeta()['message']);
} }
public function testGetSubAdminsOfGroup() { public function testGetSubAdminsOfGroup() {
@ -305,12 +264,7 @@ class GroupsTest extends \Test\TestCase {
$this->createUser('SubAdmin2'), $this->createUser('SubAdmin2'),
]); ]);
$result = $this->api->getSubAdminsOfGroup([ $result = $this->api->getSubAdminsOfGroup('GroupWithSubAdmins');
'groupid' => 'GroupWithSubAdmins',
]);
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertTrue($result->succeeded());
$this->assertEquals(['SubAdmin1', 'SubAdmin2'], $result->getData()); $this->assertEquals(['SubAdmin1', 'SubAdmin2'], $result->getData());
} }
@ -328,53 +282,33 @@ class GroupsTest extends \Test\TestCase {
->willReturn([ ->willReturn([
]); ]);
$result = $this->api->getSubAdminsOfGroup([ $result = $this->api->getSubAdminsOfGroup('GroupWithOutSubAdmins');
'groupid' => 'GroupWithOutSubAdmins',
]);
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertTrue($result->succeeded());
$this->assertEquals([], $result->getData()); $this->assertEquals([], $result->getData());
} }
/**
* @expectedException \OCP\AppFramework\OCS\OCSException
* @expectedExceptionCode 101
* @expectedExceptionMessage Invalid group name
*/
public function testAddGroupEmptyGroup() { public function testAddGroupEmptyGroup() {
$this->request $this->api->addGroup('');
->method('getParam')
->with('groupid')
->willReturn('');
$result = $this->api->addGroup([]);
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertFalse($result->succeeded());
$this->assertEquals(101, $result->getStatusCode());
$this->assertEquals('Invalid group name', $result->getMeta()['message']);
} }
/**
* @expectedException \OCP\AppFramework\OCS\OCSException
* @expectedExceptionCode 102
*/
public function testAddGroupExistingGroup() { public function testAddGroupExistingGroup() {
$this->request
->method('getParam')
->with('groupid')
->willReturn('ExistingGroup');
$this->groupManager $this->groupManager
->method('groupExists') ->method('groupExists')
->with('ExistingGroup') ->with('ExistingGroup')
->willReturn(true); ->willReturn(true);
$result = $this->api->addGroup([]); $this->api->addGroup('ExistingGroup');
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertFalse($result->succeeded());
$this->assertEquals(102, $result->getStatusCode());
} }
public function testAddGroup() { public function testAddGroup() {
$this->request
->method('getParam')
->with('groupid')
->willReturn('NewGroup');
$this->groupManager $this->groupManager
->method('groupExists') ->method('groupExists')
->with('NewGroup') ->with('NewGroup')
@ -385,17 +319,10 @@ class GroupsTest extends \Test\TestCase {
->method('createGroup') ->method('createGroup')
->with('NewGroup'); ->with('NewGroup');
$result = $this->api->addGroup([]); $this->api->addGroup('NewGroup');
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertTrue($result->succeeded());
} }
public function testAddGroupWithSpecialChar() { public function testAddGroupWithSpecialChar() {
$this->request
->method('getParam')
->with('groupid')
->willReturn('Iñtërnâtiônàlizætiøn');
$this->groupManager $this->groupManager
->method('groupExists') ->method('groupExists')
->with('Iñtërnâtiônàlizætiøn') ->with('Iñtërnâtiônàlizætiøn')
@ -406,32 +333,28 @@ class GroupsTest extends \Test\TestCase {
->method('createGroup') ->method('createGroup')
->with('Iñtërnâtiônàlizætiøn'); ->with('Iñtërnâtiônàlizætiøn');
$result = $this->api->addGroup([]); $this->api->addGroup('Iñtërnâtiônàlizætiøn');
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertTrue($result->succeeded());
} }
/**
* @expectedException \OCP\AppFramework\OCS\OCSException
* @expectedExceptionCode 101
*/
public function testDeleteGroupNonExisting() { public function testDeleteGroupNonExisting() {
$result = $this->api->deleteGroup([ $this->api->deleteGroup('NonExistingGroup');
'groupid' => 'NonExistingGroup'
]);
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertFalse($result->succeeded());
$this->assertEquals(101, $result->getStatusCode());
} }
/**
* @expectedException \OCP\AppFramework\OCS\OCSException
* @expectedExceptionCode 102
*/
public function testDeleteAdminGroup() { public function testDeleteAdminGroup() {
$this->groupManager $this->groupManager
->method('groupExists') ->method('groupExists')
->with('admin') ->with('admin')
->willReturn('true'); ->willReturn('true');
$result = $this->api->deleteGroup([ $this->api->deleteGroup('admin');
'groupid' => 'admin'
]);
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertFalse($result->succeeded());
$this->assertEquals(102, $result->getStatusCode());
} }
public function testDeleteGroup() { public function testDeleteGroup() {
@ -450,10 +373,6 @@ class GroupsTest extends \Test\TestCase {
->method('delete') ->method('delete')
->willReturn(true); ->willReturn(true);
$result = $this->api->deleteGroup([ $this->api->deleteGroup('ExistingGroup');
'groupid' => 'ExistingGroup',
]);
$this->assertInstanceOf('\OC\OCS\Result', $result);
$this->assertTrue($result->succeeded());
} }
} }

View file

@ -165,6 +165,13 @@ trait BasicStructure {
$options['body'] = $fd; $options['body'] = $fd;
} }
// TODO: Fix this hack!
if ($verb === 'PUT' && $body === null) {
$options['body'] = [
'foo' => 'bar',
];
}
try { try {
$this->response = $client->send($client->createRequest($verb, $fullUrl, $options)); $this->response = $client->send($client->createRequest($verb, $fullUrl, $options));
} catch (\GuzzleHttp\Exception\ClientException $ex) { } catch (\GuzzleHttp\Exception\ClientException $ex) {

View file

@ -96,9 +96,12 @@ trait Provisioning {
} }
$options['body'] = [ $options['body'] = [
'userid' => $user, 'userid' => $user,
'password' => '123456' 'password' => '123456'
]; ];
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->send($client->createRequest("POST", $fullUrl, $options)); $this->response = $client->send($client->createRequest("POST", $fullUrl, $options));
if ($this->currentServer === 'LOCAL'){ if ($this->currentServer === 'LOCAL'){
@ -111,6 +114,9 @@ trait Provisioning {
$options2 = [ $options2 = [
'auth' => [$user, '123456'], 'auth' => [$user, '123456'],
]; ];
$options2['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$url = $fullUrl.'/'.$user; $url = $fullUrl.'/'.$user;
$client->send($client->createRequest('GET', $url, $options2)); $client->send($client->createRequest('GET', $url, $options2));
} }
@ -152,6 +158,9 @@ trait Provisioning {
$client = new Client(); $client = new Client();
$options = []; $options = [];
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
$options['headers'] = [
'OCS-APIREQUEST' => 'true'
];
$this->response = $client->get($fullUrl, $options); $this->response = $client->get($fullUrl, $options);
} }
@ -168,6 +177,9 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->get($fullUrl, $options); $this->response = $client->get($fullUrl, $options);
$respondedArray = $this->getArrayOfGroupsResponded($this->response); $respondedArray = $this->getArrayOfGroupsResponded($this->response);
@ -183,6 +195,9 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->get($fullUrl, $options); $this->response = $client->get($fullUrl, $options);
$respondedArray = $this->getArrayOfGroupsResponded($this->response); $respondedArray = $this->getArrayOfGroupsResponded($this->response);
@ -223,6 +238,9 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->get($fullUrl, $options); $this->response = $client->get($fullUrl, $options);
$groups = array($group); $groups = array($group);
@ -244,8 +262,11 @@ trait Provisioning {
} }
$options['body'] = [ $options['body'] = [
'groupid' => $group, 'groupid' => $group,
]; ];
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->send($client->createRequest("POST", $fullUrl, $options)); $this->response = $client->send($client->createRequest("POST", $fullUrl, $options));
if ($this->currentServer === 'LOCAL'){ if ($this->currentServer === 'LOCAL'){
@ -265,6 +286,13 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
// TODO: fix hack
$options['body'] = [
'foo' => 'bar'
];
$this->response = $client->send($client->createRequest("PUT", $fullUrl, $options)); $this->response = $client->send($client->createRequest("PUT", $fullUrl, $options));
} }
@ -280,6 +308,9 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->send($client->createRequest("DELETE", $fullUrl, $options)); $this->response = $client->send($client->createRequest("DELETE", $fullUrl, $options));
} }
@ -295,6 +326,9 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->send($client->createRequest("DELETE", $fullUrl, $options)); $this->response = $client->send($client->createRequest("DELETE", $fullUrl, $options));
} }
@ -323,10 +357,13 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$options['body'] = [ $options['body'] = [
'groupid' => $group, 'groupid' => $group,
]; ];
$this->response = $client->send($client->createRequest("POST", $fullUrl, $options)); $this->response = $client->send($client->createRequest("POST", $fullUrl, $options));
} }
@ -337,6 +374,9 @@ trait Provisioning {
$client = new Client(); $client = new Client();
$options = []; $options = [];
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->get($fullUrl, $options); $this->response = $client->get($fullUrl, $options);
} }
@ -394,6 +434,9 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->get($fullUrl, $options); $this->response = $client->get($fullUrl, $options);
$respondedArray = $this->getArrayOfSubadminsResponded($this->response); $respondedArray = $this->getArrayOfSubadminsResponded($this->response);
@ -415,8 +458,11 @@ trait Provisioning {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['body'] = [ $options['body'] = [
'groupid' => $group 'groupid' => $group
]; ];
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->send($client->createRequest("POST", $fullUrl, $options)); $this->response = $client->send($client->createRequest("POST", $fullUrl, $options));
PHPUnit_Framework_Assert::assertEquals(200, $this->response->getStatusCode()); PHPUnit_Framework_Assert::assertEquals(200, $this->response->getStatusCode());
} }
@ -433,6 +479,9 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->get($fullUrl, $options); $this->response = $client->get($fullUrl, $options);
$respondedArray = $this->getArrayOfSubadminsResponded($this->response); $respondedArray = $this->getArrayOfSubadminsResponded($this->response);
@ -561,6 +610,9 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->get($fullUrl, $options); $this->response = $client->get($fullUrl, $options);
$respondedArray = $this->getArrayOfAppsResponded($this->response); $respondedArray = $this->getArrayOfAppsResponded($this->response);
@ -579,6 +631,9 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->get($fullUrl, $options); $this->response = $client->get($fullUrl, $options);
$respondedArray = $this->getArrayOfAppsResponded($this->response); $respondedArray = $this->getArrayOfAppsResponded($this->response);
@ -597,6 +652,9 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->get($fullUrl, $options); $this->response = $client->get($fullUrl, $options);
PHPUnit_Framework_Assert::assertEquals("false", $this->response->xml()->data[0]->enabled); PHPUnit_Framework_Assert::assertEquals("false", $this->response->xml()->data[0]->enabled);
@ -613,6 +671,9 @@ trait Provisioning {
if ($this->currentUser === 'admin') { if ($this->currentUser === 'admin') {
$options['auth'] = $this->adminUser; $options['auth'] = $this->adminUser;
} }
$options['headers'] = [
'OCS-APIREQUEST' => 'true',
];
$this->response = $client->get($fullUrl, $options); $this->response = $client->get($fullUrl, $options);
PHPUnit_Framework_Assert::assertEquals("true", $this->response->xml()->data[0]->enabled); PHPUnit_Framework_Assert::assertEquals("true", $this->response->xml()->data[0]->enabled);

View file

@ -408,6 +408,7 @@ class DIContainer extends SimpleContainer implements IAppContainer {
$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) { $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
$dispatcher = new MiddlewareDispatcher(); $dispatcher = new MiddlewareDispatcher();
$dispatcher->registerMiddleware($c['CORSMiddleware']); $dispatcher->registerMiddleware($c['CORSMiddleware']);
$dispatcher->registerMiddleware($c['OCSMiddleware']);
$dispatcher->registerMiddleware($c['SecurityMiddleware']); $dispatcher->registerMiddleware($c['SecurityMiddleware']);
$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']); $dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
@ -416,7 +417,6 @@ class DIContainer extends SimpleContainer implements IAppContainer {
} }
$dispatcher->registerMiddleware($c['SessionMiddleware']); $dispatcher->registerMiddleware($c['SessionMiddleware']);
$dispatcher->registerMiddleware($c['OCSMiddleware']);
return $dispatcher; return $dispatcher;
}); });

View file

@ -23,8 +23,14 @@
namespace OC\AppFramework\Middleware; namespace OC\AppFramework\Middleware;
use OC\AppFramework\Http; use OC\AppFramework\Http;
use OCP\API;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\OCSResponse; use OCP\AppFramework\Http\OCSResponse;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\OCS\OCSException; use OCP\AppFramework\OCS\OCSException;
use OCP\AppFramework\OCS\OCSForbiddenException;
use OCP\AppFramework\OCS\OCSNotFoundException;
use OCP\AppFramework\OCSController; use OCP\AppFramework\OCSController;
use OCP\IRequest; use OCP\IRequest;
use OCP\AppFramework\Middleware; use OCP\AppFramework\Middleware;
@ -54,12 +60,35 @@ class OCSMiddleware extends Middleware {
$code = $exception->getCode(); $code = $exception->getCode();
if ($code === 0) { if ($code === 0) {
$code = Http::STATUS_INTERNAL_SERVER_ERROR; $code = API::RESPOND_UNKNOWN_ERROR;
} }
// Build the response
$response = new OCSResponse($format, $code, $exception->getMessage()); $response = new OCSResponse($format, $code, $exception->getMessage());
// Forbidden always sets 401 (even on v1.php)
if ($exception instanceof OCSForbiddenException || $code === API::RESPOND_UNAUTHORISED) {
$response->setStatus(Http::STATUS_UNAUTHORIZED);
}
// On v2.php we set actual HTTP error codes
if (substr_compare($this->request->getScriptName(), '/ocs/v2.php', -strlen('/ocs/v2.php')) === 0) { if (substr_compare($this->request->getScriptName(), '/ocs/v2.php', -strlen('/ocs/v2.php')) === 0) {
$response->setStatus($code); if ($code === API::RESPOND_NOT_FOUND) {
$response->setStatus(Http::STATUS_NOT_FOUND);
} else if ($code === API::RESPOND_SERVER_ERROR) {
$response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
} else if ($code === API::RESPOND_UNKNOWN_ERROR) {
$response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
} else if ($code === API::RESPOND_UNAUTHORISED) {
// Already set
}
// 4xx and 5xx codes are forwarded as is.
else if ($code >= 400 && $code < 600) {
$response->setStatus($code);
} else {
// All other codes get a bad request
$response->setStatus(Http::STATUS_BAD_REQUEST);
}
} }
return $response; return $response;
} }
@ -67,6 +96,35 @@ class OCSMiddleware extends Middleware {
throw $exception; throw $exception;
} }
/**
* @param \OCP\AppFramework\Controller $controller
* @param string $methodName
* @param Response $response
* @return \OCP\AppFramework\Http\Response
*/
public function afterController($controller, $methodName, Response $response) {
/*
* If a different middleware has detected that a request unauthorized or forbidden
* we need to catch the response and convert it to a proper OCS response.
*/
if ($controller instanceof OCSController && !($response instanceof OCSResponse)) {
if ($response->getStatus() === Http::STATUS_UNAUTHORIZED ||
$response->getStatus() === Http::STATUS_FORBIDDEN) {
$format = $this->getFormat($controller);
$message = '';
if ($response instanceof JSONResponse) {
/** @var DataResponse $response */
$message = $response->getData()['message'];
}
$response = new OCSResponse($format, \OCP\API::RESPOND_UNAUTHORISED, $message);
$response->setStatus(Http::STATUS_UNAUTHORIZED);
}
}
return $response;
}
/** /**
* @param \OCP\AppFramework\Controller $controller * @param \OCP\AppFramework\Controller $controller
* @return string * @return string

View file

@ -27,14 +27,14 @@ use OCP\AppFramework\OCS\OCSBadRequestException;
use OCP\AppFramework\OCS\OCSException; use OCP\AppFramework\OCS\OCSException;
use OCP\AppFramework\OCS\OCSForbiddenException; use OCP\AppFramework\OCS\OCSForbiddenException;
use OCP\AppFramework\OCS\OCSNotFoundException; use OCP\AppFramework\OCS\OCSNotFoundException;
use OC\AppFramework\Http\Request; use OCP\IRequest;
use OC\AppFramework\Middleware\OCSMiddleware; use OC\AppFramework\Middleware\OCSMiddleware;
class OCSMiddlewareTest extends \Test\TestCase { class OCSMiddlewareTest extends \Test\TestCase {
/** /**
* @var Request * @var IRequest
*/ */
private $request; private $request;
@ -101,8 +101,18 @@ class OCSMiddlewareTest extends \Test\TestCase {
$this->assertInstanceOf('OCP\AppFramework\Http\OCSResponse', $result); $this->assertInstanceOf('OCP\AppFramework\Http\OCSResponse', $result);
$this->assertSame($message, $this->invokePrivate($result, 'message')); $this->assertSame($message, $this->invokePrivate($result, 'message'));
$this->assertSame($code, $this->invokePrivate($result, 'statuscode'));
$this->assertSame(200, $result->getStatus()); if ($exception->getCode() === 0) {
$this->assertSame(\OCP\API::RESPOND_UNKNOWN_ERROR, $this->invokePrivate($result, 'statuscode'));
} else {
$this->assertSame($code, $this->invokePrivate($result, 'statuscode'));
}
if ($exception instanceof OCSForbiddenException) {
$this->assertSame(Http::STATUS_UNAUTHORIZED, $result->getStatus());
} else {
$this->assertSame(200, $result->getStatus());
}
} catch (\Exception $e) { } catch (\Exception $e) {
$this->assertTrue($forward); $this->assertTrue($forward);
$this->assertEquals($exception, $e); $this->assertEquals($exception, $e);
@ -131,7 +141,11 @@ class OCSMiddlewareTest extends \Test\TestCase {
$this->assertInstanceOf('OCP\AppFramework\Http\OCSResponse', $result); $this->assertInstanceOf('OCP\AppFramework\Http\OCSResponse', $result);
$this->assertSame($message, $this->invokePrivate($result, 'message')); $this->assertSame($message, $this->invokePrivate($result, 'message'));
$this->assertSame($code, $this->invokePrivate($result, 'statuscode')); if ($exception->getCode() === 0) {
$this->assertSame(\OCP\API::RESPOND_UNKNOWN_ERROR, $this->invokePrivate($result, 'statuscode'));
} else {
$this->assertSame($code, $this->invokePrivate($result, 'statuscode'));
}
$this->assertSame($code, $result->getStatus()); $this->assertSame($code, $result->getStatus());
} catch (\Exception $e) { } catch (\Exception $e) {
$this->assertTrue($forward); $this->assertTrue($forward);
@ -161,7 +175,11 @@ class OCSMiddlewareTest extends \Test\TestCase {
$this->assertInstanceOf('OCP\AppFramework\Http\OCSResponse', $result); $this->assertInstanceOf('OCP\AppFramework\Http\OCSResponse', $result);
$this->assertSame($message, $this->invokePrivate($result, 'message')); $this->assertSame($message, $this->invokePrivate($result, 'message'));
$this->assertSame($code, $this->invokePrivate($result, 'statuscode')); if ($exception->getCode() === 0) {
$this->assertSame(\OCP\API::RESPOND_UNKNOWN_ERROR, $this->invokePrivate($result, 'statuscode'));
} else {
$this->assertSame($code, $this->invokePrivate($result, 'statuscode'));
}
$this->assertSame($code, $result->getStatus()); $this->assertSame($code, $result->getStatus());
} catch (\Exception $e) { } catch (\Exception $e) {
$this->assertTrue($forward); $this->assertTrue($forward);
@ -169,4 +187,50 @@ class OCSMiddlewareTest extends \Test\TestCase {
} }
} }
public function dataAfterController() {
$OCSController = $this->getMockBuilder('OCP\AppFramework\OCSController')
->disableOriginalConstructor()
->getMock();
$controller = $this->getMockBuilder('OCP\AppFramework\Controller')
->disableOriginalConstructor()
->getMock();
return [
[$OCSController, new Http\Response(), false],
[$OCSController, new Http\JSONResponse(), false],
[$OCSController, new Http\JSONResponse(['message' => 'foo']), false],
[$OCSController, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), true],
[$OCSController, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), true],
[$controller, new Http\Response(), false],
[$controller, new Http\JSONResponse(), false],
[$controller, new Http\JSONResponse(['message' => 'foo']), false],
[$controller, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), false],
[$controller, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), false],
];
}
/**
* @dataProvider dataAfterController
*
* @param Controller $controller
* @param Http\Response $response
* @param bool $converted
*/
public function testAfterController($controller, $response, $converted) {
$OCSMiddleware = new OCSMiddleware($this->request);
$newResponse = $OCSMiddleware->afterController($controller, 'foo', $response);
if ($converted === false) {
$this->assertSame($response, $newResponse);
} else {
$this->assertInstanceOf('\OCP\AppFramework\Http\OCSResponse', $newResponse);
/** @var Http\OCSResponse $newResponse */
$this->assertSame($response->getData()['message'], $this->invokePrivate($newResponse, 'message'));
$this->assertSame(\OCP\API::RESPOND_UNAUTHORISED, $this->invokePrivate($newResponse, 'statuscode'));
$this->assertSame(Http::STATUS_UNAUTHORIZED, $newResponse->getStatus());
}
}
} }