2016-04-09 75 views
6

我想檢查用戶是否登錄。因此,我有一個Class類,返回true或false。現在我想一箇中間件,如果用戶登錄,檢查。Slim 3中間件重定向

$app->get('/login', '\Controller\AccountController:loginGet')->add(Auth::class)->setName('login'); 
$app->post('/login', '\Controller\AccountController:loginPost')->add(Auth::class); 

驗證類

class Auth { 
    protected $ci; 
    private $account; 

    //Constructor 
    public function __construct(ContainerInterface $ci) { 
     $this->ci = $ci; 
     $this->account = new \Account($this->ci); 
    } 

    public function __invoke($request, \Slim\Http\Response $response, $next) { 
     if($this->account->login_check()) { 
      $response = $next($request, $response); 
      return $response; 
     } else { 
      //Redirect to Homepage 
     } 

    } 
} 

因此,當用戶在頁面登錄將呈現正確。但是當用戶沒有被自動識別時,我想重定向到主頁。但是怎麼樣?!

$response->withRedirect($router->pathFor('home'); 

這不行!

回答

9

您需要return的迴應。不要忘記requestresponse對象是不可變的。

return $response = $response->withRedirect(...); 

我有一個類似的認證中間件,這是我如何做,它也增加了一個403(未經授權)的頭。

$uri = $request->getUri()->withPath($this->router->pathFor('home')); 
return $response = $response->withRedirect($uri, 403); 
+1

該解決方案是行不通的 – Vashtamyty

+0

從中間件中提供的代碼,這是行不通的。 – systemovich

+0

在OP的情況下,他們沒有在使用它之前定義'$ router'變量。假設你的中間件沒有從另一個類繼承,你在哪裏定義'$ this-> router'? –

-2

用途:

http_response_code(303); 
header('Location: ' . $url); 
exit; 
+1

請嘗試解釋您的答案,而不是僅僅發佈代碼。 –

+0

@NahuelIanni,如果你知道PHP是不言自明的。 – systemovich

+2

儘管我確信這可能有效,但OP可能正在尋找一種使用Slim Framework功能的解決方案,而不是普通的PHP。 –

1

大廈關閉tflight的答案,你需要做以下,使一切工作按預期。我試圖將其作爲修訂提交,因爲tflight的答案中提供的代碼不適用框外開箱即用的框架,但已被拒絕,因此在單獨的答案中提供:

您需要以下除了你的中間件:

protected $router; 

public function __construct($router) 
{ 
    $this->router = $router; 
} 

此外,聲明中間件時,你將需要添加以下的構造:

$app->getContainer()->get('router') 

類似的東西來:

$app->add(new YourMiddleware($app->getContainer()->get('router'))); 

如果沒有這些更改,解決方案將無法正常工作,並且會顯示$ this-> router不存在的錯誤。

這些變化的地方,你可以利用,然後通過tflight

$uri = $request->getUri()->withPath($this->router->pathFor('home')); 
return $response = $response->withRedirect($uri, 403);