MikeL
MikeL

Reputation: 208

Angularjs + Codeigniter user authentication

I have an app that has a full angularjs frontend with a codeigniter backend (with thishttps://github.com/philsturgeon/codeigniter-restserver)

I am using the codeigniter backend just to make api requests essentially.

The problem I am having now is managing a navigation view based on whether or not a user is logged in.

I have the navigation in its own navCtrl with a userService and loginCtrl.

I am storing loggedIn true or false in a cookie with a $watch on it in the navCtrl so it will update the navigations appropriately.

Any insight on why this may not be working? Any code i need to provide to clarify? Is there a "better" way to do this?

EDIT: The $watch is not actually catching when I update the value using the userService.

Thank you!

Upvotes: 2

Views: 6006

Answers (2)

VBMali
VBMali

Reputation: 1380

Checking sessions in Angularjs and CI using AJAX:

Javascript function called in angular js controllers:

 function check_session()
    {
        $.get(base_url+"admin/check_session/check", function(data, status){
             if(data=="1") /* error 1 => un-athorized user */
            {
                window.location.href=base_url+"login";
            }
            });
    }

Expaining AJAX request: check_session is CI controller and check is function in that.

Upvotes: 0

EnigmaRM
EnigmaRM

Reputation: 7632

We have a very similar setup as you. What we do is have Codeigniter send a HTTP Status code of 419 (not logged in) or something like that. And then you'll use Angular Interceptors to 'listen' for the response from the backend.

app.factory('loggedIn',function($q,$location){
    return {
        /*
         * Intercept all response errors & handle them
         */
        responseError: function(response) {
            if (response.status == 419) {
                console.error("You are not logged in");
                $location.path('/login');
            }
            return $q.reject(response);
        }
    };
});

Then push it to the $httpProvider:

app.config(['$httpProvider', function($httpProvider){
    $httpProvider.interceptors.push('loggedIn');
}]);

This should handle your front-end navigation pretty easily.

There are also other things that you can do for the $http requests before sending & before response is returned. Makes for a slick setup.

Upvotes: 3

Related Questions