Authentication.js

angular.module('homepage').
factory('Authentication', function($http, $localStorage, $rootScope) {
    var _user = {};

    function urlBase64Decode(str) {
        var output = str.replace('-', '+').replace('_', '/');
        switch (output.length % 4) {
            case 0:
                break;
            case 2:
                output += '==';
                break;
            case 3:
                output += '=';
                break;
            default:
                throw 'Illegal base64url string!';
        }
        return window.atob(output);
    }

    function getUserFromLocalStorage() {
        var token = $localStorage.token;
        var user = {};
        if (typeof token !== 'undefined') {
            var encoded = token.split('.')[1];
            user = JSON.parse(urlBase64Decode(encoded));
        }
        return user;
    }

    function removeUserFromLocalStorage() {
        delete $localStorage.token;
    }

    function getUser() {
        _user = getUserFromLocalStorage();
        return _user;
    }

    function setUser(token) {
        if(token) {
            $localStorage.token = token;
            $rootScope.userDtls = getUser();
            $rootScope.isAuthenticated = true;
        }
    }

    function removeUser() {
        removeUserFromLocalStorage();
        $rootScope.userDtls = {};
        $rootScope.isAuthenticated = false;
        _user = {};
    }

    function isAuthenticated() {
        return $rootScope.userDtls && $rootScope.userDtls.username !== undefined ? true : false;
    }

    function setHeaders() {
        // Set the token as header for your requests!
        $http.defaults.headers.common['X-Auth-Token'] = $localStorage.token;
    }

    return {
        getUser: getUser,
        setUser: setUser,
        removeUser: removeUser,
        isAuthenticated: isAuthenticated,
        setHeaders: setHeaders
    };
});