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

[GSoC19] Articles improvements #7

Open
wants to merge 15 commits into
base: articles
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
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
3 changes: 2 additions & 1 deletion app/api/server/v1/rooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ API.v1.addRoute('rooms.leave', { authRequired: true }, {

API.v1.addRoute('rooms.createDiscussion', { authRequired: true }, {
post() {
const { prid, pmid, reply, t_name, users } = this.bodyParams;
const { prid, pmid, reply, t_name, users, t } = this.bodyParams;
if (!prid) {
return API.v1.failure('Body parameter "prid" is required.');
}
Expand All @@ -238,6 +238,7 @@ API.v1.addRoute('rooms.createDiscussion', { authRequired: true }, {
pmid,
t_name,
reply,
t,
users: users || [],
}));

Expand Down
1 change: 1 addition & 0 deletions app/articles/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Readme file for articles.
Empty file added app/articles/client/index.js
Empty file.
Empty file added app/articles/index.js
Empty file.
104 changes: 104 additions & 0 deletions app/articles/server/api/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { Restivus } from 'meteor/nimble:restivus';
import _ from 'underscore';

import { processWebhookMessage } from '../../../lib';
import { API } from '../../../api';
import { settings } from '../../../settings';
import * as Models from '../../../models';

const Api = new Restivus({
Copy link
Collaborator

Choose a reason for hiding this comment

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

Note: Revisit the security

Copy link
Owner Author

Choose a reason for hiding this comment

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

Apart from token checking, what else I have to check?

enableCors: true,
apiPath: 'ghooks/',
auth: {
user() {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Add rate-limiting, to prevent brute force

Copy link
Owner Author

Choose a reason for hiding this comment

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

Integrations also don't have any rate-limit, should I add it here. 🤔

const payloadKeys = Object.keys(this.bodyParams);
const payloadIsWrapped = (this.bodyParams && this.bodyParams.payload) && payloadKeys.length === 1;
if (payloadIsWrapped && this.request.headers['content-type'] === 'application/x-www-form-urlencoded') {
try {
this.bodyParams = JSON.parse(this.bodyParams.payload);
} catch ({ message }) {
return {
error: {
statusCode: 400,
body: {
success: false,
error: message,
},
},
};
}
}

this.announceToken = settings.get('Announcement_Token');
const { blogId } = this.request.params;
const token = decodeURIComponent(this.request.params.token);

if (this.announceToken !== `${ blogId }/${ token }`) {
return {
error: {
statusCode: 404,
body: {
success: false,
error: 'Invalid token provided.',
},
},
};
}

const user = this.bodyParams.userId ? Models.Users.findOne({ _id: this.bodyParams.userId }) : Models.Users.findOne({ username: this.bodyParams.username });

return { user };
},
},
});

function executeAnnouncementRest() {
const defaultValues = {
channel: this.bodyParams.channel,
alias: this.bodyParams.alias,
avatar: this.bodyParams.avatar,
emoji: this.bodyParams.emoji,
};

// TODO: Turn this into an option on the integrations - no body means a success
// TODO: Temporary fix for https://github.com/RocketChat/Rocket.Chat/issues/7770 until the above is implemented
if (!this.bodyParams || (_.isEmpty(this.bodyParams) && !this.integration.scriptEnabled)) {
// return RocketChat.API.v1.failure('body-empty');
return API.v1.success();
}

try {
const message = processWebhookMessage(this.bodyParams, this.user, defaultValues);
if (_.isEmpty(message)) {
return API.v1.failure('unknown-error');
}

return API.v1.success();
} catch ({ error, message }) {
return API.v1.failure(error || message);
}
}

function executefetchUserRest() {
try {
const { _id, name, username, emails } = this.user;
const user = { _id, name, username, emails };

return API.v1.success({ user });
} catch ({ error, message }) {
return API.v1.failure(error || message);
}
}

Api.addRoute(':blogId/:token', { authRequired: true }, {
post: executeAnnouncementRest,
get: executeAnnouncementRest,
});

// If a user is editor/admin in Ghost but is not an admin in RC,
// then the e-mail will not be provided to that user
// This method will allow user to fetch user with email.
Api.addRoute(':blogId/:token/getUser', { authRequired: true }, {
post: executefetchUserRest,
get: executefetchUserRest,
});
6 changes: 6 additions & 0 deletions app/articles/server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import './settings';
import './methods/admin';
import './methods/user';
import './api/api';
import './lib/triggerHandler';
import './triggers';
150 changes: 150 additions & 0 deletions app/articles/server/lib/triggerHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';

import { settings } from '../../../settings';
import { API } from '../utils/url';

const api = new API();

export const triggerHandler = new class ArticlesSettingsHandler {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Refactor it to use ghostClient

constructor() {
this.trigger = {};
}

eventNameArgumentsToObject(...args) {
const argObject = {
event: args[0],
};
switch (argObject.event) {
case 'userEmail':
case 'userRealname':
case 'userAvatar':
case 'userName':
if (args.length >= 2) {
argObject.user = args[1];
}
break;
case 'roomType':
case 'roomName':
if (args.length >= 2) {
argObject.room = args[1];
}
break;
case 'siteTitle':
argObject.article = args[1];
break;
default:
argObject.event = undefined;
break;
}
return argObject;
}

mapEventArgsToData(data, { event, room, user, article }) {
data.event = event;
switch (event) {
case 'userEmail':
case 'userRealname':
case 'userAvatar':
case 'userName':
data.user_id = user._id;

if (user.avatar) {
data.avatar = user.avatar;
}

if (user.name) {
data.name = user.name;
}

if (user.email) {
data.email = user.email;
}

if (user.username) {
data.username = user.username;
}
break;
case 'roomType':
case 'roomName':
data.room_id = room.rid;

if (room.name) {
data.name = room.name;
}

if (room.type) {
data.type = room.type;
}
break;
case 'siteTitle':
if (article && article.title) {
data.title = article.title;
}
break;
default:
break;
}
}

executeTrigger(...args) {
const argObject = this.eventNameArgumentsToObject(...args);
const { event } = argObject;

if (!event) {
return;
}

if (settings.get('Articles_enabled')) {
const token = settings.get('Settings_Token');
this.trigger.api = api.rhooks(token);
this.trigger.retryCount = 5;
}

this.executeTriggerUrl(argObject, 0);
}

executeTriggerUrl({ event, room, user, article }, tries = 0) {
if (!this.trigger.api) {
return;
}
const url = this.trigger.api;

const data = {};

this.mapEventArgsToData(data, { event, room, user, article });

const opts = {
params: {},
method: 'POST',
url,
data,
auth: undefined,
npmRequestOptions: {
rejectUnauthorized: !settings.get('Allow_Invalid_SelfSigned_Certs'),
strictSSL: !settings.get('Allow_Invalid_SelfSigned_Certs'),
},
headers: {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36',
},
};

if (!opts.url || !opts.method) {
return;
}

HTTP.call(opts.method, opts.url, opts, (error, result) => {
// if the result contained nothing or wasn't a successful statusCode
if (!result) {
if (tries < this.trigger.retryCount) {
// 2 seconds, 4 seconds, 8 seconds
const waitTime = Math.pow(2, tries + 1) * 1000;

Meteor.setTimeout(() => {
this.executeTriggerUrl({ event, room, user }, tries + 1);
}, waitTime);
}
}
});
}
}();
19 changes: 19 additions & 0 deletions app/articles/server/logoutCleanUp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';

import { settings } from '../../settings';
import { API } from './utils/url';

const api = new API();

export function ghostCleanUp(cookie) {
const rcUrl = Meteor.absoluteUrl().replace(/\/$/, '');
try {
if (settings.get('Articles_enabled')) {
HTTP.call('DELETE', api.session(), { headers: { cookie, referer: rcUrl } });
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we restrict the cookie to just what is required by the ghost to log out and not pass all the cookies?

Copy link
Owner Author

Choose a reason for hiding this comment

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

We need rc_uid and rc_token while deleting the session also.

}
} catch (e) {
// Do nothing if failed to logout from Ghost.
// Error will be because user has not logged in to Ghost.
}
}
68 changes: 68 additions & 0 deletions app/articles/server/methods/admin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';
import { Random } from 'meteor/random';

import { API } from '../utils/url';
import { settings } from '../../../settings';

const api = new API();

function setupGhost(user, token) {
const rcUrl = Meteor.absoluteUrl().replace(/\/$/, '');
const blogTitle = settings.get('Article_Site_title');
const blogToken = Random.id(17);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Use Random.secret instead?

const announceToken = `${ blogToken }/${ Random.id(24) }`;
const settingsToken = `${ blogToken }/${ Random.id(24) }`;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why use different tokens, and use a base token (blogToken) as a prefix to both of them?

settings.updateById('Announcement_Token', announceToken);
settings.updateById('Settings_Token', settingsToken);
const data = {
setup: [{
rc_url: rcUrl,
rc_id: user._id,
rc_token: token,
announce_token: announceToken,
settings_token: settingsToken,
blogTitle,
}],
};
return HTTP.call('POST', api.setup(), { data, headers: { 'Content-Type': 'application/json' } });
}

function redirectGhost() {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we make it a const, and move it inside the method, as it is not being modified and used outside it?

return {
link: api.siteUrl(),
message: 'Ghost is Set up. Redirecting.',
};
}

Meteor.methods({
Articles_admin_panel(token) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Add authorisation and authentication to this meteor method

const enabled = settings.get('Articles_enabled');

if (!enabled) {
throw new Meteor.Error('Articles are disabled');
}
const user = Meteor.users.findOne(Meteor.userId());
Copy link
Collaborator

Choose a reason for hiding this comment

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

We need not fetch the whole user object here as it is not being used, just the id is used later on.

Note: use Meteor.user() in case you need a user object directly in future.

let errMsg = 'Unable to connect to Ghost. Make sure Ghost is running';

try {
let response = HTTP.call('GET', api.setup());

if (response.data.setup[0].status) { // Ghost site is already setup
return redirectGhost();
}

// Setup Ghost Site and set title
response = setupGhost(user, token);
errMsg = 'Unable to setup. Make sure Ghost is running';

if (response.statusCode === 201 && response.content) {
return redirectGhost();
}

throw new Meteor.Error(errMsg);
} catch (e) {
throw new Meteor.Error(e.error || errMsg);
}
},
});
Loading