I guess there are many ways to do this, let me explain what I'm doing, hope this is helpful. This will be a long post. I would like to hear how others do it, or it is better to use the same approach. You can also check out my project on Github, Angular-Django-Seed .
I use token authentication with Witold Szczerba http-auth-interceptor . The beauty of his approach is that whenever a request is sent from your site without the proper credentials, you are redirected to the login screen, but your request is queued for restarting when the login is completed.
Here is the login directive used with the login form. It goes to the endpoint of the Django authentication token, sets a cookie with a response token, sets a default token with a token so that all requests are authenticated, and fires an http-auth-interceptor login event.
.directive('login', function ($http, $cookieStore, authService) { return { restrict: 'A', link: function (scope, elem, attrs) { elem.bind('submit', function () { var user_data = { "username": scope.username, "password": scope.password, }; $http.post(constants.serverAddress + "api-token-auth", user_data, {"Authorization": ""}) .success(function(response) { $cookieStore.put('djangotoken', response.token); $http.defaults.headers.common['Authorization'] = 'Token ' + response.token; authService.loginConfirmed(); }); }); } }
})
I use the moduleโs .run method to set a cookie check, when a user comes to the site, if they have a set of cookies, I set the default authorization.
.run(function($rootScope) { $rootScope.$broadcast('event:initial-auth'); })
Here is my interceptor directive that handles authService translations. If a login is required, I hide everything and show the login form. Otherwise, hide the login form and show everything else.
.directive('authApplication', function ($cookieStore, $http) { return { restrict: 'A', link: function (scope, elem, attrs) { var login = elem.find('#login-holder'); var main = elem.find('#main'); scope.$on('event:auth-loginRequired', function () { main.hide(); login.slideDown('fast'); }); scope.$on('event:auth-loginConfirmed', function () { main.show(); login.slideUp('fast'); }); scope.$on('event:initial-auth', function () { if ($cookieStore.get('djangotoken')) { $http.defaults.headers.common['Authorization'] = 'Token ' + $cookieStore.get('djangotoken'); } else { login.slideDown('fast'); main.hide(); } }); } } })
To use it, all of my html were basically like that.
<body auth-application> <div id="login-holder"> ... login form </div> <div id="main"> ... ng-view, or the bulk of your html </div>