From 17a9759cf3cc50cc09a145089476873737f1ba55 Mon Sep 17 00:00:00 2001 From: Simon Backx Date: Fri, 5 Aug 2022 15:31:08 +0200 Subject: [PATCH] Fixed posting empty comments refs https://github.com/TryGhost/Team/issues/1750 - Trim whitespace from empty paragraphs - Do not allow empty comments - Also includes: Allow requesting the parent relationship of a comment (required for focusing comments) --- .../server/api/endpoints/comments-members.js | 2 +- ghost/core/core/server/models/comment.js | 21 ++++++++++++------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/ghost/core/core/server/api/endpoints/comments-members.js b/ghost/core/core/server/api/endpoints/comments-members.js index a66c0178d0..3caa843275 100644 --- a/ghost/core/core/server/api/endpoints/comments-members.js +++ b/ghost/core/core/server/api/endpoints/comments-members.js @@ -3,7 +3,7 @@ const tpl = require('@tryghost/tpl'); const errors = require('@tryghost/errors'); const models = require('../../models'); const commentsService = require('../../services/comments'); -const ALLOWED_INCLUDES = ['post', 'member', 'likes', 'replies']; +const ALLOWED_INCLUDES = ['post', 'member', 'likes', 'replies', 'parent']; const UNSAFE_ATTRS = ['status']; const messages = { diff --git a/ghost/core/core/server/models/comment.js b/ghost/core/core/server/models/comment.js index 64a0583cd5..738d7cde92 100644 --- a/ghost/core/core/server/models/comment.js +++ b/ghost/core/core/server/models/comment.js @@ -2,24 +2,22 @@ const ghostBookshelf = require('./base'); const _ = require('lodash'); const errors = require('@tryghost/errors'); const tpl = require('@tryghost/tpl'); +const {ValidationError} = require('@tryghost/errors'); const messages = { + emptyComment: 'The body of a comment cannot be empty', commentNotFound: 'Comment could not be found', notYourCommentToEdit: 'You may only edit your own comments', notYourCommentToDestroy: 'You may only delete your own comments' }; -function escapeRegex(string) { - return string.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); -} - /** * Remove empty paragraps from the start and end * + remove duplicate empty paragrapsh (only one empty line allowed) */ function trimParagraphs(str) { const paragraph = '

'; - const escapedParagraph = escapeRegex(paragraph); + const escapedParagraph = '

\\s*?

'; const startReg = new RegExp('^(' + escapedParagraph + ')+'); const endReg = new RegExp('(' + escapedParagraph + ')+$'); @@ -67,7 +65,7 @@ const Comment = ghostBookshelf.Model.extend({ if (this.hasChanged('html')) { const sanitizeHtml = require('sanitize-html'); - this.set('html', trimParagraphs( + const html = trimParagraphs( sanitizeHtml(this.get('html'), { allowedTags: ['p', 'br', 'a', 'blockquote'], allowedAttributes: { @@ -82,7 +80,16 @@ const Comment = ghostBookshelf.Model.extend({ }) } }) - )); + ).trim(); + + console.log(html); + + if (html.length === 0) { + throw new ValidationError({ + message: tpl(messages.emptyComment) + }); + } + this.set('html', html); } },