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

feat(campaign): various updates #266

Merged
merged 4 commits into from
Mar 31, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
11 changes: 11 additions & 0 deletions lib/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,17 @@ module.exports = {
type: 'array'
}
},
PUBLIC_FIELDS: {
CAMPAIGN: [
'id',
'url',
'name',
'active',
'description_short',
'description_long',
'autojoin_body'
]
},
TOKEN_LENGTH: {
MAIL_CONFIRMATION: 128,
ACCESS_TOKEN: 32,
Expand Down
11 changes: 11 additions & 0 deletions lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,16 @@ function findBy(query, fields) {
return whereObject;
}

// A helper to whilelist object's properties.
function whitelistObject(object, allowedFields) {
const newObject = {};
for (const field of allowedFields) {
newObject[field] = object[field];
}

return newObject;
}

function getRandomBytes(length) {
return new Promise((resolve, reject) => {
crypto.randomBytes(length / 2, (err, res) => {
Expand Down Expand Up @@ -197,6 +207,7 @@ module.exports = {
getSorting,
filterBy,
findBy,
whitelistObject,
getRandomBytes,
addGaugeData
};
4 changes: 3 additions & 1 deletion lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,9 @@ PermissionsRouter.put('/', permissions.updatePermission);
PermissionsRouter.delete('/', permissions.deletePermission);

// Everything related to a specific campaign. Auth only.
CampaignsRouter.use(middlewares.maybeAuthorize, middlewares.ensureAuthorized, fetch.fetchCampaign);
CampaignsRouter.use(middlewares.maybeAuthorize, fetch.fetchCampaign);
CampaignsRouter.get('/', campaigns.getCampaign);
CampaignsRouter.use(middlewares.ensureAuthorized);
CampaignsRouter.get('/members', campaigns.listCampaignMembers);
CampaignsRouter.get('/', campaigns.getCampaign);
CampaignsRouter.put('/', campaigns.updateCampaign);
Expand Down
12 changes: 8 additions & 4 deletions middlewares/campaigns.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,12 @@ exports.listAllCampaigns = async (req, res) => {
};

exports.getCampaign = async (req, res) => {
if (!req.permissions.hasPermission('global:view:campaign')) {
return errors.makeForbiddenError(res, 'Permission global:view:campaign is required, but not present.');
if (!req.user || !req.permissions.hasPermission('global:create:campaign')) {
req.currentCampaign = helpers.whitelistObject(req.currentCampaign, constants.PUBLIC_FIELDS.CAMPAIGN);
}

if (req.currentCampaign.autojoin_body) {
req.currentCampaign.autojoin_body = helpers.whitelistObject(req.currentCampaign.autojoin_body, ['id', 'name', 'email', 'phone', 'address', 'website']);
}

return res.json({
Expand All @@ -96,10 +100,10 @@ exports.createCampaign = async (req, res) => {
}

// TODO: filter out fields that are changed in the other way
const circle = await Campaign.create(req.body);
const campaign = await Campaign.create(req.body);
return res.json({
success: true,
data: circle
data: campaign
});
};

Expand Down
10 changes: 6 additions & 4 deletions middlewares/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,15 @@ exports.fetchPermission = async (req, res, next) => {
};

exports.fetchCampaign = async (req, res, next) => {
// searching the campaign by id if it's numeric
if (!helpers.isNumber(req.params.campaign_id)) {
return errors.makeBadRequestError(res, 'Campaign ID is invalid.');
// Checking if the passed ID is a string or not.
// If it is a string, find the campaign by URL, if not, find it by ID or URL.
let findObject = { url: req.params.campaign_id };
if (!Number.isNaN(Number(req.params.campaign_id))) {
findObject = { id: Number(req.params.campaign_id) };
}

const campaign = await Campaign.findOne({
where: { id: Number(req.params.campaign_id) },
where: findObject,
include: [{ model: Body, as: 'autojoin_body' }]
});
if (!campaign) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = {
up: (queryInterface, Sequelize) => queryInterface.changeColumn(
'campaigns',
'description_short',
Sequelize.TEXT
),
down: (queryInterface, Sequelize) => queryInterface.changeColumn(
'campaigns',
'description_short',
Sequelize.TEXT,
{ allowNull: false }
),
};
7 changes: 3 additions & 4 deletions models/Campaign.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,9 @@ const Campaign = sequelize.define('campaign', {
},
description_short: {
type: Sequelize.TEXT,
allowNull: false,
allowNull: true,
validate: {
notEmpty: { msg: 'Description should be set.' },
notNull: { msg: 'Description should be set.' }
notEmpty: { msg: 'Description should be set.' }
}
},
description_long: {
Expand All @@ -41,7 +40,7 @@ const Campaign = sequelize.define('campaign', {
},
activate_user: {
type: Sequelize.BOOLEAN,
allowNull: false,
allowNull: true,
defaultValue: true
}
}, {
Expand Down
58 changes: 50 additions & 8 deletions test/api/campaigns-details.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe('Campaign details', () => {
await generator.clearAll();
});

test('should return 404 if the campaign is not found', async () => {
test('should return 404 if the campaign id is not found', async () => {
const user = await generator.createUser({ superadmin: true });
const token = await generator.createAccessToken({}, user);

Expand All @@ -33,7 +33,7 @@ describe('Campaign details', () => {
expect(res.body).toHaveProperty('message');
});

test('should return 400 if id is not a number', async () => {
test('should return 404 if the campaign name is not found', async () => {
const user = await generator.createUser({ superadmin: true });
const token = await generator.createAccessToken({}, user);

Expand All @@ -45,13 +45,13 @@ describe('Campaign details', () => {
headers: { 'X-Auth-Token': token.value }
});

expect(res.statusCode).toEqual(400);
expect(res.statusCode).toEqual(404);
expect(res.body.success).toEqual(false);
expect(res.body).toHaveProperty('message');
expect(res.body).not.toHaveProperty('data');
});

test('should fail if no permission', async () => {
test('should return less info if no permission', async () => {
const user = await generator.createUser();
const token = await generator.createAccessToken({}, user);

Expand All @@ -63,10 +63,31 @@ describe('Campaign details', () => {
headers: { 'X-Auth-Token': token.value }
});

expect(res.statusCode).toEqual(403);
expect(res.body.success).toEqual(false);
expect(res.body).not.toHaveProperty('data');
expect(res.body).toHaveProperty('message');
expect(res.statusCode).toEqual(200);
expect(res.body.success).toEqual(true);
expect(res.body).toHaveProperty('data');
expect(res.body.data).not.toHaveProperty('autojoin_body_id');
});

test('should return some info about the autojoin_body', async () => {
const user = await generator.createUser();
const token = await generator.createAccessToken({}, user);

const body = await generator.createBody();
const campaign = await generator.createCampaign({ autojoin_body_id: body.id });

const res = await request({
uri: '/campaigns/' + campaign.id,
method: 'GET',
headers: { 'X-Auth-Token': token.value }
});

expect(res.statusCode).toEqual(200);
expect(res.body.success).toEqual(true);
expect(res.body).toHaveProperty('data');
expect(res.body.data).toHaveProperty('autojoin_body');
expect(res.body.data.autojoin_body).toHaveProperty('email');
expect(res.body.data.autojoin_body).not.toHaveProperty('founded_at');
});

test('should find the campaign by id', async () => {
Expand All @@ -89,4 +110,25 @@ describe('Campaign details', () => {
expect(res.body).not.toHaveProperty('errors');
expect(res.body.data.id).toEqual(campaign.id);
});

test('should find the campaign by url', async () => {
const user = await generator.createUser({ superadmin: true });
const token = await generator.createAccessToken({}, user);

await generator.createPermission({ scope: 'global', action: 'view', object: 'campaign' });

const campaign = await generator.createCampaign();

const res = await request({
uri: '/campaigns/' + campaign.url,
method: 'GET',
headers: { 'X-Auth-Token': token.value }
});

expect(res.statusCode).toEqual(200);
expect(res.body.success).toEqual(true);
expect(res.body).toHaveProperty('data');
expect(res.body).not.toHaveProperty('errors');
expect(res.body.data.url).toEqual(campaign.url);
});
});
28 changes: 0 additions & 28 deletions test/unit/campaigns.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,32 +67,6 @@ describe('Campaigns testing', () => {
}
});

test('should fail with null description_short', async () => {
try {
await generator.createCampaign({ description_short: null });
expect(1).toEqual(0);
} catch (err) {
expect(err).toHaveProperty('errors');
expect(err.errors.length).toEqual(1);
expect(err.errors[0].path).toEqual('description_short');
}
});

test('should fail with not set description_short', async () => {
try {
const campaign = generator.generateCampaign();
delete campaign.description_short;

await Campaign.create(campaign);

expect(1).toEqual(0);
} catch (err) {
expect(err).toHaveProperty('errors');
expect(err.errors.length).toEqual(1);
expect(err.errors[0].path).toEqual('description_short');
}
});

test('should fail with null description_long', async () => {
try {
await generator.createCampaign({ description_long: null });
Expand Down Expand Up @@ -123,14 +97,12 @@ describe('Campaigns testing', () => {
const data = generator.generateCampaign({
name: '\t\t\ttest\t\t\t',
url: '\t\t\tTEST\t\t\t',
description_short: ' \t test\t \t',
description_long: ' \t test\t \t',
});

const campaign = await Campaign.create(data);
expect(campaign.name).toEqual('test');
expect(campaign.url).toEqual('test');
expect(campaign.description_short).toEqual('test');
expect(campaign.description_long).toEqual('test');
});
});