Utilizing the power of HTML5 sessionStorage, I was able to devise an effective solution. Take a look at this straightforward illustration:
// Initializing the main module
var myapp = angular.module('myapp', []);
// Defining actions to be executed when running the application
myapp.run(['$location', '$rootScope',
function($location, $rootScope) {
// Setting up a listener to monitor route changes. This ensures that a user is logged in before accessing data.
$rootScope.$on("$routeChangeStart", function(event, next, current) {
// Checking if there is no token, indicating that the user is not logged in
if (sessionStorage.getItem("token") === null) {
// Redirecting to the login page
window.location.href = "login.html";
}
});
}]);
// Creating a controller for the login page
myapp.controller('LoginController', ['$scope', '$http',
function($scope, $http) {
// Automatically filling in email/password fields if user had selected "remember me"
// Login functionality triggered upon form submission
$scope.login = function() {
// Authenticating the user by sending a POST request to the server. Upon successful authentication, a token is received.
$http.post('http://example.com/login', $scope.user)
.success(function(response) {
// Storing the token in sessionStorage under the key "token"
sessionStorage.setItem("token", response.token);
// Redirecting to the desired location
window.location = 'index.html';
});
};
}]);