Joel's Thoughts

Redirect Users To The Original Page After Login In AngularJs

July 04, 2016

So I have this scenario on my AngularJs application where:

  1. User needs to log-in to access a page.
  2. User will be redirected to the login page if not authenticated.
  3. Once user successfully logged-in, redirect him/her back to that original page.

I start by building the AngularJs config.


   'use strict';

    angular
      .module('myApp', [
        'ngCookies',        
        'ngRoute',
        'restangular'        
      ])
      .config(function ($routeProvider,RestangularProvider, $provide) {

        //this will store info for the referrer page
        $provide.decorator('$document',function($delegate){
            $delegate.referrer = null;
            $delegate.params = {};
            return $delegate; 
        });

        // Set the base URL for Restangular.
        RestangularProvider
                .setBaseUrl('/')
                .setDefaultHttpFields({withCredentials: true});

        //routes
        $routeProvider      
          .when('/restricted', {
            templateUrl: 'views/restricted.html',
            controller: 'RestrictedCtrl',             
            access: { requiredLogin: true }
          })         
          .when('/login', {
            templateUrl: 'views/login.html',
            controller: 'LoginCtrl',   
            access: { requiredLogin: false }
          })
          .otherwise({
            redirectTo: '/login',
            access: { requiredLogin: false }
          });

      }).run(function($rootScope, $location, $cookies, $document) {
          $rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {        
                if (nextRoute.access.requiredLogin && !$cookies.get('login')) {       

                    //store the referrer page for redirect after logged-in
                    $document.params = nextRoute.params; //store the parameters                       
                    $document.referrer = nextRoute.$$route.originalPath; //store the original url

                    //redirect user to the login page 
                    $location.path("/login");

                }
          });    
      });

As you see I’m using Restangular - an AngularJs service that simplifies common GET, POST, DELETE, and UPDATE requests. Inside my routes, you’ll notice that I have a route called “restricted”. Obviously, “restricted” is only for logged-in users as it’s “requiredLogin” property value is set to true.

It’s important to take note that I’m using $provide.decorator to modify the $document service. This provides access to the $delegate object which will store the needed info for the referrer page. Inside AngularJs’ run block, we create a “routeChangeStart” event listener. Every time a route is about to change due to unauthenticated user, the application automatically saves the referrer page’s url and parameters on the $document service.

Next step is to create a basic service for the login controller to use. I’ll call it UserService.


    'use strict';

    angular.module('myApp')
    .factory('UserService', function(Restangular,$cookies) {
        return {
            logIn: function(username, password, callback) {              
                if (username !== undefined && password !== undefined) {                             
                    Restangular.all('login').post({user: username, password: password}).then(function(result) {                  
                       //get, set users info or set cookie at this point
                       callback(result);                       
                    },function (result) { 
                        //perform callback if not successful                 
                        callback(result);
                    });                 
                }            
            }, 
            logOut: function() {
               //execute logout logic 
            }
        };
     });

Finally, we create the login controller using the UserService and $document service.


    'use strict';

    angular.module('myApp')
    .controller('LoginCtrl', function ($scope, UserService, $location, $document) {        
         $scope.logIn = function logIn(username, password) {
             //call the UserService login function            
             UserService.logIn(username, password, function(res){
                 if(res.status !== 401){
                   //start getting the referrer page info for redirect                 
                   var referrer = $document.referrer,
                   params = $document.params;

                   //set back referrer data to original values
                   $document.referrer = null;
                   $document.params = {};

                    //if there is a referrer page, redirect user to that page 
                   (referrer ? $location.path(referrer).search(params):$location.path("/"));                                   
                 }
                 else{
                     //execute our login error                  
                 }                
             });            
         };
   });









  • About
  • Search
  • Resume
  • Powered by Jekyll using the Trio theme