我傾向於推出我自己的簡單認證庫。
首先,這是認證庫。它在會話中保留用戶ID令牌。在進行身份驗證時,會檢查是否存在此令牌。
應用程序/庫/ 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;
}
}
創建我自己的基本控制器和驗證那裏。爲方便起見,如果通過身份驗證,基本控制器將加載並存儲當前用戶。
應用/庫/ 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');
}
}
}
然後,在任何行動,我可以調用基控制器的認證功能。
class Items extends MY_Controller
{
function Items()
{
parent::MY_Controller();
}
function create()
{
// Do authentication
$this->do_auth();
// Continue with handling request
}
}
如果我喜歡我也可以保護整個控制器。
class Items extends MY_Controller
{
function Items()
{
parent::MY_Controller();
// Secure entire controller
$this->do_auth();
}
}
我將登錄和註銷操作置於用戶控制器中。在登錄操作中,我驗證用戶的憑據並登錄到用戶。
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');
}
}
謝謝你。我決定嘗試DX_Auth。它看起來非常全面和易於使用。 – Camsoft 2010-03-07 10:34:08