First, create a controller called Auth.php
in your CodeIgniter application’s controllers
directory:
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));
}
}
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.Then, in the
login
function, we’re getting the email and password from the request body.We’re using the
get_by_email
function of theuser_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.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.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.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