dongsheng6056 2015-05-08 11:24
浏览 452
已采纳

用户未登录时如何设置401状态?

When i make a request from ajax in response i need to send 401 (Not Authorized) status when user is not logged in.

I am using OOP Concepts with MVC Framework. So my construct function is following

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(); is defined in my another class that check session and return login-ed user info.

Now when i make a ajax request and user is not logged in i want to send http status 401. But how i can as i can't use return in construct.

So what next procedure i need to follow to do this. I want to return it from __construct because i dont want that i check $this->user in my calling function and then echo some result.

Please suggest and tell if i am doing something wrong.

  • 写回答

2条回答 默认 最新

  • duanli9930 2015-05-08 11:39
    关注
    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();
       }
    }
    

    You can also render some view inside Request::unauthorized() or perfom redirect to authentication page.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面