Merge branch 'develop' of github.com:cerebrate-project/cerebrate into develop

refacto/CRUDComponent
iglocska 2023-09-12 09:27:57 +02:00
commit 69b653dd59
No known key found for this signature in database
GPG Key ID: BEA224F1FEF113AC
11 changed files with 238 additions and 100 deletions

View File

@ -65,7 +65,8 @@ class SummaryCommand extends Command
$folderPath = rtrim($folderPath, '/');
$filename = sprintf('%s/%s.txt', $folderPath, $nationality);
$file_input = fopen($filename, 'w');
$organisationIDsForNationality = $this->_fetchOrganisationsForNationality($nationality);
$organisationForNationality = $this->_fetchOrganisationsForNationality($nationality);
$organisationIDsForNationality = array_keys($organisationForNationality);
if (empty($organisationIDsForNationality)) {
$message = sprintf('No changes for organisations with nationality `%s`', $nationality);
fwrite($file_input, $message);
@ -73,6 +74,7 @@ class SummaryCommand extends Command
return;
}
$userForOrg = $this->_fetchUserForOrg($organisationIDsForNationality);
$userEmailByID = Hash::combine($userForOrg, '{n}.id', '{n}.individual.email');
$userID = Hash::extract($userForOrg, '{n}.id');
$individualID = Hash::extract($userForOrg, '{n}.individual_id');
@ -80,9 +82,16 @@ class SummaryCommand extends Command
fwrite($file_input, $message);
$this->io->out($message);
$logsUsers = $this->_fetchLogsForUsers($userID, $days);
$logsUsers = array_map(function($log) use ($userEmailByID) {
$userID = $log['model_id'];
$log['element_id'] = $userID;
$log['element_display_field'] = $userEmailByID[$userID];
return $log;
}, $logsUsers);
$userByIDs = Hash::combine($userForOrg, '{n}.id', '{n}');
$logsUserMetaFields = $this->_fetchLogsForUserMetaFields($userID, $days);
$logsUserMetaFields = $this->_formatUserMetafieldLogs($logsUserMetaFields, $userByIDs);
$logsUserMetaFields = $this->_formatUserMetafieldLogs($logsUserMetaFields, $userEmailByID);
$logsUsersCombined = array_merge($logsUsers, $logsUserMetaFields);
usort($logsUsersCombined, function($a, $b) {
return $a['created'] < $b['created'] ? -1 : 1;
@ -97,6 +106,12 @@ class SummaryCommand extends Command
fwrite($file_input, $message);
$this->io->out($message);
$logsOrgs = $this->_fetchLogsForOrgs($organisationIDsForNationality, $days);
$logsOrgs = array_map(function ($log) use ($organisationIDsForNationality) {
$orgID = $log['model_id'];
$log['element_id'] = $orgID;
$log['element_display_field'] = $organisationIDsForNationality[$orgID];
return $log;
}, $logsOrgs);
$modifiedOrgs = $this->_formatLogsForTable($logsOrgs);
foreach ($modifiedOrgs as $row) {
fputcsv($file_input, $row);
@ -107,6 +122,12 @@ class SummaryCommand extends Command
fwrite($file_input, $message);
$this->io->out($message);
$logsIndividuals = $this->_fetchLogsForIndividuals($individualID, $days);
$logsIndividuals = array_map(function ($log) use ($userEmailByID) {
$individualID = $log['model_id'];
$log['element_id'] = $individualID;
$log['element_display_field'] = $userEmailByID[$individualID];
return $log;
}, $logsIndividuals);
$modifiedIndividuals = $this->_formatLogsForTable($logsIndividuals);
foreach ($modifiedIndividuals as $row) {
fputcsv($file_input, $row);
@ -125,12 +146,18 @@ class SummaryCommand extends Command
protected function _fetchOrganisationsForNationality(string $nationality): array
{
return array_keys($this->Organisations->find('list')
return $this->Organisations->find('list')
->where([
'nationality' => $nationality,
])
->all()
->toArray());
->toArray();
// return array_keys($this->Organisations->find('list')
// ->where([
// 'nationality' => $nationality,
// ])
// ->all()
// ->toArray());
}
protected function _fetchOrgNationalities(): array
@ -139,6 +166,7 @@ class SummaryCommand extends Command
->where([
'nationality !=' => '',
])
->group('nationality')
->all()
->extract('nationality')
->toList();
@ -190,9 +218,14 @@ class SummaryCommand extends Command
$metaFieldLogs = array_filter($logs, function ($log) use ($userIDs) {
return !empty($log['changed']['scope']) && $log['changed']['scope'] === 'user' && in_array($log['changed']['parent_id'], $userIDs);
});
$metaFieldDeletionLogs = array_filter($logs, function ($log) use ($userIDs) {
$metaFieldLogs = array_map(function ($log) {
$log['modified_user_id'] = $log['changed']['parent_id'];
return $log;
}, $metaFieldLogs);
$metaFieldDeletionLogs = array_filter($logs, function ($log) {
return $log['request_action'] === 'delete';
});
$allLogs = $metaFieldLogs;
foreach ($metaFieldDeletionLogs as $i => $log) {
$latestAssociatedLog = $this->_fetchLogs([
'contain' => ['Users'],
@ -205,11 +238,14 @@ class SummaryCommand extends Command
'limit' => 1,
]);
if (!empty($latestAssociatedLog)) {
$metaFieldDeletionLogs[$i]['changed']['orig_value'] = $latestAssociatedLog[0]['changed']['value'];
$metaFieldDeletionLogs[$i]['changed']['value'] = '';
if (in_array($latestAssociatedLog[0]['changed']['parent_id'], $userIDs)) {
$log['changed']['orig_value'] = $latestAssociatedLog[0]['changed']['value'];
$log['changed']['value'] = '';
$log['modified_user_id'] = $latestAssociatedLog[0]['changed']['parent_id'];
$allLogs[] = $log;
}
}
}
$allLogs = array_merge($metaFieldLogs, $metaFieldDeletionLogs);
return $allLogs;
}
@ -268,9 +304,9 @@ class SummaryCommand extends Command
}, $logs);
}
protected function _formatUserMetafieldLogs($logEntries, $userByIDs): array
protected function _formatUserMetafieldLogs($logEntries, $userEmailByID): array
{
return array_map(function($log) use ($userByIDs) {
return array_map(function($log) use ($userEmailByID) {
$log['model'] = 'Users';
$log['request_action'] = 'edit';
$log['changed'] = [
@ -279,13 +315,15 @@ class SummaryCommand extends Command
$log['changed']['value']
]
];
$log['element_id'] = $log['modified_user_id'];
$log['element_display_field'] = $userEmailByID[$log['modified_user_id']];
return $log;
}, $logEntries);
}
protected function _formatLogsForTable($logEntries): array
{
$header = ['Model', 'Action', 'Editor user', 'Log ID', 'Datetime', 'Change'];
$header = ['Model', 'Action', 'Editor user', 'Log ID', 'Datetime', 'Modified element ID', 'Modified element', 'Change'];
$data = [$header];
foreach ($logEntries as $logEntry) {
$formatted = [
@ -294,6 +332,8 @@ class SummaryCommand extends Command
sprintf('%s (%s)', $logEntry['user']['username'], $logEntry['user_id']),
$logEntry['id'],
$logEntry['created']->i18nFormat('yyyy-MM-dd HH:mm:ss'),
$logEntry['element_id'] ?? '-',
$logEntry['element_display_field'] ?? '-',
];
if ($logEntry['request_action'] == 'edit') {
$formatted[] = json_encode($logEntry['changed'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

View File

@ -49,6 +49,9 @@ class AlignmentsController extends AppController
throw new NotFoundException(__('Invalid alignment.'));
}
$alignment = $this->Alignments->get($id);
if (!$this->canEditIndividual($alignment->individual_id) || !$this->canEditOrganisation($alignment->organisation_id)) {
throw new MethodNotAllowedException(__('You cannot delete this alignments.'));
}
if ($this->request->is('post') || $this->request->is('delete')) {
if ($this->Alignments->delete($alignment)) {
$message = __('Alignments deleted.');
@ -73,8 +76,21 @@ class AlignmentsController extends AppController
if (empty($scope) || empty($source_id)) {
throw new NotAcceptableException(__('Invalid input. scope and source_id expected as URL parameters in the format /alignments/add/[scope]/[source_id].'));
}
if (!in_array($scope, ['individuals', 'organisations'])) {
throw new MethodNotAllowedException(__('Invalid scope. Should be `individuals` or `organisations`.'));
}
$this->loadModel('Individuals');
$this->loadModel('Organisations');
$validIndividualIDs = $this->Individuals->getValidIndividualsToEdit($this->ACL->getUser());
$validOrgs = $this->Organisations->getEditableOrganisationsForUser($this->ACL->getUser());
if ($scope == 'individuals' && !$this->canEditIndividual($source_id)) {
throw new MethodNotAllowedException(__('You cannot modify that individual.'));
} else if ($scope == 'organisations' && !$this->canEditOrganisation($source_id)) {
throw new MethodNotAllowedException(__('You cannot modify that organisation.'));
}
$alignment = $this->Alignments->newEmptyEntity();
if ($this->request->is('post')) {
$this->Alignments->patchEntity($alignment, $this->request->getData());
@ -83,6 +99,11 @@ class AlignmentsController extends AppController
} else {
$alignment['organisation_id'] = $source_id;
}
if ($scope == 'individuals' && !$this->canEditOrganisation($alignment['organisation_id'])) {
throw new MethodNotAllowedException(__('You cannot use that organisation.'));
} else if ($scope == 'organisations' && !$this->canEditIndividual($alignment['individual_id'])) {
throw new MethodNotAllowedException(__('You cannot assign that individual.'));
}
$alignment = $this->Alignments->save($alignment);
if ($alignment) {
$message = __('Alignment added.');
@ -105,7 +126,7 @@ class AlignmentsController extends AppController
}
}
if ($scope === 'organisations') {
$individuals = $this->Individuals->find('list', ['valueField' => 'email'])->toArray();
$individuals = $this->Individuals->find('list', ['valueField' => 'email'])->where(['id IN' => $validIndividualIDs])->toArray();
$this->set('individuals', $individuals);
$organisation = $this->Organisations->find()->where(['id' => $source_id])->first();
if (empty($organisation)) {
@ -113,7 +134,7 @@ class AlignmentsController extends AppController
}
$this->set(compact('organisation'));
} else {
$organisations = $this->Organisations->find('list', ['valueField' => 'name'])->toArray();
$organisations = Hash::combine($validOrgs, '{n}.id', '{n}.name');
$this->set('organisations', $organisations);
$individual = $this->Individuals->find()->where(['id' => $source_id])->first();
if (empty($individual)) {
@ -124,6 +145,31 @@ class AlignmentsController extends AppController
$this->set(compact('alignment'));
$this->set('scope', $scope);
$this->set('source_id', $source_id);
$this->set('metaGroup', 'ContactDB');
}
private function canEditIndividual($indId): bool
{
$currentUser = $this->ACL->getUser();
if ($currentUser['role']['perm_admin']) {
return true;
}
$this->loadModel('Individuals');
$validIndividuals = $this->Individuals->getValidIndividualsToEdit($currentUser);
if (in_array($indId, $validIndividuals)) {
return true;
}
return false;
}
private function canEditOrganisation($orgId): bool
{
$currentUser = $this->ACL->getUser();
if ($currentUser['role']['perm_admin']) {
return true;
}
if ($currentUser['role']['perm_org_admin'] && $currentUser['organisation']['id'] == $orgId) {
return true;
}
return false;
}
}

View File

@ -41,8 +41,8 @@ class ACLComponent extends Component
'queryACL' => ['perm_admin']
],
'Alignments' => [
'add' => ['perm_admin'],
'delete' => ['perm_admin'],
'add' => ['perm_admin', 'perm_org_admin'],
'delete' => ['perm_admin', 'perm_org_admin'],
'index' => ['*'],
'view' => ['*']
],
@ -368,6 +368,9 @@ class ACLComponent extends Component
if (!$currentUser['role']['perm_org_admin']) {
return false;
} else {
if ($currentUser['id'] == $user['id']) {
return true;
}
if ($currentUser['organisation_id'] !== $user['organisation_id']) {
return false;
}

View File

@ -118,13 +118,19 @@ class UserSettingsController extends AppController
} else {
$validUsers = $this->Users->find('list')->select(['id', 'username'])->order(['username' => 'asc'])->all()->toArray();
}
$dropdownData = [
'user' => [$entity->user_id => $validUsers[$entity->user_id]],
];
$entity = $this->CRUD->edit($id, [
'redirect' => ['action' => 'index', $entity->user_id],
'beforeSave' => function ($data) use ($validUsers) {
'beforeSave' => function ($data) use ($validUsers, $entity) {
if (!in_array($data['user_id'], array_keys($validUsers))) {
throw new MethodNotAllowedException(__('You cannot edit the given user.'));
}
if ($data['user_id'] != $entity->user_id) {
throw new MethodNotAllowedException(__('You cannot assign the setting to a different user.'));
}
return $data;
}
]);
@ -132,11 +138,9 @@ class UserSettingsController extends AppController
if (!empty($responsePayload)) {
return $responsePayload;
}
$dropdownData = [
'user' => $validUsers,
];
$this->set(compact('dropdownData'));
$this->set('user_id', $this->entity->user_id);
$this->set('is_edit', true);
$this->render('add');
}

View File

@ -51,7 +51,7 @@ class UsersController extends AppController
}
$this->set(
'validRoles',
$this->Users->Roles->find('list')->select(['id', 'name'])->order(['name' => 'asc'])->where(['perm_admin' => 0])->all()->toArray()
$this->Users->Roles->find('list')->select(['id', 'name'])->order(['name' => 'asc'])->where(['perm_admin' => 0, 'perm_org_admin' => 0])->all()->toArray()
);
$this->set('metaGroup', $this->isAdmin ? 'Administration' : 'Cerebrate');
}
@ -259,7 +259,7 @@ class UsersController extends AppController
$params['fields'][] = 'disabled';
if (!$currentUser['role']['perm_admin']) {
$params['afterFind'] = function ($data, &$params) use ($currentUser, $validRoles) {
if (!in_array($data['role_id'], array_keys($validRoles))) {
if (!in_array($data['role_id'], array_keys($validRoles)) && $this->ACL->getUser()['id'] != $data['id']) {
throw new MethodNotAllowedException(__('You cannot edit the given privileged user.'));
}
if (!$this->ACL->canEditUser($currentUser, $data)) {
@ -268,7 +268,7 @@ class UsersController extends AppController
return $data;
};
$params['beforeSave'] = function ($data) use ($currentUser, $validRoles) {
if (!in_array($data['role_id'], array_keys($validRoles))) {
if (!in_array($data['role_id'], array_keys($validRoles)) && $this->ACL->getUser()['id'] != $data['id']) {
throw new MethodNotAllowedException(__('You cannot assign the chosen role to a user.'));
}
return $data;
@ -284,6 +284,9 @@ class UsersController extends AppController
if (empty($currentUser['role']['perm_admin'])) {
$org_conditions = ['id' => $currentUser['organisation_id']];
}
if ($this->ACL->getUser()['id'] == $id) {
$validRoles[$this->ACL->getUser()['role']['id']] = $this->ACL->getUser()['role']['name']; // include the current role of the user
}
$dropdownData = [
'role' => $validRoles,
'organisation' => $this->Users->Organisations->find('list', [

View File

@ -125,7 +125,7 @@ class IndividualsTable extends AppTable
public function getValidIndividualsToEdit(object $currentUser): array
{
$validRoles = $this->Users->Roles->find('list')->select(['id'])->where(['perm_admin' => 0, 'perm_org_admin' => 0])->all()->toArray();
$validIndividualIds = $this->Users->find('list')->select(['individual_id'])->where(
$validIndividualIds = $this->Users->find()->select(['individual_id'])->where(
[
'organisation_id' => $currentUser['organisation_id'],
'disabled' => 0,
@ -134,7 +134,7 @@ class IndividualsTable extends AppTable
['id' => $currentUser['id']],
]
]
)->all()->toArray();
return array_keys($validIndividualIds);
)->all()->extract('individual_id')->toArray();
return $validIndividualIds;
}
}

View File

@ -83,4 +83,17 @@ class OrganisationsTable extends AppTable
$this->saveMetaFields($id, $org);
}
}
public function getEditableOrganisationsForUser($user): array
{
$query = $this->find();
if (empty($user['role']['perm_admin'])) {
if (!empty($user['role']['perm_org_admin'])) {
$query->where(['Organisations.id' => $user['organisation']['id']]);
} else {
return []; // User not an org_admin. Cannot edit orgs
}
}
return $query->all()->toList();
}
}

View File

@ -10,6 +10,7 @@
'label' => __('User'),
'options' => $dropdownData['user'],
'value' => !is_null($user_id) ? $user_id : '',
'disabled' => !empty($is_edit),
],
[
'field' => 'name',

View File

@ -135,6 +135,9 @@ echo $this->element('genericElements/IndexTable/index_table', [
],
'function' => function ($row, $options) use ($loggedUser, $validRoles) {
if (empty($loggedUser['role']['perm_admin'])) {
if ($row['id'] == $loggedUser['id']) {
return true;
}
if (empty($loggedUser['role']['perm_org_admin'])) {
return false;
}

View File

@ -4,43 +4,56 @@ $alignments = '';
$canRemove = $this->request->getParam('prefix') !== 'Open';
if ($field['scope'] === 'individuals') {
foreach ($raw_alignments as $alignment) {
$alignments .= sprintf(
'<div><span class="fw-bold">%s</span> @ %s <a href="#" class="fas fa-trash .text-reset .text-decoration-none" onClick="%s"></a></div>',
h($alignment['type']),
sprintf(
'<a href="%s/organisations/view/%s">%s</a>',
$baseurl,
h($alignment['organisation']['id']),
h($alignment['organisation']['name'])
),
!$canRemove ? '' : sprintf(
"UI.submissionModalForIndex(%s);",
sprintf(
"'/alignments/delete/%s'",
h($alignment['id'])
$canEdit = in_array($alignment->individual_id, $editableIds);
$alignmentEntryHtml = $this->Bootstrap->node('span', ['class' => ['fw-bold']], h($alignment['type']));
$alignmentEntryHtml .= ' @ ' . $this->Bootstrap->node('span', ['class' => ['ms-1']], sprintf(
'<a href="%s/organisations/view/%s">%s</a>',
$baseurl,
h($alignment['organisation']['id']),
h($alignment['organisation']['name'])
),);
if ($canRemove && !empty($canEdit)) {
$alignmentEntryHtml .= $this->Bootstrap->button([
'icon' => 'trash',
'variant' => 'link',
'class' => ['ms-1', 'p-0'
],
'onclick' => sprintf(
"UI.submissionModalForSinglePage(%s);",
sprintf(
"'/alignments/delete/%s'",
$alignment['id']
)
)
)
);
]);
}
$alignments .= sprintf('<div>%s</div>', $alignmentEntryHtml);
}
} else if ($field['scope'] === 'organisations') {
foreach ($raw_alignments as $alignment) {
$alignments .= sprintf(
'<div>[<span class="fw-bold">%s</span>] %s <a href="#" class="fas fa-trash .text-reset .text-decoration-none" onClick="%s"></a></div>',
h($alignment['type']),
sprintf(
'<a href="%s/individuals/view/%s">%s</a>',
$baseurl,
h($alignment['individual']['id']),
h($alignment['individual']['email'])
),
!$canRemove ? '' : sprintf(
"UI.submissionModalForIndex(%s);",
sprintf(
"'/alignments/delete/%s'",
h($alignment['id'])
$canEdit = in_array($alignment->organisation_id, $editableIds);
$alignmentEntryHtml = '[' . $this->Bootstrap->node('span', ['class' => ['fw-bold']], h($alignment['type'])) . ']';
$alignmentEntryHtml .= $this->Bootstrap->node('span', ['class' => ['ms-1']], sprintf(
'<a href="%s/organisations/view/%s">%s</a>',
$baseurl,
h($alignment['individual']['id']),
h($alignment['individual']['email'])
),);
if ($canRemove && !empty($canEdit)) {
$alignmentEntryHtml .= $this->Bootstrap->button([
'icon' => 'trash',
'variant' => 'link',
'class' => ['ms-1', 'p-0'],
'onclick' => sprintf(
"UI.submissionModalForSinglePage(%s);",
sprintf(
"'/alignments/delete/%s'",
$alignment['id']
)
)
)
);
]);
}
$alignments .= sprintf('<div>%s</div>', $alignmentEntryHtml);
}
}
echo $alignments;

View File

@ -10,52 +10,64 @@ if (!empty($field['path'])) {
}
if ($field['scope'] === 'individuals') {
foreach ($extracted['alignments'] as $alignment) {
$alignments .= sprintf(
'<div><span class="fw-bold">%s</span> @ %s <a href="#" class="fas fa-trash" onClick="%s"></a></div>',
h($alignment['type']),
sprintf(
'<a href="%s/organisations/view/%s">%s</a>',
$baseurl,
h($alignment['organisation']['id']),
h($alignment['organisation']['name'])
),
sprintf(
"UI.submissionModalForSinglePage(%s);",
sprintf(
"'/alignments/delete/%s'",
$alignment['id']
$alignmentEntryHtml = $this->Bootstrap->node('span', ['class' => ['fw-bold']], h($alignment['type']));
$alignmentEntryHtml .= ' @ ' . $this->Bootstrap->node('span', ['class' => ['ms-1']], sprintf(
'<a href="%s/organisations/view/%s">%s</a>',
$baseurl,
h($alignment['organisation']['id']),
h($alignment['organisation']['name'])
),);
if (!empty($canEdit)) {
$alignmentEntryHtml .= $this->Bootstrap->button([
'icon' => 'trash',
'variant' => 'link',
'class' => ['ms-1', 'p-0'],
'onclick' => sprintf(
"UI.submissionModalForSinglePage(%s);",
sprintf(
"'/alignments/delete/%s'",
$alignment['id']
)
)
)
);
]);
}
$alignments .= sprintf('<div>%s</div>', $alignmentEntryHtml);
}
} else if ($field['scope'] === 'organisations') {
foreach ($extracted['alignments'] as $alignment) {
$alignments .= sprintf(
'<div>[<span class="fw-bold">%s</span>] %s <a href="#" class="fas fa-trash" onClick="%s"></a></div>',
h($alignment['type']),
sprintf(
'<a href="%s/individuals/view/%s">%s</a>',
$baseurl,
h($alignment['individual']['id']),
h($alignment['individual']['email'])
),
sprintf(
"UI.submissionModalForSinglePage(%s);",
sprintf(
"'/alignments/delete/%s'",
$alignment['id']
$alignmentEntryHtml = '[' . $this->Bootstrap->node('span', ['class' => ['fw-bold']], h($alignment['type'])) . ']';
$alignmentEntryHtml .= $this->Bootstrap->node('span', ['class' => ['ms-1']], sprintf(
'<a href="%s/organisations/view/%s">%s</a>',
$baseurl,
h($alignment['individual']['id']),
h($alignment['individual']['email'])
),);
if (!empty($canEdit)) {
$alignmentEntryHtml .= $this->Bootstrap->button([
'icon' => 'trash',
'variant' => 'link',
'class' => ['ms-1', 'p-0'],
'onclick' => sprintf(
"UI.submissionModalForSinglePage(%s);",
sprintf(
"'/alignments/delete/%s'",
$alignment['id']
)
)
)
);
]);
}
$alignments .= sprintf('<div>%s</div>', $alignmentEntryHtml);
}
}
echo sprintf(
'<div class="alignments-list">%s</div><div class="alignments-add-container"><button class="alignments-add-button btn btn-primary btn-sm" onclick="%s">%s</button></div>',
$alignments,
sprintf(
"UI.submissionModalForSinglePage('/alignments/add/%s/%s');",
h($field['scope']),
h($extracted['id'])
),
$field['scope'] === 'individuals' ? __('Add organisation') : __('Add individual')
);
echo sprintf('<div class="alignments-list">%s</div>', $alignments);
if (!empty($canEdit)) {
echo sprintf(
'<div class="alignments-add-container"><button class="alignments-add-button btn btn-primary btn-sm" onclick="%s">%s</button></div>',
sprintf(
"UI.submissionModalForSinglePage('/alignments/add/%s/%s');",
h($field['scope']),
h($extracted['id'])
),
$field['scope'] === 'individuals' ? __('Add organisation') : __('Add individual')
);
}