4

我已正确安装Ion Auth并在我的服务器上运行。我还有默认的CodeIgniter 2 “新闻”教程在同一个 CI 安装中工作。我只是在玩弄并好奇使用身份验证系统“封闭”或保护整个应用程序的正确方法。

对于这个问题,让我们使用 CI 附带的“新闻”教程。

在我的控制器的index()函数中news.php,我添加了条件代码来检查用户是否已登录。如果没有,用户将被带到登录屏幕。

public function index() {
    $data['news'] = $this->news_model->get_news();
    $data['title'] = 'News archive';
    if ($this->ion_auth->logged_in()) {
        $this->load->view('templates/header', $data);
        $this->load->view('news/index', $data);
        $this->load->view('templates/footer');
    } else {
        redirect('auth/login', 'refresh');
    }
}

我可以看到这是可行的,但直接的缺点是控制器中的每个函数也必须使用类似的条件逻辑进行修改,以保护所有其他页面视图。例如 - 检查登录,显示页面,否则转到登录页面......一遍又一遍。

这是它应该做的方式吗?

如果一个应用程序已经构建并且正在运行,并且只是想保护它,该怎么办?添加条件逻辑来检查控制器中每个页面视图的登录状态似乎不必要地冗长。

是否可以在一个地方保护整个应用程序(所有视图)以最大限度地减少代码修改?如果是这样,怎么做?

4

3 回答 3

10

为了保护整个控制器,您可以将身份验证检查放入__construct()调用中,如 eric.itzhak 所述。

为了保护整个应用程序,您可以扩展 CI_Controller 类,将身份验证放在该文件的构造函数中,然后最后在每个控制器中通过 MY_Controller 而不是 CI_Controller 进行扩展。

代码示例:

/* File: application/core/MY_Controller.php */
class MY_Controller extends CI_Controller
{
    function __construct()
    {
        parent::__construct();

        if ( ! $this->ion_auth->logged_in())
        {
            redirect('auth/login');
        }
    }
}

然后,在每个控制器中(注意 MY_Controller,而不是 CI_Controller):

class Controller_name extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
    }

    // rest of controller methods
}

这些代码示例假设您正在自动加载(您也可以) ion auth 库。MY_Controller如果没有,请根据需要在文件中加载库。

这种方法有两个优点:

  1. 您只需在要保护的每个控制器中将 CI_Controller 更改为 MY_Controller。
  2. 如果您需要一个未受保护的控制器,即包含身份验证方法的控制器,您不必保护所有有用的东西(如果您的身份验证控制器要求您登录,您将无法登录:P -会有一个重定向循环)。
于 2012-11-30T02:23:19.500 回答
2

构造函数是要走的路。需要考虑的其他事情 - 如果您调用自己的方法而不是直接调用 Ion Auth,它将更加灵活。通常,登录过程的一部分是获取视图中显示的唯一值,或者用于跟踪会话等的 id。例如:在页面上显示用户名。

因此,将 ion auth 登录检查推送到模型,添加获取用户信息的方法或您需要的任何内容。如果每个方法不起作用,则返回 false。然后在你的构造函数中检查它是否被返回

function __construct() {
    parent::__construct();
 // load the model
 $this->load->model( 'customer_model' );

 // if logged in, return $this->customer, available to all methods in class
 if(! $this->customer = $this->customer_model->verifyLogin() ) 
 { redirect('auth/login', 'refresh'); }
 } 

 public function index()
 {
   // pass customer to data 
  $data['customer'] = $this->customer ;

 // $customer->name will now be available in view


 } 
于 2012-12-01T01:52:58.790 回答
1

我认为正确的逻辑是检查__construct方法内的用户状态,因为每次使用控制器时都会执行此操作。它不会保护整个 ci 应用程序,只是这个控制器中的方法,但我认为这对你的情况有用。

尝试这个 :

 public function __construct()
   {

        if (!$this->ion_auth->logged_in()) 
             redirect('auth/login', 'refresh');
   }
于 2012-11-29T23:09:27.047 回答