Skip to content

Commit

Permalink
feat(general): campaigns crud and testing
Browse files Browse the repository at this point in the history
  • Loading branch information
serge1peshcoff committed Feb 12, 2020
1 parent 813671e commit e311e93
Show file tree
Hide file tree
Showing 11 changed files with 375 additions and 29 deletions.
18 changes: 14 additions & 4 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const MemberRouter = router({ mergeParams: true });
const BodiesRouter = router({ mergeParams: true });
const CirclesRouter = router({ mergeParams: true });
const PermissionsRouter = router({ mergeParams: true });
const CampaignsRouter = router({ mergeParams: true });

const server = express();
server.use(bodyParser.json());
Expand All @@ -44,13 +45,13 @@ process.on('unhandledRejection', (err) => {

// Endpoints not requiring authorization.
GeneralRouter.get('/healthcheck', middlewares.healthcheck);
GeneralRouter.post('/campaigns/:campaign_id', campaigns.registerUser);
GeneralRouter.post('/signup/:campaign_id', campaigns.registerUser);
GeneralRouter.post('/confirm-email', register.confirmEmail);
GeneralRouter.post('/login', login.login);
GeneralRouter.post('/renew', login.renew);

// Endpoints allowing unauthorized and authorized access.
GeneralRouter.use(middlewares.maybeAuthorize);
GeneralRouter.use(middlewares.maybeAuthorize, myPermissions.loadMyGlobalPermissions);
GeneralRouter.get('/bodies', bodies.listAllBodies);

// Endpoints not allowing unauthorized access.
Expand All @@ -62,8 +63,10 @@ GeneralRouter.get('/members', middlewares.ensureAuthorized, members.listAllUsers
GeneralRouter.post('/bodies', middlewares.ensureAuthorized, bodies.createBody);
GeneralRouter.get('/circles', middlewares.ensureAuthorized, circles.listAllCircles);
GeneralRouter.post('/circles', middlewares.ensureAuthorized, circles.createCircle);
GeneralRouter.get('/permissions', permissions.listAllPermissions);
GeneralRouter.post('/permissions', permissions.createPermission);
GeneralRouter.get('/permissions', middlewares.ensureAuthorized, permissions.listAllPermissions);
GeneralRouter.post('/permissions', middlewares.ensureAuthorized, permissions.createPermission);
GeneralRouter.get('/campaigns', middlewares.ensureAuthorized, campaigns.listAllCampaigns);
GeneralRouter.post('/campaigns', middlewares.ensureAuthorized, campaigns.createCampaign);

// Everything related to a specific (maybe logged in) user. Auth only.
MemberRouter.use(middlewares.maybeAuthorize, middlewares.ensureAuthorized, fetch.fetchUser);
Expand Down Expand Up @@ -92,10 +95,17 @@ PermissionsRouter.get('/', permissions.getPermission);
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.get('/', campaigns.getCampaign);
CampaignsRouter.put('/', campaigns.updateCampaign);
CampaignsRouter.delete('/', campaigns.deleteCampaign);

server.use('/members/:user_id', MemberRouter);
server.use('/bodies/:body_id', BodiesRouter);
server.use('/circles/:circle_id', CirclesRouter);
server.use('/permissions/:permission_id', PermissionsRouter);
server.use('/campaigns/:campaign_id', CampaignsRouter);
server.use('/', GeneralRouter);

server.use(middlewares.notFound);
Expand Down
46 changes: 46 additions & 0 deletions middlewares/campaigns.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,49 @@ exports.registerUser = async (req, res) => {
}
});
};

exports.listAllCampaigns = async (req, res) => {
const circle = await Campaign.findAll({});

return res.json({
success: true,
data: circle
});
};

exports.getCampaign = async (req, res) => {
// TODO: check permissions
return res.json({
success: true,
data: req.currentCampaign
});
};

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

exports.updateCampaign = async (req, res) => {
// TODO: check permissions
// TODO: filter out fields that are changed in the other way
await req.currentCampaign.update(req.body);
return res.json({
success: true,
data: req.currentCampaign
});
};

exports.deleteCampaign = async (req, res) => {
// TODO: check permissions
await req.currentCampaign.destroy();
return res.json({
success: true,
message: 'Campaign is deleted.'
});
};
2 changes: 1 addition & 1 deletion middlewares/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ exports.fetchCampaign = async (req, res, next) => {
}

