Implementing User Authentication and Authorization in CodeIgniter

User authentication and authorization are crucial components of any web application. Implementing these features ensures that only authenticated users can access certain areas of the application and perform specific actions. In this article, we will explore how to implement user authentication and authorization in CodeIgniter, a popular PHP framework.

Setting up the Database

Before we dive into the implementation, we need to set up the necessary database tables to store user information. Create a table named users with columns such as id, username, password, and role. The role column will determine the user's level of authorization.

User Authentication

CodeIgniter provides a convenient library, called Session, to handle user authentication. Follow these steps to implement user authentication:

  1. Start by loading the Session library in your controller or autoload it in your config/autoload.php file: php $this->load->library('session');

  2. Create a login form in your view file to allow users to enter their credentials (e.g., username and password). Submitting this form will trigger the authentication process.

  3. In your controller, handle the form submission and verify the user's credentials against the database. You can do this by using a function like:

    public function login()
    {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
    
        // Verify credentials against the database
    
        if ($authenticated) {
            $user = $this->getUserByUsername($username); // Retrieve the user from the database
            $this->session->set_userdata('user', $user); // Save user data in session
            redirect('dashboard'); // Redirect to the dashboard or desired page
        } else {
            // Authentication failed, show an error message
        }
    }

    Note that you need to implement the getUserByUsername function to fetch user information from the database.

  4. Once the user is successfully authenticated, their data is stored in the session. You can then use the session data to determine whether the user is logged in or not.

    if ($this->session->userdata('user')) {
        // User is logged in
    } else {
        // User is not logged in
    }

With these steps, you have successfully implemented user authentication in CodeIgniter.

User Authorization

User authentication only verifies the user's identity, but it doesn't determine what actions they can perform within the application. User authorization, on the other hand, specifies the user's level of access and what they are allowed to do.

To implement user authorization in CodeIgniter, follow these steps:

  1. Extend the authentication implementation by adding the role column to the users table. This column will assign specific roles to each user.

  2. Define roles and their corresponding permissions in your application. For example, you might have roles like admin, moderator, and user, each with varying levels of access.

  3. Update the user session to include the user's role after successful authentication:

    $this->session->set_userdata('user', $user);
    $this->session->set_userdata('role', $user->role); // Save the user's role in session
  4. Create a middleware or use CodeIgniter's built-in functionality to check the user's role and authorize their access to specific pages or actions. For example, you can create a isAdmin middleware to only allow administrators to access certain routes.

    public function isAdmin()
    {
        $role = $this->session->userdata('role');
        
        if ($role !== 'admin') {
            // Redirect or show an error message
        }
    }
  5. Apply the middleware to your desired routes or controller methods to restrict access:

    class AdminController extends CI_Controller
    {
        public function __construct()
        {
            $this->load->library('session');
            $this->load->library('middleware');
            $this->middleware->isAdmin(); // Apply the `isAdmin` middleware to all methods
        }
        // ...
    }

By following these steps, you have implemented user authentication and authorization in CodeIgniter. Users can now securely log in and access specific areas of your application based on their assigned roles.

Remember to always secure user passwords by hashing and salting them before storing them in the database. Additionally, consider implementing additional security measures, such as CSRF protection, to further enhance your application's security.


noob to master © copyleft