0

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.

ajaykumartak
  • 776
  • 9
  • 29

2 Answers2

1

It will be easiest to do

header("HTTP/1.1 401 Unauthorized");
exit;
Plamen Ivanov
  • 101
  • 1
  • 5
  • I don't think there is another way to do this in the exact scenario you have. If you want it to happen in the construct I guess that is the only way. Not sure what framework you are using but you might want to use a middleware of some sort here. – Plamen Ivanov May 08 '15 at 11:40
  • Thanks alot for your response but i used approach suggested by @Mateusz Nowak so accepting his answer and vote up for your first and good answer. – ajaykumartak May 08 '15 at 11:51
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();
   }
}

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

Mateusz Nowak
  • 4,021
  • 2
  • 25
  • 37