const campaign = await Campaign.findOne({
where: { id: Number(req.params.circle_id) }
where: { id: Number(req.params.campaign_id) }
});
if (!campaign) {
return errors.makeNotFoundError(res, 'Campaign is not found.');
Expand Down
14 changes: 0 additions & 14 deletions middlewares/generic.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
const moment = require('moment');
const _ = require('lodash');

const errors = require('../lib/errors');
const logger = require('../lib/logger');
const helpers = require('../lib/helpers');
const {
User,
Circle,
CircleMembership,
CirclePermission,
Permission,
AccessToken
} = require('../models');
const { Sequelize } = require('../lib/sequelize');
const packageInfo = require('../package');

exports.maybeAuthorize = async (req, res, next) => {
Expand Down Expand Up @@ -53,13 +46,6 @@ exports.ensureAuthorized = async (req, res, next) => {
return next();
};

exports.getMyGlobalPermissions = async (req, res) => {
return res.json({
success: true,
data: req.permissions
});
};

/* istanbul ignore next */
exports.healthcheck = (req, res) => {
return res.json({
Expand Down
13 changes: 12 additions & 1 deletion middlewares/my-permissions.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ const {
} = require('../models');
const { Sequelize } = require('../lib/sequelize');

exports.getMyGlobalPermissions = async (req, res, next) => {
exports.loadMyGlobalPermissions = async (req, res, next) => {
if (!req.user) {
return next();
}

// Fetching permissions.
// 1) get the list of the circles user's in.
const directCircleMemberships = await CircleMembership.findAll({
Expand Down Expand Up @@ -39,3 +43,10 @@ exports.getMyGlobalPermissions = async (req, res, next) => {

return next();
};

exports.getMyGlobalPermissions = async (req, res) => {
return res.json({
success: true,
data: req.permissions
});
};
18 changes: 9 additions & 9 deletions test/api/campaign-submission.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('Campaign submission', () => {
const user = generator.generateUser();

const res = await request({
uri: '/campaigns/asdasdas',
uri: '/signup/asdasdas',
method: 'POST',
headers: { 'X-Auth-Token': 'blablabla' },
body: user
Expand All @@ -36,7 +36,7 @@ describe('Campaign submission', () => {
const user = generator.generateUser();

const res = await request({
uri: '/campaigns/' + campaign.url,
uri: '/signup/' + campaign.url,
method: 'POST',
headers: { 'X-Auth-Token': 'blablabla' },
body: user
Expand All @@ -53,7 +53,7 @@ describe('Campaign submission', () => {
const user = generator.generateUser({ username: 'not valid username ' });

const res = await request({
uri: '/campaigns/' + campaign.url,
uri: '/signup/' + campaign.url,
method: 'POST',
headers: { 'X-Auth-Token': 'blablabla' },
body: user
Expand All @@ -71,7 +71,7 @@ describe('Campaign submission', () => {
const user = generator.generateUser({ first_name: '!@#!@#D' });

const res = await request({
uri: '/campaigns/' + campaign.url,
uri: '/signup/' + campaign.url,
method: 'POST',
headers: { 'X-Auth-Token': 'blablabla' },
body: user
Expand All @@ -89,7 +89,7 @@ describe('Campaign submission', () => {
const user = generator.generateUser({ last_name: '!@#!@#D' });

const res = await request({
uri: '/campaigns/' + campaign.url,
uri: '/signup/' + campaign.url,
method: 'POST',
headers: { 'X-Auth-Token': 'blablabla' },
body: user
Expand All @@ -107,7 +107,7 @@ describe('Campaign submission', () => {
const user = generator.generateUser({ email: null });

const res = await request({
uri: '/campaigns/' + campaign.url,
uri: '/signup/' + campaign.url,
method: 'POST',
headers: { 'X-Auth-Token': 'blablabla' },
body: user
Expand All @@ -125,7 +125,7 @@ describe('Campaign submission', () => {
const user = generator.generateUser({ password: null });

const res = await request({
uri: '/campaigns/' + campaign.url,
uri: '/signup/' + campaign.url,
method: 'POST',
headers: { 'X-Auth-Token': 'blablabla' },
body: user
Expand All @@ -143,7 +143,7 @@ describe('Campaign submission', () => {
const user = generator.generateUser({ username: null });

const res = await request({
uri: '/campaigns/' + campaign.url,
uri: '/signup/' + campaign.url,
method: 'POST',
headers: { 'X-Auth-Token': 'blablabla' },
body: user
Expand All @@ -161,7 +161,7 @@ describe('Campaign submission', () => {
const user = generator.generateUser();

const res = await request({
uri: '/campaigns/' + campaign.url,
uri: '/signup/' + campaign.url,
method: 'POST',
headers: { 'X-Auth-Token': 'blablabla' },
body: user
Expand Down
57 changes: 57 additions & 0 deletions test/api/campaigns-creating.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const { startServer, stopServer } = require('../../lib/server.js');
const { request } = require('../scripts/helpers');
const generator = require('../scripts/generator');

describe('Campaigns creating', () => {
beforeAll(async () => {
await startServer();
});

afterAll(async () => {
await stopServer();
});

afterEach(async () => {
await generator.clearAll();
});

test('should fail if there are validation errors', async () => {
const user = await generator.createUser({ username: 'test', mail_confirmed_at: new Date() });
const token = await generator.createAccessToken({}, user);

const campaign = generator.generateCampaign({ name: '' });

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

expect(res.statusCode).toEqual(422);
expect(res.body.success).toEqual(false);
expect(res.body).not.toHaveProperty('data');
expect(res.body).toHaveProperty('errors');
expect(res.body.errors).toHaveProperty('name');
});

test('should succeed if everything is okay', async () => {
const user = await generator.createUser({ username: 'test', mail_confirmed_at: new Date() });
const token = await generator.createAccessToken({}, user);

const campaign = generator.generateCampaign();

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

expect(res.statusCode).toEqual(200);
expect(res.body.success).toEqual(true);
expect(res.body).not.toHaveProperty('errors');
expect(res.body).toHaveProperty('data');
expect(res.body.data.name).toEqual(campaign.name);
});
});
55 changes: 55 additions & 0 deletions test/api/campaigns-deleting.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const { startServer, stopServer } = require('../../lib/server.js');
const { request } = require('../scripts/helpers');
const generator = require('../scripts/generator');
const { Campaign } = require('../../models');

describe('Campaigns deleting', () => {
beforeAll(async () => {
await startServer();
});

afterAll(async () => {
await stopServer();
});

afterEach(async () => {
await generator.clearAll();
});

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

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

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

test('should succeed if everything is okay', async () => {
const user = await generator.createUser();
const token = await generator.createAccessToken({}, user);

const campaign = await generator.createCampaign();

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

expect(res.statusCode).toEqual(200);
expect(res.body.success).toEqual(true);
expect(res.body).not.toHaveProperty('errors');
expect(res.body).toHaveProperty('message');

const campaignFromDb = await Campaign.findByPk(campaign.id);
expect(campaignFromDb).toEqual(null);
});
});
Loading

0 comments on commit e311e93

Please sign in to comment.