Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Commit

Permalink
fix(Angular.js): don't crash on invalid query parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
petebacondarwin committed Jun 20, 2013
1 parent a790813 commit 8264d08
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
25 changes: 22 additions & 3 deletions src/Angular.js
Original file line number Diff line number Diff line change
Expand Up @@ -821,17 +821,36 @@ function startingTag(element) {

/////////////////////////////////////////////////

/**
* Tries to decode the URI component without throwing an exception.
*
* @private
* @param str value potential URI component to check.
* @returns {boolean} True if `value` can be decoded
* with the decodeURIComponent function.
*/
function tryDecodeURIComponent(value) {
try {
return decodeURIComponent(value);
} catch(e) {
// Ignore any invalid uri component
}
}


/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue){
if (keyValue) {
if ( keyValue ) {
key_value = keyValue.split('=');
key = decodeURIComponent(key_value[0]);
obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
key = tryDecodeURIComponent(key_value[0]);
if ( isDefined(key) ) {
obj[key] = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
}
}
});
return obj;
Expand Down
6 changes: 6 additions & 0 deletions test/AngularSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,12 @@ describe('angular', function() {
expect(parseKeyValue('flag1&key=value&flag2')).
toEqual({flag1: true, key: 'value', flag2: true});
});
it('should ignore key values that are not valid URI components', function() {
expect(function() { parseKeyValue('%'); }).not.toThrow();
expect(parseKeyValue('%')).toEqual({});
expect(parseKeyValue('invalid=%')).toEqual({ invalid: undefined });
expect(parseKeyValue('invalid=%&valid=good')).toEqual({ invalid: undefined, valid: 'good' });
});
});

describe('toKeyValue', function() {
Expand Down

0 comments on commit 8264d08

Please sign in to comment.