Skip to content

Commit

Permalink
Merge pull request #313 from center-for-threat-informed-defense/300-r…
Browse files Browse the repository at this point in the history
…efactor-groups-service

Refactored groups service
  • Loading branch information
seansica authored Nov 7, 2023
2 parents bb38aa0 + 3fa882a commit 059a5e0
Show file tree
Hide file tree
Showing 21 changed files with 733 additions and 1,152 deletions.
17 changes: 17 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,23 @@
"program": "${workspaceFolder}/bin/www",
"outputCapture": "std",
"envFile": "${workspaceFolder}/.env"
},
{
"type": "node",
"request": "launch",
"name": "Run Regression Tests",
"skipFiles": [
"<node_internals>/**"
],
"runtimeExecutable": "npm",
"args": [
"run",
"test"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"outputCapture": "std",
"envFile": "${workspaceFolder}/.env"
}
]
}
11 changes: 7 additions & 4 deletions app/controllers/assets-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,15 @@ exports.retrieveById = async function(req, res) {
};

exports.retrieveVersionById = async function(req, res) {
const options = {
retrieveDataComponents: req.query.retrieveDataComponents
}

// TODO Remove after confirming these are not being used by assetsService.retrieveVersionById
// const options = {
// retrieveDataComponents: req.query.retrieveDataComponents
// }

try {
const asset = await assetsService.retrieveVersionById(req.params.stixId, req.params.modified, options);
// const asset = await assetsService.retrieveVersionById(req.params.stixId, req.params.modified, options);
const asset = await assetsService.retrieveVersionById(req.params.stixId, req.params.modified);
if (!asset) {
return res.status(404).send('Asset not found.');
}
Expand Down
199 changes: 100 additions & 99 deletions app/controllers/groups-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

const groupsService = require('../services/groups-service');
const logger = require('../lib/logger');
const { DuplicateIdError, BadlyFormattedParameterError, InvalidTypeError, InvalidQueryStringParameterError } = require('../exceptions');

exports.retrieveAll = function(req, res) {
exports.retrieveAll = async function(req, res) {
const options = {
offset: req.query.offset || 0,
limit: req.query.limit || 0,
Expand All @@ -14,100 +15,101 @@ exports.retrieveAll = function(req, res) {
lastUpdatedBy: req.query.lastUpdatedBy,
includePagination: req.query.includePagination
}
try {
const results = await groupsService.retrieveAll(options);

groupsService.retrieveAll(options, function(err, results) {
if (err) {
logger.error('Failed with error: ' + err);
return res.status(500).send('Unable to get groups. Server error.');
}
else {
if (options.includePagination) {
logger.debug(`Success: Retrieved ${ results.data.length } of ${ results.pagination.total } total group(s)`);
}
else {
logger.debug(`Success: Retrieved ${ results.length } group(s)`);
}
return res.status(200).send(results);
} catch (err) {
logger.error('Failed with error: ' + err);
return res.status(500).send('Unable to get groups. Server error.');
}
});

};

exports.retrieveById = function(req, res) {
exports.retrieveById = async function(req, res) {
const options = {
versions: req.query.versions || 'latest'
}
try {
const groups = await groupsService.retrieveById(req.params.stixId, options);

groupsService.retrieveById(req.params.stixId, options, function (err, groups) {
if (err) {
if (err.message === groupsService.errors.badlyFormattedParameter) {
logger.warn('Badly formatted stix id: ' + req.params.stixId);
return res.status(400).send('Stix id is badly formatted.');
}
else if (err.message === groupsService.errors.invalidQueryStringParameter) {
logger.warn('Invalid query string: versions=' + req.query.versions);
return res.status(400).send('Query string parameter versions is invalid.');
}
else {
logger.error('Failed with error: ' + err);
return res.status(500).send('Unable to get groups. Server error.');
}

if (groups.length === 0) {
return res.status(404).send('Group not found.');
}
else {
if (groups.length === 0) {
return res.status(404).send('Group not found.');
}
else {
logger.debug(`Success: Retrieved ${ groups.length } group(s) with id ${ req.params.stixId }`);
return res.status(200).send(groups);
}
logger.debug(`Success: Retrieved ${ groups.length } group(s) with id ${ req.params.stixId }`);
return res.status(200).send(groups);
}
});

} catch (err) {
if (err instanceof BadlyFormattedParameterError) {
logger.warn('Badly formatted stix id: ' + req.params.stixId);
return res.status(400).send('Stix id is badly formatted.');
}
else if (err instanceof InvalidQueryStringParameterError) {
logger.warn('Invalid query string: versions=' + req.query.versions);
return res.status(400).send('Query string parameter versions is invalid.');
}
else {
logger.error('Failed with error: ' + err);
return res.status(500).send('Unable to get groups. Server error.');
}
}

};

exports.retrieveVersionById = function(req, res) {
groupsService.retrieveVersionById(req.params.stixId, req.params.modified, function (err, group) {
if (err) {
if (err.message === groupsService.errors.badlyFormattedParameter) {
logger.warn('Badly formatted stix id: ' + req.params.stixId);
return res.status(400).send('Stix id is badly formatted.');
}
else {
logger.error('Failed with error: ' + err);
return res.status(500).send('Unable to get group. Server error.');
}
} else {
if (!group) {
return res.status(404).send('Group not found.');
}
else {
logger.debug(`Success: Retrieved group with id ${group.id}`);
return res.status(200).send(group);
}
exports.retrieveVersionById = async function(req, res) {

try {
const group = await groupsService.retrieveVersionById(req.params.stixId, req.params.modified);
if (!group) {
return res.status(404).send('Group not found.');
}
else {
logger.debug(`Success: Retrieved group with id ${group.id}`);
return res.status(200).send(group);
}
} catch (err) {
if (err instanceof BadlyFormattedParameterError) {
logger.warn('Badly formatted stix id: ' + req.params.stixId);
return res.status(400).send('Stix id is badly formatted.');
}
else {
logger.error('Failed with error: ' + err);
return res.status(500).send('Unable to get group. Server error.');
}
});
}

};

exports.create = async function(req, res) {
// Get the data from the request
const groupData = req.body;
const options = {
import: false,
userAccountId: req.user?.userAccountId
};

// Create the group
try {
const options = {
import: false,
userAccountId: req.user?.userAccountId
};

const group = await groupsService.create(groupData, options);
logger.debug('Success: Created group with id ' + group.stix.id);
return res.status(201).send(group);
}
catch(err) {
if (err.message === groupsService.errors.duplicateId) {
if (err instanceof DuplicateIdError) {
logger.warn('Duplicate stix.id and stix.modified');
return res.status(409).send('Unable to create group. Duplicate stix.id and stix.modified properties.');
}
else if (err.message === groupsService.errors.invalidType) {
else if (err instanceof InvalidTypeError) {
logger.warn('Invalid stix.type');
return res.status(400).send('Unable to create group. stix.type must be intrusion-set');
}
Expand All @@ -118,58 +120,57 @@ exports.create = async function(req, res) {
}
};

exports.updateFull = function(req, res) {
exports.updateFull = async function(req, res) {
// Get the data from the request
const groupData = req.body;

// Create the group
groupsService.updateFull(req.params.stixId, req.params.modified, groupData, function(err, group) {
if (err) {
logger.error("Failed with error: " + err);
return res.status(500).send("Unable to update group. Server error.");
}
else {
if (!group) {
return res.status(404).send('Group not found.');
} else {
logger.debug("Success: Updated group with id " + group.stix.id);
return res.status(200).send(group);
}
try {
// Create the group
const group = await groupsService.updateFull(req.params.stixId, req.params.modified, groupData);
if (!group) {
return res.status(404).send('Group not found.');
} else {
logger.debug("Success: Updated group with id " + group.stix.id);
return res.status(200).send(group);
}
});
} catch (err) {
logger.error("Failed with error: " + err);
return res.status(500).send("Unable to update group. Server error.");
}

};

exports.deleteVersionById = function(req, res) {
groupsService.deleteVersionById(req.params.stixId, req.params.modified, function (err, group) {
if (err) {
logger.error('Delete group failed. ' + err);
return res.status(500).send('Unable to delete group. Server error.');
}
else {
if (!group) {
return res.status(404).send('Group not found.');
} else {
logger.debug("Success: Deleted group with id " + group.stix.id);
return res.status(204).end();
}
exports.deleteVersionById = async function(req, res) {

try {
const group = await groupsService.deleteVersionById(req.params.stixId, req.params.modified);
if (!group) {
return res.status(404).send('Group not found.');
} else {
logger.debug("Success: Deleted group with id " + group.stix.id);
return res.status(204).end();
}
});
} catch (err) {
logger.error('Delete group failed. ' + err);
return res.status(500).send('Unable to delete group. Server error.');
}

};

exports.deleteById = function(req, res) {
groupsService.deleteById(req.params.stixId, function (err, groups) {
if (err) {
logger.error('Delete group failed. ' + err);
return res.status(500).send('Unable to delete group. Server error.');
exports.deleteById = async function(req, res) {

try {
const groups = await groupsService.deleteById(req.params.stixId);
if (groups.deletedCount === 0) {
return res.status(404).send('Group not found.');
}
else {
if (groups.deletedCount === 0) {
return res.status(404).send('Group not found.');
}
else {
logger.debug(`Success: Deleted group with id ${ req.params.stixId }`);
return res.status(204).end();
}
logger.debug(`Success: Deleted group with id ${ req.params.stixId }`);
return res.status(204).end();
}
});
} catch (err) {
logger.error('Delete group failed. ' + err);
return res.status(500).send('Unable to delete group. Server error.');
}

};
7 changes: 7 additions & 0 deletions app/exceptions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ class NotImplementedError extends CustomError {
}
}

class InvalidTypeError extends CustomError {
constructor(options) {
super('Invalid stix.type', options);
}
}

module.exports = {

//** General errors */
Expand All @@ -101,4 +107,5 @@ module.exports = {
IdentityServiceError,
TechniquesServiceError,
TacticsServiceError,
InvalidTypeError
};
3 changes: 2 additions & 1 deletion app/repository/_base.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ class BaseRepository extends AbstractRepository {
$match: {
$or: [
{ 'stix.name': { '$regex': options.search, '$options': 'i' } },
{ 'stix.description': { '$regex': options.search, '$options': 'i' } }
{ 'stix.description': { '$regex': options.search, '$options': 'i' } },
{ 'workspace.attack_id': { '$regex': options.search, '$options': 'i' } }
]
}
};
Expand Down
9 changes: 2 additions & 7 deletions app/repository/assets-repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@
const BaseRepository = require('./_base.repository');
const Asset = require('../models/asset-model');

class AssetsRepository extends BaseRepository {
class AssetsRepository extends BaseRepository {}

constructor() {
super(Asset);
}
}

module.exports = new AssetsRepository();
module.exports = new AssetsRepository(Asset);
7 changes: 7 additions & 0 deletions app/repository/collection-bundles.repository.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const BaseRepository = require("./_base.repository");

const Collection = require('../models/collection-model');

class CollectionBundlesRepository extends BaseRepository { }

module.exports = new CollectionBundlesRepository(Collection);
8 changes: 8 additions & 0 deletions app/repository/groups-repository.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
'use strict';

const BaseRepository = require('./_base.repository');
const Group = require('../models/group-model');

class GroupsRepository extends BaseRepository { }

module.exports = new GroupsRepository(Group);
10 changes: 2 additions & 8 deletions app/repository/matrix-repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,6 @@
const BaseRepository = require('./_base.repository');
const Matrix = require('../models/matrix-model');

class MatrixRepository extends BaseRepository {
class MatrixRepository extends BaseRepository { }

constructor() {
super(Matrix);
// this.model = Matrix;
}
}

module.exports = new MatrixRepository();
module.exports = new MatrixRepository(Matrix);
Loading

0 comments on commit 059a5e0

Please sign in to comment.