AngularJS - Checking if a user is authenticated and then routing them to the correct page AngularJS - Checking if a user is authenticated and then routing them to the correct page angularjs angularjs

AngularJS - Checking if a user is authenticated and then routing them to the correct page


There are two separate concerns that you are dealing with. The first, is to be able to determine if you are logged in. Assuming the user needs to be logged in for any state except the login state, you would implement it like so by listening for $stateChangeState events and verifying that the user is logged in:

login.run(function($state, authService) {    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {        var authToken = authService.isAuthed();        if (!authToken && toState !== 'login') {            //not logged in, so redirect to the login view instead of the view            //the user was attempting to load            event.preventDefault();            $state.go('login');        }     })});

This will put them on the login state if they haven't already logged in.

The second part is to redirect to the correct view after they login, which you would do in your login controller:

function LoginCtrl(user, $state) {    var self = this;    function handleRequest(res) {        self.responsedata = res;        self.message = res.data.message;        var authToken = res.data.auth_token;        localStorage.setItem('token', authToken);        //after successful login, redirect to dashboard        $state.go('dashboard');    }    self.login = function() {        this.requestdata = 'Starting request...';        user.login(self.username, self.pwd, self)                .then(handleRequest, handleRequest)    }}


ok I see you are using ui.router so let's work within this framework.

You want to

  1. check if a user is logged in
  2. redirect user to a view

What you're looking for is resolve:{loggedIn: checkLoggedInFn}

so your route for dashboard could be something like

.state('dashboard', { url: '/dashboard', templateUrl: 'dashboard/dashboard.html', resolve: {    loggedIn: function(){       //do your checking here    }  }})

what this does basically is that the controller will not instantiate until every resolve is resolved (so you can use a promise here for example), and then the value is passed into the controller as a parameter, so you could then do something like:

if(!loggedIn){   $state.go('login');}


You would handle the logic inside your login controller specifically here:

 self.login = function() {    this.requestdata = 'Starting request...';    user.login(self.username, self.pwd, self)      .then(handleRequest, handleRequest)  }

Inside the callback for the success on login, you would simple do a state change to send the user to the correct state.