Search code examples
phpajaxoopconstruct

How to set 401 status when user is not logged in?


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.


Solution

  • 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.