-
-
Save ev0k3r/6039031 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
| KK.factory('TokenHandler', ['$cookieStore', function ($cookieStore) { | |
| var tokenHandler = {}; | |
| tokenHandler.setToken = function (newToken) { | |
| $cookieStore.put("X-Authorization-Token", newToken); | |
| console.log('set token ' + newToken); | |
| }; | |
| tokenHandler.getToken = function () { | |
| console.log('get cookie ' + $cookieStore.get("X-Authorization-Token")); | |
| return $cookieStore.get("X-Authorization-Token"); | |
| }; | |
| // wraps given actions of a resource to send auth token | |
| // with every request | |
| tokenHandler.wrapActions = function (resource, actions) { | |
| // copy original resource | |
| var wrappedResource = resource; | |
| // loop through actions and actually wrap them | |
| for (var i = 0; i < actions.length; i++) { | |
| tokenWrapper(wrappedResource, actions[i]); | |
| }; | |
| // return modified copy of resource | |
| return wrappedResource; | |
| }; | |
| // wraps resource action to send request with auth token | |
| var tokenWrapper = function (resource, action) { | |
| // copy original action | |
| resource['_' + action] = resource[action]; | |
| // create new action wrapping the original | |
| // and sending token | |
| resource[action] = function (param, data, success, error) { | |
| var interceptSuccess = function(responseData, headers) { | |
| var token = headers('x-token'); | |
| if (token) { | |
| //update token | |
| tokenHandler.setToken(token); | |
| } | |
| if (angular.isFunction(success)) { | |
| success(responseData, headers); | |
| } | |
| }; | |
| return resource['_' + action]( | |
| angular.extend({}, param || {}, { 'Token': tokenHandler.getToken() }), | |
| data, | |
| interceptSuccess, | |
| error | |
| ); | |
| }; | |
| }; | |
| return tokenHandler; | |
| }]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment