9

我想检查用户是否登录。因此我有一个类女巫返回真或假。现在我想要一个检查用户是否登录的中间件。

$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');

这不行!

4

4 回答 4

10

你需要return回应。不要忘记requestandresponse对象是不可变的。

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

我有一个类似的身份验证中间件,我就是这样做的,它还添加了一个 403(未经授权)标头。

$uri = $request->getUri()->withPath($this->router->pathFor('home'));
return $response = $response->withRedirect($uri, 403);
于 2016-04-09T21:51:42.987 回答
3

根据 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);
于 2017-04-21T18:11:26.033 回答
0

制作基本Middleware并注入$container其中,以便您的所有中间件都可以扩展它。

Class Middleware
{
  protected $container;

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

  public function __get($property)
  {
    if (isset($this->container->{$property})) {
      return $this->container->{$property};
    }
    // error
  }
}

确保您的Auth中间件与基本中间件位于同一文件夹中,或者您可以使用命名空间。

class Auth extends Middleware
{
  public function __invoke($request, $response, $next)
  {
    if (!$this->account->login_check()) {
      return $response->withRedirect($this->router->pathFor('home'));
    }

    return $next($request, $response);
  }
}
于 2018-10-04T11:37:19.257 回答
-1

利用:

http_response_code(303);
header('Location: ' . $url);
exit;
于 2016-12-06T13:19:47.957 回答