Here you go… should help you get going
First, extend Controller and use this as the parent class for all controllers that need security. Something like below would work - I would stick it in app/libraries - PHP5:
<?php if (!defined('BASEPATH')) exit('<h1>Forbidden</h1>');
class Admin_Controller extends Controller
{
const ACCESS_ID = 'admin_id';
const LOGIN_URL = 'login';
public function __construct ()
{
parent::Controller();
}
static function _authorizeAdmin ()
{
// IF not admin, redirect to login
if (!isset($_SESSION[self::ACCESS_ID]))
{
redirect(self::LOGIN_URL);
}
}
}
?>
Then create a controller to use it - something like the following - notice the calling of _authorizeAdmin() - if you call this in the constructor method of an inheriting controller, that controller will have security - the below example loads a model called admin_model and calls an authenticate method to process login - I didn’t include this in the post and you can write it yourself:
<?php
require_once(APPPATH . '/libraries/admin_controller.php');
class Index extends Admin_Controller
{
public function __construct ()
{
parent::__construct();
$this->load->model('admin_model');
}
public function index ()
{
self::_authorizeAdmin();
//load view
}
public function login ()
{
// IF logged in, logout and alert user
if (isset($_SESSION[self::ACCESS_ID]))
{
unset($_SESSION[self::ACCESS_ID]);
// user logged out
}
// IF POST, authenticate -> IF valid, set session and redirect :: ELSE, alert user
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$user = $this->admin_model->authenticate($_POST['username'], $_POST['password']);
if ($user)
{
$_SESSION[self::ACCESS_ID] = $user->id;
// redirect to secure page
}
else
{
// failed login attempt - maybe create a message for user
}
}
// load login view
}
public function logout ()
{
self::_authorizeAdmin();
// logout
unset($_SESSION[self::ACCESS_ID]);
// redirect to login
redirect(self::LOGIN_URL);
}
}
?>
Just to clarify, any controller that inherits from Admin_Controller can have security enabled like so:
<?php
require_once(APPPATH . '/libraries/admin_controller.php');
class Index extends Admin_Controller
{
public function __construct ()
{
parent::__construct();
// the below line acts as a gatekeeper
self::_authorizeAdmin();
}
}