Arreglando grupos de usuarios

This commit is contained in:
imnavajas
2024-05-03 16:36:02 +02:00
parent 9858616b6e
commit c152cf699d
12 changed files with 186 additions and 198 deletions

View File

@ -13,6 +13,8 @@ declare(strict_types=1);
namespace Config; namespace Config;
require "RBAC/roles.php";
use CodeIgniter\Shield\Config\AuthGroups as ShieldAuthGroups; use CodeIgniter\Shield\Config\AuthGroups as ShieldAuthGroups;
class AuthGroups extends ShieldAuthGroups class AuthGroups extends ShieldAuthGroups
@ -40,28 +42,7 @@ class AuthGroups extends ShieldAuthGroups
* *
* @see https://codeigniter4.github.io/shield/quick_start_guide/using_authorization/#change-available-groups for more info * @see https://codeigniter4.github.io/shield/quick_start_guide/using_authorization/#change-available-groups for more info
*/ */
public array $groups = [ public array $groups = SK_ROLES;
'superadmin' => [
'title' => 'Super Admin',
'description' => 'Complete control of the site.',
],
'admin' => [
'title' => 'Admin',
'description' => 'Day to day administrators of the site.',
],
'developer' => [
'title' => 'Developer',
'description' => 'Site programmers.',
],
'user' => [
'title' => 'User',
'description' => 'General users of the site. Often customers.',
],
'beta' => [
'title' => 'Beta User',
'description' => 'Has access to beta-level features.',
],
];
/** /**
* -------------------------------------------------------------------- * --------------------------------------------------------------------

View File

@ -0,0 +1,24 @@
<?php
const SK_ROLES = [
'superadmin' => [
'title' => 'Super Admin',
'description' => 'Complete control of the site.',
],
'admin' => [
'title' => 'Admin',
'description' => 'Day to day administrators of the site.',
],
'developer' => [
'title' => 'Developer',
'description' => 'Site programmers.',
],
'user' => [
'title' => 'User',
'description' => 'General users of the site. Often customers.',
],
'beta' => [
'title' => 'Beta User',
'description' => 'Has access to beta-level features.',
],
];

View File

@ -5,8 +5,8 @@ namespace App\Controllers;
use App\Models\CronTabModel; use App\Models\CronTabModel;
use App\Models\NotificationModel; use App\Models\NotificationModel;
use App\Models\Usuarios\UserModel; use App\Models\Usuarios\UserModel;
use App\Models\Usuarios\UserGroupModel; use App\Models\Usuarios\GroupModel;
use App\Models\Usuarios\GroupUserModel; use App\Models\Usuarios\GroupsUsersModel;
use App\Models\ActivityModel; use App\Models\ActivityModel;
use CodeIgniter\RESTful\ResourceController; use CodeIgniter\RESTful\ResourceController;
@ -24,8 +24,8 @@ class Ajax extends ResourceController
function __construct() function __construct()
{ {
$this->user_model = new UserModel(); $this->user_model = new UserModel();
$this->group_model = new UserGroupModel(); $this->group_model = new GroupModel();
$this->group_user_model = new GroupUserModel(); $this->group_user_model = new GroupsUsersModel();
$this->activity_model = new ActivityModel(); $this->activity_model = new ActivityModel();
$this->crontab_model = new CronTabModel(); $this->crontab_model = new CronTabModel();
$this->notification_model = new NotificationModel(); $this->notification_model = new NotificationModel();
@ -56,20 +56,20 @@ class Ajax extends ResourceController
//Total number of records without filtering //Total number of records without filtering
$totalRecords = $this->user_model->select('id_user') $totalRecords = $this->user_model->select('id_user')
//->join('auth_user_group','auth_user_group.token = auth_user.group') //->join('auth_groups','auth_groups.token = auth_user.group')
->countAllResults(); ->countAllResults();
//Total number of records with filtering //Total number of records with filtering
$totalRecordwithFilter = $this->user_model->select('id_user') $totalRecordwithFilter = $this->user_model->select('id_user')
//->join('auth_user_group','auth_user_group.token = auth_user.group') //->join('auth_groups','auth_groups.token = auth_user.group')
->orLike('first_name', $searchValue) ->orLike('first_name', $searchValue)
->orLike('email', $searchValue) ->orLike('email', $searchValue)
->countAllResults(); ->countAllResults();
//Fetch records //Fetch records
//$records = $this->user_model->select('auth_user.*,auth_user_group.title') //$records = $this->user_model->select('auth_user.*,auth_groups.title')
$records = $this->user_model->select('auth_user.*') $records = $this->user_model->select('auth_user.*')
//->join('auth_user_group','auth_user_group.token = auth_user.group') //->join('auth_groups','auth_groups.token = auth_user.group')
->orLike('first_name', $searchValue) ->orLike('first_name', $searchValue)
->orLike('email', $searchValue) ->orLike('email', $searchValue)
->orderBy($columnName,$columnSortOrder) ->orderBy($columnName,$columnSortOrder)

View File

@ -1,15 +1,15 @@
<?php namespace App\Controllers\Configuracion; <?php namespace App\Controllers\Configuracion;
use App\Models\Usuarios\UserGroupModel; use App\Models\Usuarios\GroupModel;
use App\Models\Usuarios\GroupUserModel; use App\Models\Usuarios\GroupsUsersModel;
class Group extends \App\Controllers\GoBaseController class Group extends \App\Controllers\GoBaseController
{ {
use \CodeIgniter\API\ResponseTrait; use \CodeIgniter\API\ResponseTrait;
protected static $primaryModelName = 'App\Models\Usuarios\UserGroupModel'; protected static $primaryModelName = 'App\Models\Usuarios\GroupModel';
protected $modelName = UserGroupModel::class; protected $modelName = GroupModel::class;
protected static $singularObjectNameCc = 'userGroup'; protected static $singularObjectNameCc = 'userGroup';
protected static $singularObjectName = 'Group'; protected static $singularObjectName = 'Group';
@ -36,8 +36,8 @@ class Group extends \App\Controllers\GoBaseController
$this->viewData['usingClientSideDataTable'] = true; $this->viewData['usingClientSideDataTable'] = true;
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Groups.group')]); $this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Groups.group')]);
// IMN // IMN
$this->group_user_model = new GroupUserModel(); $this->group_user_model = new GroupsUsersModel();
$this->viewData['model'] = $this->group_user_model; $this->viewData['model'] = $this->model;
parent::index(); parent::index();
} }
@ -52,11 +52,9 @@ class Group extends \App\Controllers\GoBaseController
$postData = $this->request->getPost(); $postData = $this->request->getPost();
$title = $postData['title']; $name = $postData['name'];
$dashboard = $postData['dashboard']; unset($postData['name']);
unset($postData['title']); unset($postData['id']);
unset($postData['dashboard']);
unset($postData['id_group']);
unset($postData['save']); unset($postData['save']);
$controller = null; $controller = null;
@ -82,9 +80,7 @@ class Group extends \App\Controllers\GoBaseController
$temp_data['rules'] = json_encode($rules_access ?? '{}'); $temp_data['rules'] = json_encode($rules_access ?? '{}');
$temp_data['token'] = md5(uniqid(rand(), true));; $temp_data['name'] = $name;
$temp_data['title'] = $title;
$temp_data['dashboard'] = $dashboard;
$sanitizedData = $this->sanitized($temp_data, $nullIfEmpty); $sanitizedData = $this->sanitized($temp_data, $nullIfEmpty);
@ -126,10 +122,8 @@ class Group extends \App\Controllers\GoBaseController
endif; // ($requestMethod === 'post') endif; // ($requestMethod === 'post')
$this->viewData['group'] = isset($sanitizedData) ? new UserGroupModel($sanitizedData) : new UserGroupModel(); $this->viewData['group'] = isset($sanitizedData) ? new GroupModel($sanitizedData) : new GroupModel();
$this->viewData['formAction'] = route_to('createGroup'); $this->viewData['formAction'] = route_to('createGroup');
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Group.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix'); $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Group.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
@ -162,14 +156,10 @@ class Group extends \App\Controllers\GoBaseController
$postData = $this->request->getPost(); $postData = $this->request->getPost();
$id_group = $groupEntity->id_group; $id_group = $groupEntity->id;
$token = $groupEntity->token; $name = $postData['name'];
$title = $postData['title']; unset($postData['id']);
$dashboard = $postData['dashboard']; unset($postData['name']);
unset($postData['id_group']);
unset($postData['title']);
unset($postData['dashboard']);
$controller = null; $controller = null;
$rules_access = null; $rules_access = null;
@ -192,15 +182,12 @@ class Group extends \App\Controllers\GoBaseController
} }
} }
$temp_data['id_group'] = $id_group; $temp_data['id'] = $id_group;
$temp_data['rules'] = json_encode($rules_access ?? '{}'); $temp_data['rules'] = json_encode($rules_access ?? '{}');
$temp_data['token'] = $token; $temp_data['name'] = $name;
$temp_data['title'] = $title;
$temp_data['dashboard'] = $dashboard;
$sanitizedData = $this->sanitized($temp_data, $nullIfEmpty); $sanitizedData = $this->sanitized($temp_data, $nullIfEmpty);
$noException = true; $noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
@ -243,9 +230,7 @@ class Group extends \App\Controllers\GoBaseController
endif; // ($requestMethod === 'post') endif; // ($requestMethod === 'post')
$this->viewData['group'] = $groupEntity; $this->viewData['group'] = $groupEntity;
$this->viewData['formAction'] = route_to('updateGroup', $id); $this->viewData['formAction'] = route_to('updateGroup', $id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Group.userGroup') . ' ' . lang('Basic.global.edit3'); $this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Group.userGroup') . ' ' . lang('Basic.global.edit3');

View File

@ -3,8 +3,8 @@
use App\Entities\Usuarios\UserEntity; use App\Entities\Usuarios\UserEntity;
use App\Models\Usuarios\UserGroupModel; use App\Models\Usuarios\GroupModel;
use App\Models\Usuarios\GroupUserModel; use App\Models\Usuarios\GroupsUsersModel;
use App\Models\UserModel; use App\Models\UserModel;
class Users extends \App\Controllers\GoBaseController { class Users extends \App\Controllers\GoBaseController {
@ -31,8 +31,8 @@ class Users extends \App\Controllers\GoBaseController {
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) { public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) {
$this->group_model = new UserGroupModel(); $this->group_model = new GroupModel();
$this->group_user_model = new GroupUserModel(); $this->group_user_model = new GroupsUsersModel();
$this->user_model = new UserModel(); $this->user_model = new UserModel();
$this->viewData['pageTitle'] = lang('Users.moduleTitle'); $this->viewData['pageTitle'] = lang('Users.moduleTitle');

View File

@ -6,11 +6,10 @@ use CodeIgniter\Entity;
class UserGroupEntity extends \CodeIgniter\Entity\Entity class UserGroupEntity extends \CodeIgniter\Entity\Entity
{ {
protected $attributes = [ protected $attributes = [
"id_group" => null, "id" => null,
"title" => null, "name" => null,
"dashboard" => null, "description" => null,
"rules" => null, "rules" => null,
"token" => null,
"created_at" => null, "created_at" => null,
"updated_at" => null, "updated_at" => null,
]; ];

View File

@ -0,0 +1,103 @@
<?php
namespace App\Models\Usuarios;
class GroupModel extends \App\Models\BaseModel
{
protected $table = "auth_groups";
/**
* Whether primary key uses auto increment.
*
* @var bool
*/
protected $useAutoIncrement = true;
protected $primaryKey = "id";
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
const SORTABLE = [
1 => "t1.id",
2 => "t1.keyword",
3 => "t1.name",
4 => "t1.description",
5 => "t1.rules",
6 => "t1.created_at",
7 => "t1.updated_at",
];
protected $allowedFields = ["id", "name", "description", "rules"];
protected $returnType = "App\Entities\Usuarios\UserGroupEntity";
public static $labelField = "name";
protected $validationRules = [
"description" => [
"label" => "UserGroups.description",
"rules" => "required|max_length[150]",
],
"name" => [
"label" => "UserGroups.name",
"rules" => "required|max_length[50]",
],
];
protected $validationMessages = [
"description" => [
"max_length" => "UserGroups.validation.description.max_length",
"required" => "UserGroups.validation.description.required",
],
"name" => [
"max_length" => "UserGroups.validation.name.max_length",
"required" => "UserGroups.validation.name.required",
],
];
/**
* Get resource data.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResource(string $search = "")
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS id, t1.keyword AS keyword, t1.name AS name, t1.description AS description, t1.rules AS rules,
t1.token AS token, t1.created_at AS created_at, t1.updated_at AS updated_at"
);
return empty($search)
? $builder
: $builder
->groupStart()
->like("t1.id", $search)
->orLike("t1.keyword", $search)
->orLike("t1.name", $search)
->orLike("t1.description", $search)
->orLike("t1.rules", $search)
->orLike("t1.created_at", $search)
->orLike("t1.updated_at", $search)
->groupEnd();
}
public function getUsersWithRol($groupKeyWord)
{
return $this->db
->table('auth_groups_users')
->select('user_id')
->where('group', $groupKeyWord)
->countAllResults();
}
}

View File

@ -3,13 +3,10 @@ namespace App\Models\Usuarios;
use App\Models\BaseModel; use App\Models\BaseModel;
class GroupUserModel extends BaseModel class GroupsUsersModel extends BaseModel
{ {
protected $table = 'group_user'; protected $table = 'auth_groups_users';
protected $allowedFields = [ protected $allowedFields = [ ];
'token_user',
'token_group'
];
public function getUsersWithRol($token_group){ public function getUsersWithRol($token_group){

View File

@ -1,90 +0,0 @@
<?php
namespace App\Models\Usuarios;
class UserGroupModel extends \App\Models\BaseModel
{
protected $table = "auth_user_group";
/**
* Whether primary key uses auto increment.
*
* @var bool
*/
protected $useAutoIncrement = true;
protected $primaryKey = "id_group";
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
const SORTABLE = [
1 => "t1.id_group",
2 => "t1.title",
3 => "t1.dashboard",
4 => "t1.rules",
5 => "t1.token",
6 => "t1.created_at",
7 => "t1.updated_at",
];
protected $allowedFields = ["id_group", "title", "dashboard", "rules", "token"];
protected $returnType = "App\Entities\Usuarios\UserGroupEntity";
public static $labelField = "title";
protected $validationRules = [
"dashboard" => [
"label" => "UserGroups.dashboard",
"rules" => "required|max_length[50]",
],
"title" => [
"label" => "UserGroups.title",
"rules" => "required|max_length[150]",
],
];
protected $validationMessages = [
"dashboard" => [
"max_length" => "UserGroups.validation.dashboard.max_length",
"required" => "UserGroups.validation.dashboard.required",
],
"title" => [
"max_length" => "UserGroups.validation.title.max_length",
"required" => "UserGroups.validation.title.required",
],
];
/**
* Get resource data.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResource(string $search = "")
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id_group AS id_group, t1.title AS title, t1.dashboard AS dashboard, t1.rules AS rules,
t1.token AS token, t1.created_at AS created_at, t1.updated_at AS updated_at"
);
return empty($search)
? $builder
: $builder
->groupStart()
->like("t1.id_group", $search)
->orLike("t1.title", $search)
->orLike("t1.dashboard", $search)
->orLike("t1.rules", $search)
->orLike("t1.token", $search)
->orLike("t1.created_at", $search)
->orLike("t1.updated_at", $search)
->groupEnd();
}
}

View File

@ -187,8 +187,8 @@ class UserModel extends \App\Models\BaseModel
public function getGroupsTitles($user_token){ public function getGroupsTitles($user_token){
$sql = 'SELECT `auth_user_group`.`title` FROM `auth_user_group` $sql = 'SELECT `auth_groups`.`title` FROM `auth_groups`
JOIN `group_user` ON `auth_user_group`.`token` = `group_user`.`token_group` JOIN `group_user` ON `auth_groups`.`token` = `group_user`.`token_group`
JOIN `auth_user` ON `auth_user`.`token` = `group_user`.`token_user` JOIN `auth_user` ON `auth_user`.`token` = `group_user`.`token_user`
WHERE `auth_user`.`token` = \''. $user_token . '\''; WHERE `auth_user`.`token` = \''. $user_token . '\'';

View File

@ -11,32 +11,21 @@
<?= formAlert() ?> <?= formAlert() ?>
<form id="groupForm" method="post" class="card-body" action="<?= $formAction ?>"> <form id="groupForm" method="post" class="card-body" action="<?= $formAction ?>">
<?= csrf_field() ?> <?= csrf_field() ?>
<input type="hidden"
name="id_group"
value="<?= (isset($obj)) ? $obj['id_group'] : set_value('id_group') ?>"
>
<input type="hidden"
name="token"
value="<?= (isset($obj)) ? $obj['token'] : set_value('token') ?>"
>
<div class="row g-3"> <div class="row g-3">
<input type="hidden"
name="id_group"
value="<?= old('id', $group->id) ?>"
>
<div class="col-md-6"> <div class="col-md-6">
<label for="title" class="form-label text-dark"> <label for="title" class="form-label text-dark">
<?= lang("App.group_field_title") ?> <?= lang("App.group_field_title") ?>
</label> </label>
<input type="text" name="title" id="title" class="form-control" <input type="text" name="name" id="name" class="form-control"
value="<?= old('title', $group->title) ?>"> value="<?= old('name', $group->name) ?>">
</div>
<div class="col-md-6">
<label for="dashboard" class="form-label text-dark">
<?= lang("App.group_field_dashboard") ?>
</label>
<?php $id_select = (isset($group)) ? $group->dashboard : set_value('dashboard'); ?>
<select name="dashboard" id="dashboard" class="select2 form-control">
<option value="user" <?= $id_select == "user" ? 'selected' : '' ?>><?= lang("App.group_label_user") ?></option>
<option value="admin" <?= $id_select == "admin" ? 'selected' : '' ?>><?= lang("App.group_label_admin") ?></option>
</select>
</div> </div>
</div>
<div class="row g-3 mt-3">
<div class="col-md-6"> <div class="col-md-6">
<button type="button" name="select_all" <button type="button" name="select_all"
id="select_all" id="select_all"
@ -120,15 +109,15 @@
<?= $this->section('additionalInlineJs') ?> <?= $this->section('additionalInlineJs') ?>
$('#select_all').on('click', function () { $('#select_all').on('click', function () {
$(':checkbox').each(function() { $(':checkbox').each(function() {
this.checked = true; this.checked = true;
}); });
}); });
$('#remove_all').on('click', function () { $('#remove_all').on('click', function () {
$(':checkbox').each(function() { $(':checkbox').each(function() {
this.checked = false; this.checked = false;
});
}); });
});
<?= $this->endSection() ?> <?= $this->endSection() ?>

View File

@ -43,12 +43,12 @@
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<div class="d-flex justify-content-between"> <div class="d-flex justify-content-between">
<h6 class="fw-normal mb-2"><?= $model->getUsersWithRol($item->token); ?> usuarios en total</h6> <h6 class="fw-normal mb-2"><?= $model->getUsersWithRol($item->keyword); ?> usuarios en total</h6>
</div> </div>
<div class="d-flex justify-content-between align-items-end mt-1"> <div class="d-flex justify-content-between align-items-end mt-1">
<div class="role-heading"> <div class="role-heading">
<h4 class="mb-1"><?= esc($item->title) ?></h4> <h4 class="mb-1"><?= esc($item->name) ?></h4>
<a href="<?= route_to('editGroup', $item->id_group) ?>"> <a href="<?= route_to('editGroup', $item->id) ?>">
<span><?= lang('Basic.global.edit') ?></span> <span><?= lang('Basic.global.edit') ?></span>
</a> </a>
</div> </div>
@ -56,7 +56,7 @@
anchor('#confirm2delete', "<i class='ti ti-trash ti-md'></i>", anchor('#confirm2delete', "<i class='ti ti-trash ti-md'></i>",
[ [
'class' => 'text-muted', 'class' => 'text-muted',
'data-href' => route_to('deleteGroup', $item->id_group), 'data-href' => route_to('deleteGroup', $item->id),
'data-bs-toggle' => 'modal', 'data-bs-toggle' => 'modal',
'data-bs-target' => '#confirm2delete' 'data-bs-target' => '#confirm2delete'
]); ]);