I am working on angular project. When I login to application, I am saving access_token received from the login service in to $cookies. This access_token gets expires after 2 mins. After login, for subsequest functionality, I have to send this access_token to the service using $http to get valid response. Once this access_token gets expires after 2 mins, I am calling to a service which will regenerate access_token and again saving in $cookies. Without access_token, my other functionalities won't work.
Basically I need to check if access token present in $cookies or not before every service call in the application. If access token is not present, then Need to regenerate it with another service call using $http and save it back in cookies and then the desire service call of the functionality. and If access token present then do the desire service call.
my one of functionality is :
mPosController.controller('offerController', ['$scope', '$route', '$cookies', '$rootScope', 'mosServiceFactory', 'ngDialog', '$modal', '$q', function ($scope, $route, $cookies, $rootScope, mosServiceFactory, ngDialog, $modal, $q) {
mosServiceFactory.viewAllOffers('page=0').then(function (data) {
//Do the desire functionality
});
}]);
My services are :
mPosServices.factory('mosServiceFactory', function ($http, $rootScope, $cookies,$q) {
return{
viewAllOffers: function (page) {
var allOffers = $http({
method: "get",
url: "myserviceurl?enrollmentId=" + $rootScope.enrollMentId + "&" + page + "&size=10&access_token=" + $cookies.get('access_token'),
});
return allOffers;
},
refresh_token: function () {
var refreshToken = $http({
method: "get",
url: "myserviceurl/oauth/token?grant_type=refresh_token&client_id=restapp&client_secret=restapp&refresh_token=" + $cookies.get('refresh_token'),
})
return refreshToken;
},
}
});
So before calling viewAllOffers(), I need to check if access_token is present in $cookies or not if not thencall refresh_token service.
How do I achieve this generically?