Skip to content

Instantly share code, notes, and snippets.

@Anahkiasen
Created April 14, 2014 16:55
Show Gist options
  • Save Anahkiasen/10665081 to your computer and use it in GitHub Desktop.
Save Anahkiasen/10665081 to your computer and use it in GitHub Desktop.
angular.module('nobrow.interceptors').config(function ($provide, $httpProvider) {
$provide.factory('TokenHttpInterceptor',function ($http, $cacheFactory) {
var cache = $cacheFactory('nobrow');
return {
request: function (config) {
var token = cache.get('access_token');
if (token) {
config.headers.common.Authorization = 'Bearer '+token;
// Else request it and cache it
} else {
$http.post('/api/authentication/token', {
client_id : 'iosapp',
client_secret : 'tttttuuuuvvvvvv',
username : 'iosapp',
password : 'foobar',
grant_type : 'password',
}).success(function (response) {
cache.put('access_token', response.access_token);
config.headers.common.Authorization = 'Bearer '+response.access_token;
});
}
},
};
});
// Add the interceptor to the $httpProvider.
$httpProvider.interceptors.push('TokenHttpInterceptor');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment