0

当我从 ajax 发出请求作为响应时,我需要在用户未登录时发送 401(未授权)状态。

我正在使用带有 MVC 框架的 OOP 概念。所以我的构造函数如下

function __construct() {
        parent::__construct();

        $request = apache_request_headers();
        if(isset($request['X-Requested-With']) && $request['X-Requested-With'] == 'XMLHttpRequest')
        {
            $this->user = General::getUser(false);
        }
        else
        {
            $this->user = General::getUser();
        }
}

General::getUser();在我的另一个检查会话并返回登录用户信息的类中定义。

现在,当我发出 ajax 请求并且用户未登录时,我想发送 http 状态 401。但是我怎么能,因为我不能在构造中使用 return。

那么我需要遵循什么下一个程序来做到这一点。我想从中返回它,__construct因为我不希望我检查$this->user我的调用函数然后回显一些结果。

请建议并告诉我是否做错了什么。

4

2 回答 2

1

这将是最容易做到的

header("HTTP/1.1 401 Unauthorized");
exit;
于 2015-05-08T11:32:26.100 回答
1
class HomeController {
   function __construct() {
        parent::__construct();

        $request = apache_request_headers();
        if(isset($request['X-Requested-With']) && $request['X-Requested-With'] == 'XMLHttpRequest')
        {
            $this->user = General::getUser(false);
        }
        else
        {
            $this->user = General::getUser();
        }

        Authentication::authorize($this->user);
   }
}

class Authentication {
   public static function authorize($user) {
      if(! $user->isLoggedIn()) {
          Request::unauthorized();
      }

      return true;
   }
}

class Request {
   public static function unauthorized() {
       header("HTTP/1.1 401 Unauthorized");
       die();
   }
}

您还可以在 Request::unauthorized() 中呈现一些视图或执行重定向到身份验证页面。

于 2015-05-08T11:39:21.513 回答