Login Api in php CI with authentication

First, create a controller called Auth.php in your CodeIgniter application’s controllers directory:

				
					<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('user_model'); // Load user model
    }

    public function login() {
        $email = $this->input->post('email');
        $password = $this->input->post('password');

        // Check if user exists
        $user = $this->user_model->get_by_email($email);
        if (!$user) {
            // User not found
            $this->output->set_status_header(401);
            $response = array('message' => 'Invalid email or password');
            $this->output->set_output(json_encode($response));
            return;
        }

        // Verify password
        if (!password_verify($password, $user->password)) {
            // Invalid password
            $this->output->set_status_header(401);
            $response = array('message' => 'Invalid email or password');
            $this->output->set_output(json_encode($response));
            return;
        }

        // Password is correct, create JWT token
        $payload = array(
            'user_id' => $user->id,
            'email' => $user->email,
        );
        $token = JWT::encode($payload, 'your_secret_key');

        // Return token in response
        $response = array('token' => $token);
        $this->output->set_output(json_encode($response));
    }
}

				
			
  1. In the above code, we’re first loading the user_model which we’ll use to check if the user exists and verify the password.

  2. Then, in the login function, we’re getting the email and password from the request body.

  3. We’re using the get_by_email function of the user_model to check if the user with the given email exists. If the user doesn’t exist, we’re returning a 401 Unauthorized status code with an error message.

  4. If the user exists, we’re verifying the password using password_verify function. If the password is incorrect, we’re returning a 401 status code with an error message.

  5. If the email and password are correct, we’re creating a JSON Web Token (JWT) using the JWT::encode function (assuming you have installed the firebase/php-jwt library via Composer). We’re encoding the user’s ID and email into the token’s payload.

  6. Finally, we’re returning the JWT token in the response body.

Note: You need to install Firebase JWT library. You can do this by running the following command via Composer:

				
					composer require firebase/php-jwt

				
			

Share:

Facebook
Twitter
Pinterest
LinkedIn

Leave a Reply

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