Recently, I started learning angularJs and I am currently working on implementing login/logout functionality in my application.
In order to achieve this, I have created an AuthService that facilitates user login and a SessionService that stores the authentication token in local storage (I am using jwt).
This is how the AuthService looks like:
'use strict';
angular.module('App')
.factory('AuthService', ['ApiService', 'SessionService', '$q', '$timeout', 'jwtHelper', function (ApiService, SessionService, $q, $timeout, jwtHelper) {
// inherit
var service = Object.create(ApiService);
service.login = login;
service.logout = logout;
service.check = check;
service.user = user;
return service;
function login(credentials) {
return service.form('user.login', credentials)
.then(function success(response) {
SessionService.setToken(response.token);
return response;
});
}
function logout() {
// Implementing a promise for easier handling
// of logout in the controller
var d = $q.defer();
$timeout(function () {
SessionService.setToken();
d.resolve();
}, 0);
return d.promise;
}
function check() {
var token = SessionService.getToken();
return !!token && !jwtHelper.isTokenExpired(token);
}
function user() {
return service.call('user', {cache: true});
}
}]);
I'm experiencing an issue with the logout method. Since there is no server call involved, all I need to do is clear the local storage to log the user out. However, I prefer to handle this using a promise so that in the controller I can use the following approach:
function logout() {
AuthService.logout().then(function success() {
$state.go('login');
});
}
Do you think this is a good way to achieve the logout functionality?