forked from revir/nodebb-plugin-blog-comments2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibrary.js
518 lines (471 loc) · 14.6 KB
/
library.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
(function(module) {
"use strict";
var Comments = {};
const { getNestedChildren, getNestedPosts } = require("./public/lib/src/helper");
var db = require.main.require("./src/database"),
meta = require.main.require("./src/meta"),
posts = require.main.require("./src/posts"),
topics = require.main.require("./src/topics"),
user = require.main.require("./src/user"),
groups = require.main.require("./src/groups"),
fs = require.main.require("fs"),
path = require.main.require("path"),
async = require.main.require("async"),
winston = require.main.require("winston");
var simpleRecaptcha = require.main.require("simple-recaptcha-new");
module.exports = Comments;
function CORSSafeReq(req) {
var hostUrls = (meta.config["blog-comments:url"] || "").split(","),
url;
hostUrls.forEach(function(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) {
winston.warn(
"[nodebb-plugin-blog-comments-cryptofr] Origin (" +
req.get("origin") +
") does not match hostUrls: " +
hostUrls.join(", ")
);
}
return url;
}
function CORSFilter(req, res) {
var url = CORSSafeReq(req);
if (!url) {
return;
}
res.header("Access-Control-Allow-Origin", url);
res.header(
"Access-Control-Allow-Headers",
"X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept"
);
res.header("Access-Control-Allow-Credentials", "true");
return res;
}
Comments.getToken = function (req, res) {
return res.json({
token: req.csrfToken()
})
}
Comments.getTopicIDByCommentID = function(commentID, blogger, callback) {
db.getObjectField("blog-comments:" + blogger, commentID, function(
err,
tid
) {
callback(err, tid);
});
};
Comments.getCommentData = function(req, res) {
var commentID = req.params.id,
blogger = req.params.blogger || "default",
uid = req.user ? req.user.uid : 0;
Comments.getTopicIDByCommentID(commentID, blogger, function(err, tid) {
var disabled = false;
async.parallel(
{
posts: async function getPosts() {
if (disabled) {
throw err;
} else {
return getNestedPosts(
tid,
uid,
req.params.pagination || 0,
req.params.sorting
);
}
},
postCount: function(next) {
topics.getTopicField(tid, "postcount", next);
},
user: function(next) {
user.getUserData(uid, next);
},
isAdministrator: function(next) {
user.isAdministrator(uid, next);
},
isPublisher: function(next) {
groups.isMember(uid, "publishers", next);
},
category: function(next) {
topics.getCategoryData(tid, next);
},
mainPost: function(next) {
topics.getMainPost(tid, uid, next);
}
},
function(err, data) {
CORSFilter(req, res);
var top = true;
var bottom = false;
var compose_location = meta.config["blog-comments:compose-location"];
if (compose_location == "bottom") {
bottom = true;
top = false;
}
res.json({
posts: data.posts,
postCount: data.postCount - 1,
user: data.user,
template: Comments.template,
singleCommentTpl: Comments.singleCommentTpl,
loginModalTemplate: Comments.loginModalTemplate,
registerModalTemplate: Comments.registerModalTemplate,
token: req.csrfToken(),
isAdmin: !data.isAdministrator
? data.isPublisher
: data.isAdministrator,
isLoggedIn: !!uid,
tid: tid,
category: data.category,
mainPost: data.mainPost,
isValid: !!data.mainPost && !!tid,
atBottom: bottom,
atTop: top,
siteTitle: meta.config.title,
sorting: req.params.sorting
});
}
);
});
};
function get_redirect_url(url, err) {
var rurl = url + "#nodebb-comments";
if (url.indexOf("#") !== -1) {
// compatible for mmmw's blog, he uses hash in url;
rurl = url;
}
if (err) {
rurl = url + "?error=" + err.message + "#nodebb-comments";
if (url.indexOf("#") !== -1) {
rurl =
url.split("#")[0] + "?error=" + err.message + "#" + url.split("#")[1];
}
}
return rurl;
}
Comments.votePost = function(req, res, callback) {
if (!CORSSafeReq(req)) {
return;
}
var toPid = req.body.toPid,
isUpvote = JSON.parse(req.body.isUpvote),
uid = req.user ? req.user.uid : 0;
const fn = isUpvote ? "upvote" : "unvote";
posts[fn](toPid, uid, function(err, result) {
CORSFilter(req, res);
res.json({ error: err && err.message, result: result });
});
};
Comments.downvotePost = function(req, res, callback) {
if (!CORSSafeReq(req)) {
return;
}
var toPid = req.body.toPid,
isDownvote = JSON.parse(req.body.isDownvote),
uid = req.user ? req.user.uid : 0;
const fn = isDownvote ? "downvote" : "unvote";
posts[fn](toPid, uid, function(err, result) {
CORSFilter(req, res);
res.json({ error: err && err.message, result: result });
});
};
Comments.bookmarkPost = function(req, res, callback) {
if (!CORSSafeReq(req)) {
return;
}
var toPid = req.body.toPid,
isBookmark = JSON.parse(req.body.isBookmark),
uid = req.user ? req.user.uid : 0;
var func = isBookmark ? "bookmark" : "unbookmark";
posts[func](toPid, uid, function(err, result) {
CORSFilter(req, res);
res.json({ error: err && err.message, result: result });
});
};
Comments.replyToComment = function(req, res, callback) {
var content = req.body.content,
tid = req.body.tid,
url = req.body.url,
toPid = req.body.toPid,
uid = req.user ? req.user.uid : 0;
topics.reply(
{
tid: tid,
uid: uid,
toPid: toPid,
content: content
},
function(err, postData) {
res.redirect(get_redirect_url(url, err));
}
);
};
Comments.editPost = function(req, res) {
const { pid } = req.params;
const content = req.body.content,
url = req.body.url,
uid = req.user ? req.user.uid : 0;
posts.edit(
{
uid,
content,
pid,
req
},
function(err, postData) {
res.redirect(get_redirect_url(url, err));
}
);
};
Comments.publishArticle = function(req, res, callback) {
var markdown = req.body.markdown,
title = req.body.title,
url = req.body.url,
commentID = req.body.id,
tags = req.body.tags,
blogger = req.body.blogger || "default",
uid = req.user ? req.user.uid : 0,
cid = JSON.parse(req.body.cid);
if (cid === -1) {
var hostUrls = (meta.config["blog-comments:url"] || "").split(","),
position = 0;
hostUrls.forEach(function(hostUrl, i) {
hostUrl = hostUrl.trim();
if (hostUrl[hostUrl.length - 1] === "/") {
hostUrl = hostUrl.substring(0, hostUrl.length - 1);
}
if (hostUrl === req.get("origin")) {
position = i;
}
});
cid = meta.config["blog-comments:cid"].toString() || "";
cid =
parseInt(cid.split(",")[position], 10) ||
parseInt(cid.split(",")[0], 10) ||
1;
}
async.parallel(
{
isAdministrator: function(next) {
user.isAdministrator(uid, next);
},
isPublisher: function(next) {
groups.isMember(uid, "publishers", next);
}
},
function(err, userStatus) {
if (!userStatus.isAdministrator && !userStatus.isPublisher) {
return res.json({
error:
"Only Administrators or members of the publishers group can publish articles"
});
}
topics.post(
{
uid: uid,
title: title,
content: markdown,
tags: tags ? JSON.parse(tags) : [],
req: req,
externalLink: url, // save externalLink and externalComment to topic, only v2mm theme can do this.
externalComment: markdown,
cid: cid
},
function(err, result) {
if (!err && result && result.postData && result.postData.tid) {
posts.setPostField(
result.postData.pid,
"blog-comments:url",
url,
function(err) {
if (err) {
return res.json({
error: "Unable to post topic",
result: result
});
}
db.setObjectField(
"blog-comments:" + blogger,
commentID,
result.postData.tid
);
var rurl =
(req.header("Referer") || "/") + "#nodebb-comments";
if (url.indexOf("#") !== -1) {
// compatible for mmmw's blog, he uses hash in url;
rurl = url;
}
res.redirect(rurl);
}
);
} else {
res.json({ error: "Unable to post topic", result: result });
}
}
);
}
);
};
Comments.addLinkbackToArticle = function(post, callback) {
var hostUrls = (meta.config["blog-comments:url"] || "").split(","),
position;
posts.getPostField(post.pid, "blog-comments:url", function(err, url) {
if (url) {
hostUrls.forEach(function(hostUrl, i) {
if (url.indexOf(hostUrl.trim().replace(/^https?:\/\//, "")) !== -1) {
position = i;
}
});
var blogName = meta.config["blog-comments:name"] || "";
blogName =
parseInt(blogName.split(",")[position], 10) ||
parseInt(blogName.split(",")[0], 10) ||
1;
post.profile.push({
content:
"Posted from <strong><a href=" +
url +
" target='blank'>" +
blogName +
"</a></strong>"
});
}
callback(err, post);
});
};
Comments.deletePost = async function (req, res) {
const uid = req.user ? req.user.uid : 0;
const pid = req.params.pid;
await posts.delete(pid, uid)
return res.json({deleted: true, uid, pid})
}
Comments.addAdminLink = function(custom_header, callback) {
custom_header.plugins.push({
route: "/blog-comments",
icon: "fa-book",
name: "Blog Comments"
});
callback(null, custom_header);
};
function renderAdmin(req, res, callback) {
res.render("admin/admin", {});
}
function captchaMiddleware(req, res, next) {
const privateKey = meta.config["blog-comments:captcha-api-key"]; // your private key here
const ip = req.ip; // this is an optional parameter
const response = req.body.captcha;
simpleRecaptcha(privateKey, ip, response, function(err) {
if (err)
return res.status(500).send({
error: err.message,
results: {}
});
return next();
});
}
function register(req, res) {
if (req.body.terms) {
return user.create(req.body, function userCreateCb(err, uid) {
// TODO Add status for user endpoint
const error = err && err.message;
return res.status(error ? 403 : 200).json({
error,
results: {
uid
}
});
});
} else {
return res.json({
error: "Terms are not accepted",
results: {}
});
}
}
function userExists(req, res) {
const { username } = req.query;
if (username) {
return user.existsBySlug(username, function cb(err, exists) {
const error = err && err.message;
return res.status(error ? 403 : 200).json({
error,
results: {
exists
}
});
});
} else {
return res.json({
error: null,
results: {
exists: true
}
});
}
}
function emailExists(req, res) {
const { email } = req.query;
if (email) {
return user.email.available(email, function cb(err, available) {
const error = err && err.message;
return res.status(error ? 403 : 200).json({
error,
results: {
available
}
});
});
} else {
return res.json({
error: null,
results: {
available: true
}
});
}
}
Comments.init = function(params, callback) {
var app = params.router,
middleware = params.middleware,
controllers = params.controllers;
const registerTemplate = (fileName, folder, key) =>
fs.readFile(
path.resolve(__dirname, `./public/templates/${folder}/${fileName}.tpl`),
function(err, data) {
Comments[key] = data.toString();
}
);
registerTemplate("comments", "comments", "template");
registerTemplate("single", "comments","singleCommentTpl");
registerTemplate("loginModal","modal", "loginModalTemplate");
registerTemplate("registerModal","modal", "registerModalTemplate");
// TODO Apply CSRF to everything
app.get(
"/comments/get/:blogger/:id/:pagination(\\d+)?/:sorting(oldest|newest|best)?",
middleware.applyCSRF,
Comments.getCommentData
);
app.post("/comments/plugin/register", captchaMiddleware, register);
app.post("/comments/reply", Comments.replyToComment);
app.post("/comments/publish", Comments.publishArticle);
app.post("/comments/vote", Comments.votePost);
app.post("/comments/downvote", Comments.downvotePost);
app.post("/comments/bookmark", Comments.bookmarkPost);
app.post("/comments/edit/:pid", Comments.editPost);
app.get("/comments/plugin/email", emailExists);
app.get("/comments/plugin/username", userExists);
app.get("/admin/blog-comments", middleware.admin.buildHeader, renderAdmin);
app.get("/api/admin/blog-comments", renderAdmin);
app.post("/comments/delete/:pid", Comments.deletePost);
app.get('/comments/token', middleware.applyCSRF, Comments.getToken);
callback();
};
})(module);