Categories
PHP

CodeIgniter 4 Shield User Management

Managing user accounts effectively is crucial for any web application. CodeIgniter 4 Shield simplifies this task with its powerful authentication and authorization tools. In this post, we will explore user profile management, password reset and recovery, and account activation and deactivation using CodeIgniter 4 Shield.

In the previous post we described how to create a basic CodeIgniter 4 project with composer and how to add the Shield dependency for authorization. How to create a basic login and Registration system and how to implement logout feature. We will take this post a step ahead and dive into the user management system in CodeIgniter 4 Shield.

1. User Profile Management

1.1 Creating User Profile Views and Forms

To manage user profiles, you need to create views and forms that allow users to view and update their information. Let’s start by creating a basic profile view and form.

Profile View (app/Views/profile_view.php):

<code><!DOCTYPE html>
<html>
<head>
    <title>User Profile</title>
</head>
<body>
    <h1>User Profile</h1>
    <form action="<?= site_url('profile/update') ?>" method="post">
        <?= csrf_field() ?>
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" value="<?= esc($user['username']) ?>" required>
        
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" value="<?= esc($user['email']) ?>" required>
        
        <input type="submit" value="Update Profile">
    </form>
</body>
</html></code>
Code language: PHP (php)
 

Profile Controller (app/Controllers/Profile.php):

<code><?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Profile extends Controller
{
    public function index()
    {
        $userModel = model('UserModel');
        $userId = auth()->id(); // Get current user ID
        $data['user'] = $userModel->find($userId);
        return view('profile_view', $data);
    }

    public function update()
    {
        $userModel = model('UserModel');
        $userId = auth()->id(); // Get current user ID

        $userModel->update($userId, [
            'username' => $this->request->getPost('username'),
            'email' => $this->request->getPost('email'),
        ]);

        return redirect()->to('/profile')->with('success', 'Profile updated successfully.');
    }
}</code>
Code language: PHP (php)
 

1.2 Updating User Information

Updating user information involves handling form submissions and updating the user data in the database. The update() method in the Profile controller demonstrates how to achieve this.

2. Password Reset and Recovery

2.1 Implementing Password Reset Functionality

To implement password reset functionality, you need to create a reset request form and a reset form.

Password Reset Request Form (app/Views/password_reset_request.php):

 <code><!DOCTYPE html>
<html>
<head>
    <title>Password Reset Request</title>
</head>
<body>
    <h1>Request Password Reset</h1>
    <form action="<?= site_url('password/reset-request') ?>" method="post">
        <?= csrf_field() ?>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <input type="submit" value="Request Reset Link">
    </form>
</body>
</html></code>
Code language: PHP (php)

Password Reset Controller (app/Controllers/Password.php):

<code><?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Password extends Controller
{
    public function resetRequest()
    {
        $email = $this->request->getPost('email');
        $userModel = model('UserModel');
        $user = $userModel->where('email', $email)->first();

        if ($user) {
            // Send reset link via email (implement email sending)
            // For simplicity, we just log a message here
            log_message('info', 'Password reset link sent to ' . $email);
        }

        return redirect()->to('/')->with('message', 'If the email is registered, a reset link will be sent.');
    }
}
</code>
Code language: PHP (php)
 

Password Reset Form (app/Views/password_reset.php):

 <code><!DOCTYPE html>
<html>
<head>
    <title>Reset Password</title>
</head>
<body>
    <h1>Reset Password</h1>
    <form action="<?= site_url('password/reset') ?>" method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="token" value="<?= esc($token) ?>">
        
        <label for="new_password">New Password:</label>
        <input type="password" id="new_password" name="new_password" required>
        
        <input type="submit" value="Reset Password">
    </form>
</body>
</html></code>
Code language: HTML, XML (xml)

Password Reset Controller (app/Controllers/Password.php):

<code><?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Password extends Controller
{
    public function reset()
    {
        $token = $this->request->getPost('token');
        $newPassword = $this->request->getPost('new_password');
        $userModel = model('UserModel');

        // Validate token and reset password
        // For simplicity, token validation is skipped here
        $user = $userModel->where('reset_token', $token)->first();
        
        if ($user) {
            $userModel->update($user['id'], [
                'password' => password_hash($newPassword, PASSWORD_DEFAULT),
                'reset_token' => null // Clear reset token
            ]);

            return redirect()->to('/login')->with('success', 'Password reset successfully.');
        }

        return redirect()->to('/')->with('error', 'Invalid token.');
    }
}
</code>
Code language: PHP (php)
 

2.2 Handling Password Recovery Requests

Handle password recovery requests by creating forms for users to request a password reset link and to set a new password using the provided link.

3. Account Activation and Deactivation

3.1 Implementing Account Activation via Email

To implement account activation, generate an activation token and send it via email to the user.

Account Activation Controller (app/Controllers/Account.php):

<code><?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Account extends Controller
{
    public function activate($token)
    {
        $userModel = model('UserModel');
        $user = $userModel->where('activation_token', $token)->first();

        if ($user) {
            $userModel->update($user['id'], [
                'is_active' => true,
                'activation_token' => null // Clear activation token
            ]);

            return redirect()->to('/login')->with('success', 'Account activated successfully.');
        }

        return redirect()->to('/')->with('error', 'Invalid activation token.');
    }
}</code>
Code language: PHP (php)

3.2 Handling Account Deactivation

To handle account deactivation, update the user’s status in the database.

Account Deactivation Controller (app/Controllers/Account.php):

<code><?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Account extends Controller
{
    public function deactivate()
    {
        $userId = auth()->id(); // Get current user ID
        $userModel = model('UserModel');

        $userModel->update($userId, [
            'is_active' => false
        ]);

        return redirect()->to('/login')->with('success', 'Account deactivated. Please contact support to reactivate.');
    }
}
</code>
Code language: PHP (php)
 

Conclusion

With CodeIgniter 4 Shield, managing user profiles, handling password resets, and controlling account activation and deactivation are streamlined processes. By following the code examples provided, you can effectively implement these features and ensure robust user management in your application.

Feel free to customize the code to fit your specific requirements and enhance your application’s user management capabilities.

For more details and advanced configurations, refer to the CodeIgniter 4 Shield documentation.

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.