I recently developed a basic app that includes user authentication based on the guidelines found in this useful resource.
The core components of my app are a userAccountService, which manages communication with the server, and a login controller that oversees the login process.
In order to show or hide certain elements based on whether a user is logged in or not, I created a navController.
function navCtrl ($scope, $modal, userAccountService) {
$scope.IsUserLoggedIn = function () {
return userAccountService.isUserLoggedIn;
}
}
To implement this in HTML, I use ng-hide="isUserLoggedIn()
This is an excerpt from my userAccountService:
app.factory('userAccountService', ['$http', '$q', userAccountService]);
function userAccountService($http, $q) {
var service = {
registerUser: registerUser,
loginUser: loginUser,
logOut: logOut,
getValues: getValues,
isUserLoggedIn: false,
accessToken: ""
};
// Additional code omitted
function loginUser(userData) {
var tokenUrl = serverBaseUrl + "/Token";
if (!userData.grant_type) {
userData.grant_type = "password";
}
var deferred = $q.defer();
$http({
method: 'POST',
url: tokenUrl,
data: userData,
})
.success(function (data,status,headers,cfg) {
// Save access_token for API calls
accessToken = data.access_token;
isUserLoggedIn = true;
console.log(data);
deferred.resolve(data);
})
.error(function (err, status) {
console.log(err);
deferred.reject(status);
});
return deferred.promise;
}
}
If you're interested in learning more about managing user authentication in AngularJS apps, here's a great article I found helpful: link