2013-06-12 21 views
0

我的問題是有點難以解釋,但我會嘗試..保持坦克驗證每一頁上的笨

基本上,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); 
    } 

如果您有登錄頁面,並且用戶每次都從頭開始,那麼這非常棒。 (我很喜歡這樣做)

但我希望用戶能夠跳轉到(幾乎)任何控制器的網站,並有一個登錄欄穿越頂部。登錄時,不應將其重定向到其他頁面。他們應該在他們試圖訪問的同一頁面上結束。

例如,我的用戶可能會直接加載example.com/food/burgers。我想要一個空白頁面出現,但只是在頂部有一個登錄欄。然後,當他們登錄時,他們最終回到'漢堡'頁面,但這次還有一個漢堡包列表和頂部的酒吧,告訴他們他們已登錄,並可選擇註銷。

那麼我該如何做到這一點?我需要從每個控制器調用auth/login方法嗎?我是否將其作爲「包含」來做?不知道。

+0

更簡單的方法是讓用戶在成功登錄後將其轉到'/ auth/login'並保存當前的瀏覽網址,例如'example.com/food/burgers ')。如果你喜歡這種方式,我會幫你通過它。 – Kyslik

回答

6

首先,您需要創建一個基礎控制器,您的所有控制器都將從其中擴展而來。您將在此基本控制器中檢查身份驗證。如果他們沒有登錄,則將入口點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'); 
     } 
    } 
} 

你主控制器將延長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); 
    } 
} 

您的驗證控制器不會擴展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 
    } 
} 

而不是使用會話存儲重定向URI的,你也可以一起把它作爲一個GET參數。

+0

我曾經看到過MY_Controller,但並不知道太多。 – mikelovelyuk

+0

非常好的答案,恭喜 –