mik*_*yuk 0 authentication codeigniter
我的问题有点难以解释,但我会试试..
基本上,在tank_auth示例脚本中,如果用户尚未登录,则会使用此代码重定向用户;
if (!$this->tank_auth->is_logged_in()) {
redirect('/auth/login/');
} else {
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->load->view('welcome', $data);
}
Run Code Online (Sandbox Code Playgroud)
如果你有一个登录页面,并且用户每次都在开头就开始,那就太好了.(而且我这样做很舒服)
但是我希望用户能够(几乎)跳到任何控制器的网站,并在顶部有一个登录栏.登录时,不应将其重定向到其他页面.他们应该在他们试图访问的同一页面上结束.
例如,我的用户可能会立即加载example.com/food/burgers.我想要一个空白页面,但只是顶部有一个登录栏.然后,当他们登录时,他们最终回到'汉堡'页面,但这次还有一个汉堡包列表和顶部的栏,告诉他们他们已登录,并可选择注销.
那我该怎么做?我是否需要从每个控制器调用auth/login方法?我是否将其作为"包含"?不知道.
首先,您需要创建一个所有控制器都将扩展的基本控制器.您将检查此基本控制器中的身份验证.如果他们未登录,则将入口点uri保存在cookie中并重定向到登录页面.
// application/core/My_Controller.php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->model('tank_auth');
if (!$this->tank_auth->is_logged_in()) {
// save the visitors entry point and redirect to login
$this->session->set_userdata('redirect', $this->uri->uri_string());
redirect('auth/login');
}
}
}
Run Code Online (Sandbox Code Playgroud)
您的主控制器将扩展MY_Controller,不需要担心身份验证.
class Welcome extends MY_Controller
{
public function index()
{
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->load->view('welcome', $data);
}
}
Run Code Online (Sandbox Code Playgroud)
您的身份验证控制器不会扩展MY_Controller,否则它将陷入重定向循环.
class Auth extends CI_Controller
{
public function login()
{
$this->load->library('session');
if (auth_success) {
// redirect the user back to the entry point or the welcome controller
if ($uri = $this->session->userdata('redirect')) {
redirect($uri);
} else {
redirect('welcome');
}
}
// handle authentication failure
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以将其作为GET参数传递,而不是使用会话来存储重定向uri .
| 归档时间: |
|
| 查看次数: |
3006 次 |
| 最近记录: |