From 9469f953d6ed9aadff736abd773f53c71a84ccf5 Mon Sep 17 00:00:00 2001 From: Mark Beamer Jr Date: Tue, 14 Aug 2018 20:58:53 -0400 Subject: [PATCH] added escape function to escape special characters for the query_string elastic search query. --- server/controllers/lighthouse.js | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/server/controllers/lighthouse.js b/server/controllers/lighthouse.js index c3f6d16..d015cf3 100644 --- a/server/controllers/lighthouse.js +++ b/server/controllers/lighthouse.js @@ -42,7 +42,7 @@ function getResults (input) { 'must': { 'query_string': { 'fields': ['channel'], - 'query' : input.channel, + 'query' : getEscapedQuery(input.channel), }, }, }, @@ -74,7 +74,7 @@ function getResults (input) { }; const conTermName = { // Contains search term - Name 'query_string': { - 'query' : '*' + input.s.trim() + '*', + 'query' : '*' + getEscapedQuery(input.s) + '*', 'fields': [ 'name', ], @@ -89,7 +89,7 @@ function getResults (input) { 'should': [ { // Contains search term in Author, Title, Description 'query_string': { - 'query' : '*' + input.s.trim() + '*', + 'query' : '*' + getEscapedQuery(input.s) + '*', 'fields': [ 'value.stream.metadata.author', 'value.stream.metadata.title', @@ -252,6 +252,28 @@ function getStatus () { }); } +function getEscapedQuery (query) { + let badCharacters = ['+', '-', '&&', '||', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '\\']; + let escapedQuery = ''; + for (var i = 0; i < query.length; i++) { + let char1 = query.charAt(i); + if (badCharacters.includes(char1)) { + escapedQuery = escapedQuery + '\\' + char1; + } else if (i + 1 <= query.length) { + let char2 = query.charAt(i + 1); + if (badCharacters.includes(char1 + char2)) { + escapedQuery = escapedQuery + '\\' + char1 + char2; + i++; + } else { + escapedQuery = escapedQuery + char1; + } + } else { + escapedQuery = escapedQuery + char1; + } + } + return escapedQuery; +} + class LighthouseControllers { /* eslint-disable no-param-reassign */ // Start syncing blocks...