我倾向于推出我自己的简单认证库。
首先,这是认证库。它在会话中保留用户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