Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Various updates to get it working #92

Open
wants to merge 40 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 37 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
9d56055
initial attempt
theaustinhowe Jan 5, 2022
4fbd241
Fix library
theaustinhowe Jan 5, 2022
3ea1a54
Update library.js
theaustinhowe Jan 5, 2022
3cdd4ad
Tweak approach
theaustinhowe Jan 5, 2022
57913cb
Tweak
theaustinhowe Jan 5, 2022
9bcf7d2
More testing.
theaustinhowe Jan 5, 2022
8faa283
More logging
theaustinhowe Jan 5, 2022
d139a21
Flip out
theaustinhowe Jan 5, 2022
9824f8b
Tweak
theaustinhowe Jan 5, 2022
10ee330
Oops
theaustinhowe Jan 5, 2022
1b5b717
Move
theaustinhowe Jan 5, 2022
e38d558
Fix template
theaustinhowe Jan 5, 2022
e125080
Fix template issue
theaustinhowe Jan 5, 2022
364beb9
Logging
theaustinhowe Jan 5, 2022
66871b6
Remove log
theaustinhowe Jan 5, 2022
6429592
Test pagination
theaustinhowe Jan 5, 2022
e076fe1
Tweak test
theaustinhowe Jan 5, 2022
5e143c9
Tweak
theaustinhowe Jan 5, 2022
3302ccf
Update behavior for parsing templates
theaustinhowe Jan 5, 2022
a6fcf04
Support hiding branding.
theaustinhowe Jan 5, 2022
3ca27ca
Revert pagination tests
theaustinhowe Jan 5, 2022
0247d82
Tweak approach to redirect_url
theaustinhowe Jan 11, 2022
0ce895a
Plugins support and 302 redirect follows
theaustinhowe Jan 11, 2022
c082d78
Minify and cleanup general file
theaustinhowe Jan 12, 2022
01a9961
eslint clean
theaustinhowe Jan 12, 2022
485221c
show_branding default on (persist existing behavior)
theaustinhowe Jan 12, 2022
4a82ec6
New settings for authorization URLs and method of authorization
theaustinhowe Jan 12, 2022
af0fd4c
Fix data check.
theaustinhowe Jan 12, 2022
92f00ec
Support auto-creating topics
theaustinhowe Jan 12, 2022
449aeb4
Don't show if no mainPost content. This occurs when a topic is purged
theaustinhowe Jan 12, 2022
ea2ecec
Merge pull request #1 from SoundryHealth/support-template-no-topic
theaustinhowe Jan 12, 2022
ce84241
Update package and yarn files
theaustinhowe Jan 12, 2022
70fc232
Support turning profile links off
theaustinhowe Jan 12, 2022
626f753
Merge pull request #2 from SoundryHealth/support-template-no-topic
theaustinhowe Jan 12, 2022
34870c7
Tweak approach
theaustinhowe Jan 12, 2022
2f59b2e
Resilience
theaustinhowe Jan 12, 2022
20e2e81
Tweak version
theaustinhowe Jan 12, 2022
45356e4
Merge pull request #3 from SoundryHealth/support-template-no-topic
theaustinhowe Jan 12, 2022
484f99c
Fix error display
theaustinhowe Jan 14, 2022
30c1d1f
Merge branch 'master' into support-template-no-topic
theaustinhowe Jan 14, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 71 additions & 45 deletions library.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,47 @@ const groups = require.main.require('./src/groups');

const Comments = module.exports;

// CORS Middleware
const CORSMiddleware = function (req, res, next) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a comment explaining what the purpose of this is.

const hostUrls = (meta.config['blog-comments:url'] || '').split(',');
const url = hostUrls.find((hostUrl) => {
hostUrl = hostUrl.trim();
if (hostUrl[hostUrl.length - 1] === '/') {
hostUrl = hostUrl.substring(0, hostUrl.length - 1);
}

return (hostUrl === req.get('origin'));
});

if (url) {
res.header('Access-Control-Allow-Origin', req.get('origin'));
} else {
winston.warn(`[nodebb-plugin-blog-comments] Origin (${req.get('origin')}) does not match hostUrls: ${hostUrls.join(', ')}`);
}

res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
res.header('Access-Control-Allow-Credentials', 'true');

next();
};

