Last active
March 10, 2016 01:43
-
-
Save pragmaticlogic/a0f7d909b0516b400e5d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
'use strict'; | |
angular.module('app'). | |
factory('authService', ['$http', '$q', '$window', | |
function($http, $q, $window) { | |
const storage = $window.localStorage; | |
let cacheToken = {}; | |
return { | |
getAuthorizationHeader() { | |
if (cacheToken.access_token && cacheToken.expires_on > moment(new Date().getTime()).unix()) { | |
return $q.when({'Authorization': 'Bearer ' + cacheToken.access_token}); | |
} else { | |
cacheToken.access_token = storage.getItem('access_token'); | |
cacheToken.refresh_token = storage.getItem('refresh_token'); | |
cacheToken.expires_on = storage.getItem('expires_on'); | |
if (cacheToken.access_token && cacheToken.expires_on > moment(new Date().getTime()).unix()) { | |
return $q.when({'Authorization': 'Bearer ' + cacheToken.access_token}); | |
} else { | |
return $http.post('/refreshToken', {'token': cacheToken.refresh_token}).then( | |
response => { | |
const token = response.data; | |
cacheToken.access_token = token.access_token; | |
storage.setItem('access_token', cacheToken.access_token); | |
cacheToken.refresh_token = token.refresh_token; | |
storage.setItem('refresh_token', cacheToken.refresh_token); | |
cacheToken.expires_on = token.expires_on; | |
storage.setItem('expires_on', cacheToken.expires_on); | |
return {'Authorization': 'Bearer ' + cacheToken.access_token}; | |
}, | |
err => { | |
console.log('Error refreshing token ' + err) | |
} | |
); | |
} | |
} | |
} | |
} | |
} | |
]) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment