I am learning AngularJS by creating a small application.
I am storing user information in sessionStorage at the time of successful login.
LoginController.JS
app.controller("LoginCntrl", function ($scope, $location, angularService) {
$scope.Login = function () {
var UserName = $scope.UserName;
var Password = $scope.Password;
var getData = angularService.LoginInformation(UserName,Password);
getData.then(function (msg) {
if (msg.data == '') {
alert('no data');
} else {
sessionStorage.UserName = msg.dataUserName;
$location.path('/members');
}
}, function (error) {
alert('error in Login');
});
};
});
On successful login, I am redirecting the user to '/memberList' and in memberlistCntrl controller I am checking if sessionStorage is empty or not. If it is empty then I assume that user is trying to access the site without login and I am sending the user back to Login screen
Code in memberlistCntrl
app.controller("memberlistCntrl", function ($scope, $location, allMembers) {
if (sessionStorage.length == 0)
{
$location.path('/login');
return;
}
$scope.MembersList = allMembers.data;
$scope.createmember = function (path) {
$location.path(path);
};
});
My questions,
- Is it a right way to check if user is logged in or not?
- Is sessionStorage the right object to store the data in "Session" so that i can access it through out all my pages or site?
- Is there any better way to accomplish the same?