Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 87
0.00% covered (danger)
0.00%
0 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
AdminAccessController
0.00% covered (danger)
0.00%
0 / 87
0.00% covered (danger)
0.00%
0 / 5
342
0.00% covered (danger)
0.00%
0 / 1
 adminPermissions
0.00% covered (danger)
0.00%
0 / 33
0.00% covered (danger)
0.00%
0 / 1
42
 savePermissions
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
20
 findUser
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
12
 getPrivilegesFromRequest
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 getResourceFromRequest
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3/**
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; under version 2
7 * of the License (non-upgradable).
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17 *
18 * Copyright (c) 2014-2023 (original work) Open Assessment Technologies SA.
19 */
20
21namespace oat\taoDacSimple\controller;
22
23use common_exception_Error;
24use common_exception_Unauthorized;
25use core_kernel_classes_Resource;
26use Exception;
27use oat\generis\model\OntologyRdfs;
28use oat\oatbox\log\LoggerAwareTrait;
29use oat\oatbox\user\UserService;
30use oat\tao\model\taskQueue\QueueDispatcher;
31use oat\tao\model\taskQueue\TaskLogActionTrait;
32use oat\taoDacSimple\model\AdminService;
33use oat\taoDacSimple\model\PermissionProvider;
34use oat\taoDacSimple\model\PermissionsServiceException;
35use oat\taoDacSimple\model\PermissionsServiceFactory;
36use oat\taoDacSimple\model\tasks\ChangePermissionsTask;
37use tao_actions_CommonModule;
38use tao_models_classes_RoleService;
39
40use function GuzzleHttp\Psr7\stream_for;
41
42/**
43 * This controller is used to manage permission administration
44 *
45 * @author     Open Assessment Technologies SA
46 * @package    taoDacSimple
47 * @subpackage actions
48 * @license    GPL-2.0
49 *
50 */
51class AdminAccessController extends tao_actions_CommonModule
52{
53    use TaskLogActionTrait;
54    use LoggerAwareTrait;
55
56    /**
57     * Manage permissions
58     *
59     * @requiresRight id GRANT
60     *
61     * @throws common_exception_Error
62     */
63    public function adminPermissions(): void
64    {
65        $resource = new core_kernel_classes_Resource($this->getRequestParameter('id'));
66
67        $accessRights = AdminService::getUsersPermissions($resource->getUri());
68        $this->setData('privileges', PermissionProvider::getRightLabels());
69        $users = [];
70        $roles = [];
71        foreach ($accessRights as $uri => $privileges) {
72            $identity = new core_kernel_classes_Resource($uri);
73            if ($identity->isInstanceOf(tao_models_classes_RoleService::singleton()->getRoleClass())) {
74                $roles[$uri] = [
75                    'label'      => $identity->getLabel(),
76                    'privileges' => $privileges,
77                ];
78                unset($accessRights[$uri]);
79            }
80        }
81        if (!empty($accessRights)) {
82            $userService = $this->getServiceLocator()->get(UserService::SERVICE_ID);
83            $usersInfo = $userService->getUsers(array_keys($accessRights));
84            foreach ($usersInfo as $uri => $user) {
85                $labels = $user->getPropertyValues(OntologyRdfs::RDFS_LABEL);
86                $users[$uri] = [
87                    'label'      => empty($labels) ? 'unknown user' : reset($labels),
88                    'privileges' => $accessRights[$uri],
89                ];
90            }
91        }
92        $this->setData('users', $users);
93        $this->setData('roles', $roles);
94        $this->setData('isClass', $resource->isClass());
95
96        $permissionsServiceFactory = $this->getServiceLocator()->get(PermissionsServiceFactory::SERVICE_ID);
97        $this->setData(
98            'recursive',
99            $permissionsServiceFactory->getOption(PermissionsServiceFactory::OPTION_RECURSIVE_BY_DEFAULT)
100        );
101
102        $this->setData('uri', $resource->getUri());
103        $this->setData('label', _dh($resource->getLabel()));
104
105        $this->setView('AdminAccessController/index.tpl');
106    }
107
108    /**
109     * Add privileges for a group of users on resources. It works for add or modify privileges
110     *
111     * @requiresRight resource_id GRANT
112     */
113    public function savePermissions(): void
114    {
115        $recursive = ($this->getRequest()->getParameter('recursive') === '1');
116
117        try {
118            $taskParameters = [
119                ChangePermissionsTask::PARAM_RECURSIVE  => $recursive,
120                ChangePermissionsTask::PARAM_RESOURCE   => $this->getResourceFromRequest(),
121                ChangePermissionsTask::PARAM_PRIVILEGES => $this->getPrivilegesFromRequest()
122            ];
123            /** @var QueueDispatcher $queueDispatcher */
124            $queueDispatcher = $this->getServiceLocator()->get(QueueDispatcher::SERVICE_ID);
125            $task = $queueDispatcher->createTask(
126                new ChangePermissionsTask(),
127                $taskParameters,
128                'Processing permissions'
129            );
130            $this->returnTaskJson($task);
131        } catch (common_exception_Unauthorized $e) {
132            $this->response = $this->getPsrResponse()->withStatus(403, __('Unable to process your request'));
133        } catch (PermissionsServiceException $e) {
134            $this->response = $this->getPsrResponse()
135                ->withStatus(400, $e->getMessage())
136                ->withBody(stream_for(json_encode(['success' => false, 'message' => $e->getMessage()])))
137                ->withHeader('Content-Type', 'application/json');
138        } catch (Exception $e) {
139            $this->logError($e->getMessage());
140
141            $this->returnJson(['success' => false], 500);
142        }
143    }
144
145    /**
146     * Find users to assign access rights
147     */
148    public function findUser()
149    {
150        $params = $this->getGetParameter('params');
151        $query = $params['query'];
152        /** @var  UserService $userService */
153        $userService = $this->getServiceLocator()->get(UserService::SERVICE_ID);
154        $data = [];
155        foreach ($userService->findUser($query) as $user) {
156            $labels = $user->getPropertyValues(OntologyRdfs::RDFS_LABEL);
157            $label = empty($labels) ? __('unknown user') : reset($labels);
158            $data[] = [
159                'id' => $user->getIdentifier(),
160                'label' => $label,
161                OntologyRdfs::RDFS_LABEL => $label,//@deprecated
162            ];
163        }
164        $response = [
165            'success' => true,
166            'page'    => 1,
167            'total'   => 1,
168            'records' => count($data),
169            'data'    => $data,
170        ];
171        return $this->returnJson($response);
172    }
173
174    private function getPrivilegesFromRequest(): array
175    {
176        if ($this->hasRequestParameter('privileges')) {
177            $privileges = $this->getRequestParameter('privileges');
178        } else {
179            $privileges = [];
180            foreach ($this->getRequest()->getParameter('users') as $userId => $data) {
181                unset($data['type']);
182                $privileges[$userId] = array_keys($data);
183            }
184        }
185
186        return $privileges;
187    }
188
189    /**
190     * @return string
191     *
192     * @throws common_exception_Error
193     */
194    private function getResourceFromRequest(): string
195    {
196        if ($this->hasRequestParameter('uri')) {
197            $resourceId = $this->getRequest()->getParameter('uri');
198        } else {
199            $resourceId = (string)$this->getRequest()->getParameter('resource_id');
200        }
201
202        return $resourceId;
203    }
204}