Slim post方法重定向不适用于苗条的中间件

时间:2016-08-15 20:12:07

标签: php httprequest slim

嘿伙计们,我对Slim Middleware有些问题。

我创建了一个中间件,用于检查用户是否使用Facebook登录并具有特定的电子邮件地址。所以现在当我使用PHPStorm RESTful Test工具调用url时,我应该无法将数据发布到服务器... 但是Redirect不起作用,所以我可以将数据发送到服务器。

/**
 * Admin Middleware
 *
 * Executed before /admin/ route
 */
$adminPageMiddleware = function ($request, $response, $next) {
    FBLoginCtrl::getInstance();
    $user = isset($_SESSION['user']) ? $_SESSION['user'] : new User();
    if (!($user->getEmail() == ADMIN_USER_EMAIL)) {
        $response = $response->withRedirect($this->router->pathFor('login'), 403);
    }
    $response = $next($request, $response);
    return $response;
};

/**
 * Milestone POST Method
 *
 * Create new Milestone
 */
$app->post('/admin/milestone', function (Request $request, Response     $response) use ($app) {
    $milestones = $request->getParsedBody();
    $milestones = isset($milestones[0]) ? $milestones :     array($milestones);
    foreach ($milestones as $milestone) {
        $ms = new Milestone();
        $msRepo = new MilestoneRepository($ms);
        $msRepo->setJsonData($milestone);
        if (!$msRepo->createMilestone()) {
            return $response->getBody()->write("Not Okay");
        };
    }
    return $response->getBody()->write("Okay");
})->add($adminPageMiddleware);

那么有人能给我一个暗示问题是什么吗? 我试图将相同的中间件添加到获取路由...它的工作原理:/奇怪的东西。

2 个答案:

答案 0 :(得分:1)

问题在于你的中间件逻辑。

if (!($user->getEmail() == ADMIN_USER_EMAIL)) {
    return $response->withRedirect($this->router->pathFor('login'), 403); //We do not want to continue execution
}
$response = $next($request, $response);
return $response;

答案 1 :(得分:0)

所以现在我最终得到了这段代码:

class AdminRouteMiddleware
{
    public function __invoke($request, $response, $next)
    {
        FBLoginCtrl::getInstance();
        $user = isset($_SESSION['user']) ? $_SESSION['user'] : new User();
        if (!($user->getEmail() == ADMIN_USER_EMAIL)) {
            if ($_SERVER['REQUEST_METHOD'] == "GET") {
                $response = $response->withRedirect('/login', 403);//want to use the route name instead of the url
            } else {
                $response->getBody()->write('{"error":Access Denied"}');
            }
        } else {
            $response = $next($request, $response);
        }
        return $response;
    }
}



/**
 * Milestone POST Method
 *
 * Create new Milestone
 */
$app->post('/admin/milestone', function (Request $request, Response     $response) use ($app) {
    $milestones = $request->getParsedBody();
    $milestones = isset($milestones[0]) ? $milestones :     array($milestones);
    foreach ($milestones as $milestone) {
        $ms = new Milestone();
        $msRepo = new MilestoneRepository($ms);
        $msRepo->setJsonData($milestone);
        if (!$msRepo->createMilestone()) {
            return $response->getBody()->write("Not Okay");
        };
    }
    return $response->getBody()->write("Okay");
})->add(new AdminRouteMiddleware());