0

I am new to Angular JS and Django. I am working on a project in which back end is implemented using Django framework. In this project multiple API's are there. Our front end is developed using Angular JS (Actually it is Angular JS Single page Application).I want to know that what would be the way to put a check condition that user is logged in or not before each API call.Because we want to reduce unecessary Api calling untill a user logged in. Currently , However we have implemented authentication mechanism in our back end part but we also want to implement some mechanism in front end so that untill a user logged in ,no request will pass to server.

We want that if user is not logged in, then no api should be called(i.e controller should not be loaded). But, as soon as a user logged in, api should be called without reloading the browser. The solution which I have tried I am providing in following section.please correct me because I know that surely I am doing something wrongly. In rsf function , I am confused what should be written inside if statement.

Please suggest some method. Thanks in advance.

myApp.config(function($routeProvider, $locationProvider) {
    var rsf = {
        // This function tells if user is logged or not
        "check": function($localStorage, $location) {
            if ($localStorage.user != null) {
                alert("You are logged in");
            } else {
                throw "Not logged in";
            }
        }
    };
    $routeProvider.when('/login', {
        templateUrl: 'vues/login.html',
        controller: 'neutreCtrl'
    }).when('/compte', {
        templateUrl: 'vues/compte.html',
        controller: 'compteCtrl',
        resolve: rsf
    }).otherwise({
        redirectTo: '/login'
    });
})
  • 1
    Possible duplicate of [AngularJS- Login and Authentication in each route and controller](https://stackoverflow.com/questions/20969835/angularjs-login-and-authentication-in-each-route-and-controller) – Ramesh Rajendran Aug 11 '17 at 06:51
  • Where I need to use $route.on(), inside if statement ???? – Rahul Choudhary Aug 11 '17 at 06:51
  • Check that link or check this : https://stackoverflow.com/questions/26993926/how-do-i-check-for-login-or-other-status-before-launching-a-route-in-angular-wit – Ramesh Rajendran Aug 11 '17 at 06:52
  • since you want to check on every api call what about this [http interceptor](http://onehungrymind.com/winning-http-interceptors-angularjs/), you can attach the authentication check to every http request. – Naren Murali Aug 11 '17 at 06:55
  • The duplicate question above contains answer which uses resolve https://stackoverflow.com/questions/20969835/angularjs-login-and-authentication-in-each-route-and-controller/29797145#29797145 – Vivz Aug 11 '17 at 06:55
  • Thanks @Ramesh this post seems quite helpful.But i want to know the service Auth is used here,what is the purpose of this service (Auth) here? – Rahul Choudhary Aug 11 '17 at 06:57

0 Answers0