Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between app calls to $http and Angular's requests for static resources in interceptor

With AngularJS interceptors, is it possible to differentiate my app calls to $http (direct either through $resource) from requests made by Angular itself for static resources, like views, without checking URLs?

I'm adding custom authorization header in HTTP interceptor like this:

transparentAuthServices.factory('authHttpInterceptor',
  function (localSessionStorage) {
    return {
      'request': function (config) {
        if (!config.ignoreAuthInterceptor && localSessionStorage.hasSession()) {
          var sessionId = localSessionStorage.getSession().sessionId;
          config.headers['Authorization'] = 'ARTAuth sessionId="' + sessionId + '"';
          return config;
        } else {
          return config;
        }
      }
    }
  };
});

It works fine but I don't need authorization for static resources and my server doesn't check them. I could check URLs and skip on those starting with '/app' (in my case) but I wonder is there an elegant solution?

like image 265
Tvaroh Avatar asked Nov 08 '13 22:11

Tvaroh


2 Answers

My experiments showed that in case of requests for templates, the config object has a cache property, and a call to config.cache.info() will return an object:

{id: "templates", size: 7}

This is probably the only reliable way to do it without inspecting the URL.

I also tried inspecting stack traces, but with no success - hard to find any reasonable pattern, and it certainly shouldn't be relied upon.

Still in my opinion the best way is to check the URL.

like image 123
Adam Avatar answered Sep 28 '22 06:09

Adam


A quick bit of inspection led me to hypothesize that template requests are made with an Accept header of text/html which lets you get round them quickly. Lots of plugins don't seem to obey that for loading templates but a few indexOf's on the url may clean that up for you. My example:

$httpProvider.interceptors.push(function () {
            return {
                request: function(config) {
                    if (config.url.indexOf('http') != 0
                        && config.headers.Accept !== 'text/html' /* Excludes template requests */
                        && config.url.indexOf('html') === -1 /* some plugins do requests with html */
                        && config.url.indexOf('tpl') === -1 /* match any template naming standards */) {
                        if (config.url.indexOf('/') == 0) {
                            config.url = apiEndpoint + config.url;
                        } else {
                            config.url = apiEndpoint + '/' + config.url;
                        }
                    }

                    return config;
                }
            }
        });
like image 42
Mark Jerzykowski Avatar answered Sep 28 '22 06:09

Mark Jerzykowski