Skip to content

Commit

Permalink
ban/unban user
Browse files Browse the repository at this point in the history
ban/unban user
  • Loading branch information
mshannaq authored Dec 8, 2023
2 parents 92f7ae3 + 09455d3 commit e034e21
Show file tree
Hide file tree
Showing 6 changed files with 305 additions and 0 deletions.
2 changes: 2 additions & 0 deletions app/Config/Routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
$routes->post('del/(:num)', 'Users::delUser/$1', ['filter' => 'session']); // json del user account
$routes->post('activate/(:num)', 'Users::activateUser/$1', ['filter' => 'session']); // json activate user email
$routes->post('deactivate/(:num)', 'Users::deactivateUser/$1', ['filter' => 'session']); // json deactivate user email
$routes->post('ban/(:num)', 'Users::banUser/$1', ['filter' => 'session']); // json ban user account
$routes->post('unban/(:num)', 'Users::unbanUser/$1', ['filter' => 'session']); // json unban user account
});

// language route
Expand Down
105 changes: 105 additions & 0 deletions app/Controllers/Users.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ public function listUsersData()
$order_by = 'username';
break;

case 'user_actstatus':
$order_by = 'status';
break;

case 'user_lastactive':
$order_by = 'last_active';
break;
Expand Down Expand Up @@ -123,6 +127,14 @@ public function listUsersData()
foreach ($users as $user) {
$user->email = esc($user->email);
$user->username = esc($user->username);

// account status
if ($user->status === 'banned') {
$userActStatus = '<span>' . lang('Users.ListUsersAccountStatusBanned') . "</span> <button id='btnUserUnBan' data-user-id='{$user->id}' data-user-name='{$user->username}' class='btn btn-sm btn-outline-success'>" . lang('Users.ListUsersAccountUnBanUser') . '</button>';
} else {
$userActStatus = '<span>' . lang('Users.ListUsersAccountStatusNormal') . "</span> <button id='btnUserBan' data-user-id='{$user->id}' data-user-name='{$user->username}' class='btn btn-sm btn-outline-danger'>" . lang('Users.ListUsersAccountBanUser') . '</button>';
}

// get the user usergroups
$userGroups = $user->getGroups();
$user_group = '';
Expand Down Expand Up @@ -156,6 +168,7 @@ public function listUsersData()
$users_data[] = [
'user_id_col' => $user->id,
'user_username_col' => $user->username,
'user_actstatus_col' => $userActStatus,
'user_lastactive_col' => $user->last_active ? $user->last_active->format('Y-m-d H:i:s') : '-',
'user_email_col' => $user->email,
'user_active_col' => $userActive,
Expand Down Expand Up @@ -300,4 +313,96 @@ public function deactivateUser(int $UserId)

return $this->response->setStatusCode(200)->setJSON($response);
}

public function banUser(int $UserId)
{
$response = [];
if (! auth()->user()->can('users.manage', 'super.admin')) {
$response['error'] = lang('Common.permissionsNoenoughpermissions');

return $this->response->setStatusCode(403)->setJSON($response);
}
$user_id = (int) $UserId;
$conditions = [
'id' => $user_id,
];
$users = $this->usermodel
->where($conditions)
->find();
if (count($users) !== 1) {
// that mean user not exists
$response['error'] = lang('Users.UserNotFound');

return $this->response->setStatusCode(200)->setJSON($response);
}

// user is exists i will try to ban it
foreach ($users as $user) {
if (! $user->isBanned()) {
// user cannot ban his account
$my_user_id = user_id();
if ($my_user_id === $user->id) {
// you cannot ban your own account
$response['error'] = lang('Users.ListUsersAccountBannedErrorYourSelf');
} else {
// not superadmin cannot ban superadmin
// now the current logged user usergroup
$auth = service('auth');
$my_user = $auth->user();
$my_user_groups = $my_user->getGroups();
// know the needed to ban user usergroup
$user_groups = $user->getGroups();
if (! in_array('superadmin', $my_user_groups, true) && in_array('superadmin', $user_groups, true)) {
// user is not super admin and try to ban superadmin . and this is nit allowed
// when you need to ban superadmin you need to be superadmin
$response['error'] = lang('Users.ListUsersAccountBannedErrorSuperadmin');

return $this->response->setStatusCode(200)->setJSON($response);
}

$user->ban();
$response['status'] = 'banned';
}
} else {
$response['error'] = lang('Users.ListUsersAccountBannedAlready');
}
}

return $this->response->setStatusCode(200)->setJSON($response);
}

public function unbanUser(int $UserId)
{
$response = [];
if (! auth()->user()->can('users.manage', 'super.admin')) {
$response['error'] = lang('Common.permissionsNoenoughpermissions');

return $this->response->setStatusCode(403)->setJSON($response);
}
$user_id = (int) $UserId;
$conditions = [
'id' => $user_id,
];
$users = $this->usermodel
->where($conditions)
->find();
if (count($users) !== 1) {
// that mean user not exists
$response['error'] = lang('Users.UserNotFound');

return $this->response->setStatusCode(200)->setJSON($response);
}

// user is exists i will try to unban it
foreach ($users as $user) {
if ($user->isBanned()) {
$user->unBan();
$response['status'] = 'unbanned';
} else {
$response['error'] = lang('Users.ListUsersAccountUnBannedAlready');
}
}

return $this->response->setStatusCode(200)->setJSON($response);
}
}
3 changes: 3 additions & 0 deletions app/Helpers/smarty_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,9 @@ function smarty_svg_error($text)
/**
* Create a nice URL to show on screen and not for real use on visits
*
* @param mixed $original_url
* @param mixed $max_length
*
* @return mixed|string
*/
function create_nice_url_for_show($original_url, $max_length = 50)
Expand Down
16 changes: 16 additions & 0 deletions app/Language/ar/Users.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,22 @@
'ListUsersEmailVerifiedStatusActivate' => 'تاكيد',
'ListUsersEmailVerifiedStatusDeActivate' => 'الغاء تاكيد',

'ListUsersAccountStatus' => 'الحالة',
'ListUsersAccountStatusBanned' => 'محظور',
'ListUsersAccountStatusNormal' => 'فعال',
'ListUsersAccountBanUser' => 'حظر',
'ListUsersAccountUnBanUser' => 'فك حظر',
'ListUsersAccountBannedOk' => 'تم حظر حساب المستخدم بنجاح',
'ListUsersAccountBannedErrorYourSelf' => 'لا يمكنك حظر حسابك',
'ListUsersAccountBannedErrorSuperadmin' => 'انت تحاول حظر مستخدم مشرف عام superadmin بيما حسابك لا يمتلك صلاحيات مشرف عام superadmin',
'ListUsersAccountBannedAlready' => 'حساب المستخدم محظور بالفعل',
'ListUsersAccountUnBannedOk' => 'تم الغاء الحظر عن حساب المستخدم',
'ListUsersAccountUnBannedAlready' => 'حساب المستخدم غير محظور بالفعل',
'ListUsersAccountBanUserTitle' => 'حظر حساب المستخدم',
'ListUsersAccountBanUserConfirm' => 'هل انت متاكد من انك تود حظر حساب المستخدم {0}؟',
'ListUsersAccountUnBanUserTitle' => 'الغاء الحظر عن حساب المستخدم',
'ListUsersAccountUnBanUserConfirm' => 'هل انت متاكد من انك تود الغاء الحظر حساب المستخدم {0}؟',

'UsersAddNewUser' => 'اضافة مستخدم جديد',

'UserActivateConfrimTitle' => 'تاكيد بريد مستخدم',
Expand Down
16 changes: 16 additions & 0 deletions app/Language/en/Users.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,22 @@
'ListUsersEmailVerifiedStatusActivate' => 'Activate',
'ListUsersEmailVerifiedStatusDeActivate' => 'Deactivate',

'ListUsersAccountStatus' => 'Status',
'ListUsersAccountStatusBanned' => 'Banned',
'ListUsersAccountStatusNormal' => 'Normal',
'ListUsersAccountBanUser' => 'Ban',
'ListUsersAccountUnBanUser' => 'Unban',
'ListUsersAccountBannedOk' => 'User account has been banned',
'ListUsersAccountBannedErrorYourSelf' => 'You cannot ban your self',
'ListUsersAccountBannedErrorSuperadmin' => 'You try to ban superadmin user while you are not superadmin',
'ListUsersAccountBannedAlready' => 'User Account is already banned',
'ListUsersAccountUnBannedOk' => 'User account has been unbanned',
'ListUsersAccountUnBannedAlready' => 'User Account is already unbanned',
'ListUsersAccountBanUserTitle' => 'Ban User Account',
'ListUsersAccountBanUserConfirm' => 'Are you sure you want to ban {0} user account?',
'ListUsersAccountUnBanUserTitle' => 'Un-ban user account',
'ListUsersAccountUnBanUserConfirm' => 'Are you sure you want to unban {0} user account?',

'UsersAddNewUser' => 'Add New User',

'UserActivateConfrimTitle' => 'Activate User Email',
Expand Down
163 changes: 163 additions & 0 deletions app/Views/basic/users/list.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ class="display table table-bordered table-striped table-hover dt-responsive"

<th><?= lang('Users.ListUsersColId'); ?></th>
<th><?= lang('Users.ListUsersColUsername'); ?></th>
<th><?= lang('Users.ListUsersAccountStatus'); ?></th>
<th><?= lang('Users.ListUsersColEmail'); ?></th>
<th><?= lang('Users.ListUsersColEmailVerifiedStatus'); ?></th>
<th><?= lang('Users.ListUsersColUserGroup'); ?></th>
Expand Down Expand Up @@ -181,6 +182,7 @@ class="display table table-bordered table-striped table-hover dt-responsive"
"columns": [
{"data": "user_id_col", "name": "user_id", orderable: true,"className": "dt-body-center"},
{"data": "user_username_col", "name": "user_username", orderable: true},
{"data": "user_actstatus_col", "name": "user_actstatus", orderable: true},
{"data": "user_email_col", "name": "user_email"},
{"data": "user_active_col", "name": "user_active", orderable: true},
{"data": "user_userroup_col", "name": "user_userroup", orderable: false},
Expand Down Expand Up @@ -446,6 +448,167 @@ class="display table table-bordered table-striped table-hover dt-responsive"

});

