From cd139f57678b98c82387d5b0034f653043b7165a Mon Sep 17 00:00:00 2001 From: Igor Minar Date: Wed, 2 Mar 2011 17:29:38 -0800 Subject: $xhr service now autodetects and strips )]}',\n ")]}\',\n" is a commonly used security prefix added to json http responses iat google and elsewhere in order to prevent certain cross-site attacks $xhr service now autodetects the prefix and strips it before deserializing the json. the implementation should be more flexible to allow for wider range of prefixes, but we need this one right now and can address other usecases later. --- src/service/xhr.js | 7 +++++-- test/service/xhrSpec.js | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/service/xhr.js b/src/service/xhr.js index 2f003398..6158b84f 100644 --- a/src/service/xhr.js +++ b/src/service/xhr.js @@ -79,8 +79,11 @@ angularServiceInject('$xhr', function($browser, $error, $log){ } $browser.xhr(method, url, post, function(code, response){ try { - if (isString(response) && /^\s*[\[\{]/.exec(response) && /[\}\]]\s*$/.exec(response)) { - response = fromJson(response, true); + if (isString(response)) { + if (response.match(/^\)\]\}',\n/)) response=response.substr(6); + if (/^\s*[\[\{]/.exec(response) && /[\}\]]\s*$/.exec(response)) { + response = fromJson(response, true); + } } if (code == 200) { callback(code, response); diff --git a/test/service/xhrSpec.js b/test/service/xhrSpec.js index 35861a92..fc51eff2 100644 --- a/test/service/xhrSpec.js +++ b/test/service/xhrSpec.js @@ -44,4 +44,43 @@ describe('$xhr', function() { expect($log.error).wasCalledWith("MyException"); }); + + + it('should automatically deserialize json objects', function() { + var response; + + $browserXhr.expectGET('/foo').respond('{"foo":"bar","baz":23}'); + $xhr('GET', '/foo', function(code, resp) { + response = resp; + }); + $browserXhr.flush(); + + expect(response).toEqual({foo:'bar', baz:23}); + }); + + + it('should automatically deserialize json arrays', function() { + var response; + + $browserXhr.expectGET('/foo').respond('[1, "abc", {"foo":"bar"}]'); + $xhr('GET', '/foo', function(code, resp) { + response = resp; + }); + $browserXhr.flush(); + + expect(response).toEqual([1, 'abc', {foo:'bar'}]); + }); + + + it('should automatically deserialize json with security prefix', function() { + var response; + + $browserXhr.expectGET('/foo').respond(')]}\',\n[1, "abc", {"foo":"bar"}]'); + $xhr('GET', '/foo', function(code, resp) { + response = resp; + }); + $browserXhr.flush(); + + expect(response).toEqual([1, 'abc', {foo:'bar'}]); + }); }); -- cgit v1.2.3