1

I'm new to AngularJS and I'm hitting the ground speeding at about 100mph. I'm trying to call a RESTful service from an angularjs site. The RESTful service uses an NH-HMAC authentication scheme. Part of the HMAC256 hash the service expects is a date formatted similar to Wed, 29 Jul 2015 15:00:00 GMT.

Since every request to the RESTful service expects this scheme, I am attempting to create a custom request transformer to add the hash to the request header. Where I'm stuck is I cannot inject the $filter service into the config adding the request transformer. I've tried creating a provider that returns a formatDate function in the $get result of the provider. However, when I try to call it, angular fails and tells me formatDate is not a function.

Below is the angularjs code I have so far. Does anyone have suggestions or examples of how to achieve this? Is there a better way or am I hosed?

Thanks

var myApp = angular.module('myApp', []);

myApp.provider('dateFormat', function() {    
    this.$get = ['$filter', function($filter) {
        return {
            formatDate: function(date) {
                return $filter('date')(date, "EEE, dd MMM yyyy HH:mm:ss 'GMT'");
            }
        }
    }]
});

myApp.config(['$httpProvider', 'dateFormatProvider', function ($httpProvider, dateFormatProvider) {    

// Add an HTTP interceptor which passes the request URL to the transformer
// Allows to include the URL into the signature
// Rejects request if no hmacSecret is available
$httpProvider.interceptors.push(function($q) {
    return {
        'request': function(config) {
            config.headers['X-URL'] = config.url;
            return config || $q.when(config);
        }
   };
});

// Add a custom request transformer to generate required headers
$httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
    var content = data ? data : '';
    var secret = 'secret-key-goes-here';
    var path = headersGetter()['X-URL'];
    var d1 = new Date();
    var dateStr = dateFormatProvider.formatDate(d1);
    var contentHash = CryptoJS.HmacMD5(content, secret);
    headersGetter()['Authorization'] = CryptoJS.HmacSHA256('GET-' +path +'-' +dateStr + '-' + contentHash, secret).toString(CryptoJS.enc.Base64);
    headersGetter()['X-URL'] = '';        

    return data;
});
}]);
Josh
  • 2,955
  • 1
  • 19
  • 28

0 Answers0