Skip to content

Instantly share code, notes, and snippets.

@Scampi-ml
Created June 29, 2025 13:28
Show Gist options
  • Save Scampi-ml/518651c9e57c5828d148e06aa6967d22 to your computer and use it in GitHub Desktop.
Save Scampi-ml/518651c9e57c5828d148e06aa6967d22 to your computer and use it in GitHub Desktop.
app\Controllers\Admin\Users.php
<?php
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Shield\Models\GroupModel;
class Users extends BaseController
{
protected $userModel;
protected $groupModel;
public function __construct()
{
$this->userModel = new UserModel();
$this->groupModel = new GroupModel();
}
public function index()
{
// Check if user is logged in and is admin
if (!auth()->loggedIn() || !auth()->user()->inGroup('admin')) {
return redirect()->to('/')->with('error', 'You do not have permission to access that page.');
}
// Get all users
$users = $this->userModel->findAll();
return view('pages/admin/users/index', [
'users' => $users
]);
}
public function create()
{
// Check if user is logged in and is admin
if (!auth()->loggedIn() || !auth()->user()->inGroup('admin')) {
return redirect()->to('/')->with('error', 'You do not have permission to access that page.');
}
// Get unique groups from the auth_groups_users table
$db = \Config\Database::connect();
$groups = $db->table('auth_groups_users')
->select('`group`')
->distinct()
->get()
->getResultArray();
// If no groups exist, provide default groups
if (empty($groups)) {
$groups = [
['group' => 'admin'],
['group' => 'user']
];
}
return view('pages/admin/users/create', [
'groups' => $groups
]);
}
public function store()
{
// Check if user is logged in and is admin
if (!auth()->loggedIn() || !auth()->user()->inGroup('admin')) {
return redirect()->to('/')->with('error', 'You do not have permission to access that page.');
}
// Validate input
$rules = [
'username' => 'required|min_length[3]|max_length[30]|alpha_numeric_space|is_unique[users.username]',
'email' => 'required|valid_email',
'password' => 'required|strong_password',
'password_confirm' => 'required|matches[password]',
'groups' => 'required',
];
// Custom email uniqueness validation
$email = $this->request->getPost('email');
$db = \Config\Database::connect();
$existingEmail = $db->table('auth_identities')
->where('type', 'email')
->where('secret', $email)
->get()
->getRow();
if ($existingEmail) {
return redirect()->back()->withInput()->with('error', ['email' => 'This email address is already registered.']);
}
if (!$this->validate($rules)) {
return redirect()->back()->withInput()->with('error', $this->validator->getErrors());
}
try {
// Debug: Log the received data
log_message('info', 'Creating user with data: ' . json_encode([
'username' => $this->request->getPost('username'),
'email' => $this->request->getPost('email'),
'groups' => $this->request->getPost('groups')
]));
// Create user using Shield's approach (similar to AdminSeeder)
$user = new User([
'username' => $this->request->getPost('username'),
'email' => $this->request->getPost('email'),
'password' => $this->request->getPost('password'),
'active' => 1,
]);
// Save user first (without transaction, like AdminSeeder)
if (!$this->userModel->save($user)) {
log_message('error', 'User save failed: ' . json_encode($this->userModel->errors()));
return redirect()->back()->withInput()->with('error', $this->userModel->errors());
}
// Get the saved user with ID
$userId = $this->userModel->getInsertID();
log_message('info', 'User created with ID: ' . $userId);
$savedUser = $this->userModel->find($userId);
if (!$savedUser) {
log_message('error', 'Failed to retrieve user after creation');
return redirect()->back()->withInput()->with('error', 'Failed to create user.');
}
// Add user to groups (like AdminSeeder)
$groups = $this->request->getPost('groups');
if (is_array($groups)) {
foreach ($groups as $group) {
$savedUser->addGroup($group);
log_message('info', 'Added user to group: ' . $group);
}
}
// Activate the user (like AdminSeeder)
$savedUser->activate();
log_message('info', 'User creation completed successfully');
return redirect()->to('admin/users')->with('message', 'User created successfully.');
} catch (\Exception $e) {
log_message('error', 'User creation failed: ' . $e->getMessage());
log_message('error', 'Stack trace: ' . $e->getTraceAsString());
return redirect()->back()->withInput()->with('error', 'An error occurred while creating the user: ' . $e->getMessage());
}
}
public function edit($id = null)
{
// Check if user is logged in and is admin
if (!auth()->loggedIn() || !auth()->user()->inGroup('admin')) {
return redirect()->to('/')->with('error', 'You do not have permission to access that page.');
}
// Get user
$user = $this->userModel->find($id);
// Check if user exists
if (!$user) {
return redirect()->to('admin/users')->with('error', 'User not found.');
}
// Get unique groups from the auth_groups_users table
$db = \Config\Database::connect();
$groups = $db->table('auth_groups_users')
->select('`group`')
->distinct()
->get()
->getResultArray();
// Get user groups
$userGroups = $user->getGroups();
return view('pages/admin/users/edit', [
'user' => $user,
'groups' => $groups,
'userGroups' => $userGroups
]);
}
public function update($id = null)
{
// Check if user is logged in and is admin
if (!auth()->loggedIn() || !auth()->user()->inGroup('admin')) {
return redirect()->to('/')->with('error', 'You do not have permission to access that page.');
}
// Get user
$user = $this->userModel->find($id);
// Check if user exists
if (!$user) {
return redirect()->to('admin/users')->with('error', 'User not found.');
}
// Validate input
$rules = [
'username' => 'required|min_length[3]|max_length[30]|alpha_numeric_space',
'email' => 'required|valid_email',
'groups' => 'required',
];
// Add password validation if password is provided
if ($this->request->getPost('password')) {
$rules['password'] = 'required|strong_password';
$rules['password_confirm'] = 'required|matches[password]';
}
if (!$this->validate($rules)) {
return redirect()->back()->withInput()->with('error', $this->validator->getErrors());
}
// Update user
$userData = [
'username' => $this->request->getPost('username'),
'email' => $this->request->getPost('email'),
];
// Add password if provided
if ($this->request->getPost('password')) {
$userData['password'] = $this->request->getPost('password');
}
$user->fill($userData);
// Save user
$this->userModel->save($user);
// Update user groups
// First remove all existing groups
foreach ($user->getGroups() as $group) {
$user->removeGroup($group);
}
// Then add the selected groups
$groups = $this->request->getPost('groups');
if (is_array($groups)) {
foreach ($groups as $group) {
$user->addGroup($group);
}
}
return redirect()->to('admin/users')->with('message', 'User updated successfully.');
}
public function delete($id = null)
{
// Check if user is logged in and is admin
if (!auth()->loggedIn() || !auth()->user()->inGroup('admin')) {
return redirect()->to('/')->with('error', 'You do not have permission to access that page.');
}
// Get user
$user = $this->userModel->find($id);
// Check if user exists
if (!$user) {
return redirect()->to('admin/users')->with('error', 'User not found.');
}
// Check if user is current user
if ($user->id === auth()->id()) {
return redirect()->to('admin/users')->with('error', 'You cannot delete your own account.');
}
// Delete user
$this->userModel->delete($id);
return redirect()->to('admin/users')->with('message', 'User deleted successfully.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment