diff --git a/server/boot/story.js b/server/boot/story.js index 6c5bdea63a..8e00af3f16 100755 --- a/server/boot/story.js +++ b/server/boot/story.js @@ -2,15 +2,12 @@ var Rx = require('rx'), assign = require('object.assign'), sanitizeHtml = require('sanitize-html'), moment = require('moment'), - mongodb = require('mongodb'), debug = require('debug')('freecc:cntr:story'), utils = require('../utils'), observeMethod = require('../utils/rx').observeMethod, saveUser = require('../utils/rx').saveUser, saveInstance = require('../utils/rx').saveInstance, - MongoClient = mongodb.MongoClient, - validator = require('validator'), - secrets = require('../../config/secrets'); + validator = require('validator'); import { ifNoUser401, @@ -206,45 +203,54 @@ module.exports = function(app) { ); } - function getStories(req, res, next) { - MongoClient.connect(secrets.db, function(err, database) { - if (err) { - return next(err); + function getStories({ body: { search = '' } = {} }, res, next) { + if (!search || typeof search !== 'string') { + return res.sendStatus(404); + } + + const query = { + '$text': { + // protect against NoSQL injection + '$search': search.replace('$', '') } - database.collection('story').find({ - '$text': { - '$search': req.body.data ? req.body.data.searchValue : '' - } - }, { - headline: 1, - timePosted: 1, - link: 1, - description: 1, - rank: 1, - upVotes: 1, - author: 1, - image: 1, - storyLink: 1, - metaDescription: 1, + }; + + const fields = { + headline: 1, + timePosted: 1, + link: 1, + description: 1, + rank: 1, + upVotes: 1, + author: 1, + image: 1, + storyLink: 1, + metaDescription: 1, + textScore: { + $meta: 'textScore' + } + }; + + const options = { + sort: { textScore: { $meta: 'textScore' } - }, { - sort: { - textScore: { - $meta: 'textScore' - } - } - }).toArray(function(err, items) { + } + }; + + return app.dataSources.db.connector + .collection('story') + .find(query, fields, options) + .toArray(function(err, items) { if (err) { return next(err); } - if (items !== null && items.length !== 0) { + if (items && items.length !== 0) { return res.json(items); } return res.sendStatus(404); }); - }); } function upvote(req, res, next) { diff --git a/server/views/stories/news-nav.jade b/server/views/stories/news-nav.jade index 16631279c1..668e25952c 100644 --- a/server/views/stories/news-nav.jade +++ b/server/views/stories/news-nav.jade @@ -35,19 +35,14 @@ script. var getLinkedName = function getLinkedName(name) { return name.toLowerCase().replace(/\s/g, '-'); } - $.post('/stories/search', - { - data: { - searchValue: searchTerm - } - }) - .fail(function (xhr, textStatus, errorThrown) { + $.post('/stories/search', { search: searchTerm }) + .fail(function(xhr, textStatus, errorThrown) { $('#search-results').empty(); var div = document.createElement("div"); $(div).html("