Ajax check if you are logged in?

So, the site already works for me (I do not work from scratch). The problem is that most of the content is only available if you are logged in (almost all). So sometimes I have a modal popup that retrieves (using ajax) something displayed.

In my server code, if someone is not logged in, they are redirected to the login page.

This creates a strange effect, as if someone is on the page and is no longer logged in, and then the modal that appears tries to display the page on the page.

What are the possibilities for straightening?

The only thing I can think of is to have a URL that checks if they are logged in and returns this, and with each ajax request, I could check if they were logged in or not, and Javascript could act accordingly.

I hope for other possibilities.

+3
source share
1 answer

I decided it like that.

  • On the server side, the process authentication error depends on whether the request is ajax or not. In the first case - the answer 401 is "unauthenticated", in the second - redirection to the login page.
  • On the client side, register a generic jQuery ajax error handler to catch 401 errors and redirect the user to the login page.

    $.ajaxSetup({
        error: function(event, request, options, error) {
            switch (event.status) {
                case 401: common.setLocation('/sign-in'); break;
                ...
            }
        }
    });
    

, , , .

+5

Source: https://habr.com/ru/post/1759708/


All Articles