I tend to roll my own simple authentication library.
Firstly, this is the authentication library. It keeps a user ID token in the session. When authenticating it checks for the existence of this token.
application/libraries/Auth.php
class Auth
{
var $ci;
var $user_id;
function Auth()
{
// Get CodeIgniter instance
$this->ci = get_instance();
// Fetch token from the session
$this->user_id = $this->ci->session->userdata('user_id');
}
function check()
{
return $this->user_id != null;
}
function login($user_id)
{
// Set token in the session
$this->ci->session->set_userdata('user_id', $user_id);
$this->user_id = $user_id;
}
function logout()
{
// Remove token from the session
$this->ci->session->unset_userdata('user_id');
$this->user_id = null;
}
}
I create my own base controller and authenticate there. For convenience, if authenticated, the base controller loads and stores the current user.
application/libraries/MY_Controller.php
class MY_Controller extends Controller
{
var $user;
function MY_Controller()
{
parent::Controller();
}
function do_auth()
{
if ($this->auth->check())
{
// Authenticated. Fetch current user
$this->user = $this->user_model->get_user($this->auth->user_id);
}
else
{
// Not authenticated. Redirect to login page
redirect('users/login');
}
}
}
Then in any action I can call the authentication function of the base controller.
class Items extends MY_Controller
{
function Items()
{
parent::MY_Controller();
}
function create()
{
// Do authentication
$this->do_auth();
// Continue with handling request
}
}
If I like I can also secure an entire controller.
class Items extends MY_Controller
{
function Items()
{
parent::MY_Controller();
// Secure entire controller
$this->do_auth();
}
}
I place the login and logout actions in a users controller. In the login action I verify the user's credentials and log in the user.
class Users extends MY_Controller
{
function Users()
{
parent::MY_Controller();
}
function login()
{
// Verify form input
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run())
{
// Fetch the user based on credentials supplied
$user = $this->user_model->get_user_by_credentials($this->input->post('username', true), $this->input->post('password', true));
if ($user != null)
{
// Credentials verified. Log the user in.
$this->auth->login($user->user_id);
redirect('');
}
else
{
// Login failed. Show the login page.
$this->load->view('users/login', array('login_failed' => true));
}
}
else
{
// Yet to authenticate. Show the login page.
$this->load->view('users/login', array('login_failed' => false));
}
}
function logout()
{
$this->auth->logout();
redirect('users/login');
}
}