/* ban user */
$("#usersList").on("click", "#btnUserBan", function () {

var banButton = this;
var userId = this.dataset.userId;
var userAccountUsername = this.dataset.userName;


Swal.fire({
title: '<?= lang('Users.ListUsersAccountBanUserTitle'); ?>',
text: '<?= lang('Users.ListUsersAccountBanUserConfirm', ["' + userAccountUsername + '"]); ?>',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#d33',
cancelButtonColor: '#073600',
confirmButtonText: '<?= lang('Common.btnYes'); ?>',
cancelButtonText: '<?= lang('Common.btnNo'); ?>',
}).then((result) => {
if (result.isConfirmed) {
/* If user clicks "Yes", make AJAX request with CSRF token*/
$.ajax({
url: '/users/ban/'+userId,
type: 'POST',
data: {
/* Any data you want to send for deletion*/
/* Include CSRF token in the data*/

/* ... other data ...*/
},
headers: {
/*/ Include CSRF token in the request headers */
'X-CSRF-Token': csrfToken,
},
dataType: 'json',
success: function (response) {
/* Check if the server response indicates success*/
if (response.status === 'banned') {

/* change the button and the status */
$(banButton).attr('id', 'btnUserUnBan');
$(banButton).text('<?= lang('Users.ListUsersAccountUnBanUser'); ?>');
$(banButton).removeClass('btn-outline-danger').addClass('btn-outline-success');
$(banButton).prev('span').text('<?= lang('Users.ListUsersAccountStatusBanned'); ?>');

Swal.fire({
title: '<?= lang('Users.ListUsersAccountBannedOk'); ?>',
icon: 'success'
});
/* You can also perform additional actions based on the response*/

} else {
Swal.fire('Error', response.error, 'error');
}
},
error: function (xhr, status, error) {
/*/ Handle errors*/
if (xhr.responseJSON && xhr.responseJSON.error) {
/* json error */
Swal.fire({
title: '<?= lang('Common.ajaxErrorTitle'); ?>',
text: xhr.responseJSON.error,
icon: 'error',
confirmButtonText: '<?= lang('Common.btnOK'); ?>',
});
} else {
/* not json error may be network error*/
Swal.fire({
title: '<?= lang('Common.ajaxErrorTitle'); ?>',
text: '<?= lang('Common.ajaxCallError1'); ?>',
icon: 'error',
confirmButtonText: '<?= lang('Common.btnOK'); ?>',
});
}
}
});
}
});

});

/* unban user */
$("#usersList").on("click", "#btnUserUnBan", function () {

var unbanButton = this;
var userId = this.dataset.userId;
var userAccountUsername = this.dataset.userName;


Swal.fire({
title: '<?= lang('Users.ListUsersAccountUnBanUserTitle'); ?>',
text: '<?= lang('Users.ListUsersAccountUnBanUserConfirm', ["' + userAccountUsername + '"]); ?>',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#d33',
cancelButtonColor: '#073600',
confirmButtonText: '<?= lang('Common.btnYes'); ?>',
cancelButtonText: '<?= lang('Common.btnNo'); ?>',
}).then((result) => {
if (result.isConfirmed) {
/* If user clicks "Yes", make AJAX request with CSRF token*/
$.ajax({
url: '/users/unban/'+userId,
type: 'POST',
data: {
/* Any data you want to send for deletion*/
/* Include CSRF token in the data*/

/* ... other data ...*/
},
headers: {
/*/ Include CSRF token in the request headers */
'X-CSRF-Token': csrfToken,
},
dataType: 'json',
success: function (response) {
/* Check if the server response indicates success*/
if (response.status === 'unbanned') {

/* change the button and the status */
$(unbanButton).attr('id', 'btnUserBan');
$(unbanButton).text('<?= lang('Users.ListUsersAccountBanUser'); ?>');
$(unbanButton).removeClass('btn-outline-success').addClass('btn-outline-danger');
$(unbanButton).prev('span').text('<?= lang('Users.ListUsersAccountStatusNormal'); ?>');

Swal.fire({
title: '<?= lang('Users.ListUsersAccountUnBannedOk'); ?>',
icon: 'success'
});
/* You can also perform additional actions based on the response*/

} else {
Swal.fire('Error', response.error, 'error');
}
},
error: function (xhr, status, error) {
/*/ Handle errors*/
if (xhr.responseJSON && xhr.responseJSON.error) {
/* json error */
Swal.fire({
title: '<?= lang('Common.ajaxErrorTitle'); ?>',
text: xhr.responseJSON.error,
icon: 'error',
confirmButtonText: '<?= lang('Common.btnOK'); ?>',
});
} else {
/* not json error may be network error*/
Swal.fire({
title: '<?= lang('Common.ajaxErrorTitle'); ?>',
text: '<?= lang('Common.ajaxCallError1'); ?>',
icon: 'error',
confirmButtonText: '<?= lang('Common.btnOK'); ?>',
});
}
}
});
}
});

});



});

Expand Down

0 comments on commit e034e21

Please sign in to comment.