我正在这样做;
示例核心/MY_CONTROLLER.php
private $action_user=null;
public function __construct()
{
parent::__construct();
##listen for post attempts;
$this->validate();
##set action_user; return null if no session else return user object
$this->action_user = $this->session->userdata('loged_user');
##extra check step
if($this->user->pwd_has_changed($this->action_user)){
$this->session->sess_destroy();
alerts('error','the password you used to login has changed ! please relogin');
return $this->failed_login();
}
}
public function alerts(){return die(json_encode(alerts()));}#a helper function.. just ignore it for this example
public function logout(){$this->session->sess_destroy();redirect();}
#AUTH
private function failed_login(){
//$callers=debug_backtrace();
alerts('warning','failed login');//.' '.$callers[1]['function']);
ob_clean();//clear flush just to make sure !
if($this->input->is_ajax_request())$this->load->view('base/ajax/landing');
else $this->load->view('base/landing');
die($this->output->get_output());//kill request and load landing in same uri. this in case he attempt login again he will be at same url; also helps with partials views
}
private function success_login(){
unset($_POST['login'],$_POST['password']);
alerts('success','welcome '.$this->action_user->login);
//nothin much to do.. just dont die
}
private function validate(){
//listen to posts if so logout and relog in
if( !$this->input->post('login') || !$this->input->post('password'))return FALSE;
$this->session->sess_destroy();#destroy session
#1. validation
$this->form_validation->set_rules('login', 'User Login', 'required|min_length[4]|max_length[12]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]|max_length[12]|xss_clean');
#1.2 Failed validation
if( ! $this->form_validation->run() )return alerts('error',$this->form_validation->error_string(),false);#set message and return false
#2. Login
$this->user->login(set_value('login'),set_value('password'));
//i dont want it to return anything ! $this->user->login should set messages of success OR fail + set user session
}
public function auth($role = null){
if(!isset($this->action_user->id))
return alerts('error',"this is a users restricted area",$this->failed_login());
//ACCESS LEVELS CONDITIONS
if($this->user->in_group($this->action_user->id,$role))return $this->success_login();
return alerts('error',"this is a {$role} restricted area",$this->failed_login());
}
#END AUTH
现在在我的控制器构造函数中;因为首先调用 MY_CONTROLLER 构造函数;所以我应该 hv 检索 $action_user 对象;或者已经尝试让他登录。
如果我想限制一个页面,我只需添加
$this->auth();
//or $this->auth('admin');
到它的构造函数,如果用户不被允许,页面将会死掉并向他发送我的视图页面而不重定向;
我使用这种方法的原因是让用户能够从任何控制器登录、注销;如果他访问http://localhost/RANDOMECONTROLLER/logout
,他仍然会注销..登录也是如此。
有时当我通过 ajax 获取页面部分时,它也很有帮助;它只会使用登录表单将登录页面返回到此 div 中。
例子
统计页面有 4 个小部件,其中 1 个只能由管理员查看;然后当 ajax fitch 4 小部件时,它会显示 3 和一个带有登录表单的 div,说你需要成为管理员才能登录..
...
所以你认为这是一个很好的方法吗?还是虫子山墙意大利面* * ?