Comments.init = async function (params) {
const { router, middleware } = params;
const routeHelpers = require.main.require('./src/routes/helpers');

Comments.template = await fs.promises.readFile(path.resolve(__dirname, './public/templates/comments/comments.tpl'), { encoding: 'utf-8' });

router.get('/comments/get/:id/:pagination?', middleware.applyCSRF, routeHelpers.tryRoute(Comments.getCommentData));
router.post('/comments/reply', middleware.applyCSRF, routeHelpers.tryRoute(Comments.replyToComment));
router.post('/comments/publish', middleware.applyCSRF, routeHelpers.tryRoute(Comments.publishArticle));
const middlewares = [
CORSMiddleware,
middleware.applyCSRF,
];

router.get('/comments/get/:id/:pagination?', middlewares, middleware.pluginHooks, routeHelpers.tryRoute(Comments.getCommentData));
router.post('/comments/reply', middlewares, routeHelpers.tryRoute(Comments.replyToComment));
router.post('/comments/publish', middlewares, routeHelpers.tryRoute(Comments.publishArticle));

routeHelpers.setupAdminPageRoute(router, '/admin/blog-comments', middleware, [], (req, res) => {
routeHelpers.setupAdminPageRoute(router, '/admin/blog-comments', middleware, [], (_, res) => {
res.render('comments/admin', {});
});
};
Expand All @@ -35,49 +65,31 @@ Comments.getTopicIDByCommentID = async function (commentID) {
return await db.getObjectField('blog-comments', commentID);
};

Comments.getCommentData = async function (req, res, next) {
Comments.getCommentData = async function (req, res) {
const commentID = req.params.id;
const pagination = req.params.pagination ? req.params.pagination : 0;

const tid = await Comments.getTopicIDByCommentID(commentID);
const topicData = await topics.getTopicData(tid);
if (!topicData) {
return next();
}

const start = pagination * 10;
const stop = start + 9;
const [postData, userData, isAdmin, isPublisher, categoryData, mainPost] = await Promise.all([
topics.getTopicPosts(topicData, `tid:${tid}:posts`, start, stop, req.uid, true),
const [userData, isAdmin, isPublisher] = await Promise.all([
user.getUserData(req.uid),
user.isAdministrator(req.uid),
groups.isMember(req.uid, 'publishers'),
topics.getCategoryData(tid),
topics.getMainPost(tid, req.uid),
]);

const hostUrls = (meta.config['blog-comments:url'] || '').split(',');
let url;

hostUrls.forEach((hostUrl) => {
hostUrl = hostUrl.trim();
if (hostUrl[hostUrl.length - 1] === '/') {
hostUrl = hostUrl.substring(0, hostUrl.length - 1);
}

if (hostUrl === req.get('origin')) {
url = req.get('origin');
}
});

if (url) {
res.header('Access-Control-Allow-Origin', url);
} else {
winston.warn(`[nodebb-plugin-blog-comments] Origin (${req.get('origin')}) does not match hostUrls: ${hostUrls.join(', ')}`);
let postData = []; let categoryData = null; let
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These should be on separate lines.

mainPost = null;
if (topicData) {
[postData, categoryData, mainPost] = await Promise.all([
topics.getTopicPosts(topicData, `tid:${tid}:posts`, start, stop, req.uid, true),
topics.getCategoryData(tid),
topics.getMainPost(tid, req.uid),
]);
}

res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
res.header('Access-Control-Allow-Credentials', 'true');

const posts = postData.filter((post) => {
if (post.user && post.user.picture && !post.user.picture.startsWith('http')) {
post.user.picture = post.user.picture.replace(relativePath, '');
Expand All @@ -88,23 +100,30 @@ Comments.getCommentData = async function (req, res, next) {
if (userData.picture && !userData.picture.startsWith('http')) {
userData.picture = userData.picture.replace(relativePath, '');
}

const compose_location = meta.config['blog-comments:compose-location'] || 'top';
const top = compose_location === 'top';
const bottom = compose_location === 'bottom';
const show_branding = (meta.config['blog-comments:show-branding'] || 'on') === 'on';
const atTop = compose_location === 'top';

res.json({
posts: posts,
postCount: topicData.postcount,
posts,
postCount: topicData ? topicData.postcount : 0,
user: userData,
template: Comments.template,
token: req.csrfToken && req.csrfToken(),
isAdmin: !isAdmin ? isPublisher : isAdmin,
isAdmin: isAdmin || isPublisher,
isLoggedIn: req.loggedIn,
tid: tid,
tid,
category: categoryData,
mainPost: mainPost,
atTop: top,
atBottom: bottom,
mainPost,
atTop,
atBottom: !atTop,
show_branding,
loginURL: meta.config['blog-comments:login-url'] || '',
registerURL: meta.config['blog-comments:register-url'] || '',
authFlow: meta.config['blog-comments:auth-behavior'] || 'popup',
autoCreate: meta.config['blog-comments:autocreate'] === 'on',
profileLink: !(meta.config['blog-comments:profile-links'] === 'off'),
});
};

Expand Down Expand Up @@ -152,12 +171,19 @@ Comments.publishArticle = async function (req, res) {
groups.isMember(req.uid, 'publishers'),
]);

if (!isAdmin && !isPublisher) {
let { uid } = req;
if (meta.config['blog-comments:autocreate'] === 'on') {
uid = parseInt(meta.config['blog-comments:autocreate-user-id'], 10);
if (!uid) {
return res.json({ error: 'Invalid autocreate user specified' });
}
} else if (!isAdmin && !isPublisher) {
return res.json({ error: 'Only Administrators or members of the publishers group can publish articles' });
}

try {
const result = await topics.post({
uid: req.uid,
uid,
title: title,
content: markdown,
tags: tags ? JSON.parse(tags) : [],
Expand All @@ -167,7 +193,7 @@ Comments.publishArticle = async function (req, res) {
if (result && result.postData && result.postData.tid) {
await posts.setPostField(result.postData.pid, 'blog-comments:url', url);
await db.setObjectField('blog-comments', commentID, result.postData.tid);
res.redirect(`${(req.header('Referer') || '/')}#nodebb-comments`);
res.redirect(`${url || req.header('Referer') || '/'}#nodebb-comments`);
}
} catch (err) {
res.json({ error: `Unable to post topic ${err.message}` });
Expand Down
Loading