Skip to content
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
39 changes: 19 additions & 20 deletions api/main_endpoints/routes/OfficeAccessCard.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const { API_KEY = 'NOTHING_REALLY' } = officeAccessCard;
const { decodeToken } = require('../util/token-functions.js');
const ROWS_PER_PAGE = 25;
const {
checkIfCardExists,
verifyCard,
generateAlias,
deleteCard,
editAlias,
Expand Down Expand Up @@ -89,14 +89,14 @@ router.get('/verify', async (req, res) => {
return res.sendStatus(FORBIDDEN);
}

const cardExists = await checkIfCardExists({ cardBytes });
if (cardExists) {
const alias = cardExists.alias;
const cardVerification = await verifyCard(cardBytes);
if (cardVerification) {
const alias = cardVerification.alias;
AuditLog.create({
action: AuditLogActions.VERIFY_CARD,
details: { alias }
});
writeLogToClient(req.method, { alias: cardExists.alias, statusCode: OK });
writeLogToClient(req.method, { alias: cardVerification.alias, statusCode: OK });
return res.sendStatus(OK);
}
// if a card doesnt exist and we arent trying
Expand Down Expand Up @@ -143,30 +143,36 @@ router.post('/delete', async (req, res) => {
return res.sendStatus(decoded.status);
}

const { alias } = req.body;
if (!alias) {
const { _id } = req.body;
if (!_id) {
writeLogToClient(req.method, {
statusCode: BAD_REQUEST,
message: 'cardBytes missing from request',
});
return res.sendStatus(BAD_REQUEST);
}
const cardDeletion = await deleteCard(_id);

const cardExists = await checkIfCardExists({ alias });
if (!await cardExists) {
if (cardDeletion === null) {
logger.info('Card does not exist');
writeLogToClient(req.method, {
statusCode: NOT_FOUND,
message: 'Card does not exist',
});
return res.sendStatus(NOT_FOUND);
}

if (await deleteCard(alias)) {
} else if(cardDeletion === false){
writeLogToClient(req.method, {
statusCode: SERVER_ERROR,
message: 'Error deleting card',
Comment on lines +164 to +166

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

let's include the card's _id here as well

});
return res.sendStatus(SERVER_ERROR);
} else {
const alias = cardDeletion.alias;
logger.info('Successfully deleted card');
writeLogToClient(req.method, {
alias,
alias: cardDeletion.alias,
statusCode: OK,
_id
});
AuditLog.create({
userId: decoded.token._id,
Expand All @@ -175,13 +181,6 @@ router.post('/delete', async (req, res) => {
});
return res.sendStatus(OK);
}

writeLogToClient(req.method, {
alias: cardExists.alias,
statusCode: SERVER_ERROR,
message: 'Error deleting card',
});
return res.sendStatus(SERVER_ERROR);
});

router.post('/getAllCards', async (req, res) => {
Expand Down
24 changes: 12 additions & 12 deletions api/main_endpoints/util/OfficeAccessCard.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ const OfficeAccessCard = require('../models/OfficeAccessCard.js');
const logger = require('../../util/logger');
const { ADJECTIVES, NOUNS } = require('../../util/CardReaderConstants.js');

function checkIfCardExists({ cardBytes = null, alias = null } = {}) {
const body = (cardBytes !== null) ? { cardBytes } : { alias };
function verifyCard(cardBytes) {
return new Promise((resolve) => {
try {
OfficeAccessCard.findOneAndUpdate(
body,
{ cardBytes },
{
$inc: { verifiedCount: 1 },
$set: { lastVerified: Date.now() }
Expand All @@ -16,7 +15,7 @@ function checkIfCardExists({ cardBytes = null, alias = null } = {}) {
}
, (error, result) => {
if (error) {
logger.error('checkIfCardExists got an error querying mongodb: ', error);
logger.error('verifyCard got an error querying mongodb: ', error);
return resolve(false);
}
if (!result) {
Expand All @@ -26,7 +25,7 @@ function checkIfCardExists({ cardBytes = null, alias = null } = {}) {
return resolve(result); // return the document
});
} catch (error) {
logger.error('checkIfCardExists caught an error: ', error);
logger.error('verifyCard caught an error: ', error);
return resolve(false);
}
});
Expand Down Expand Up @@ -64,20 +63,21 @@ async function generateAlias() {
return new Date().toGMTString();
}

function deleteCard(alias) {
function deleteCard(_id) {
return new Promise((resolve) => {
try {
OfficeAccessCard.findOneAndDelete(
{ alias }
, (error, result) => {
OfficeAccessCard.findByIdAndDelete(
_id,
(error, result) => {
if (error) {
logger.error('deleteCard got an error querying mongodb: ', error);
return resolve(false);
}
if (!result) {
logger.info(`Card ${ alias } not found in the database`);
logger.info(`Card with id: ${_id} not found in the database`);
return resolve(null);
}
return resolve(!!result);
return resolve(result);
}
);
} catch (error) {
Expand Down Expand Up @@ -113,4 +113,4 @@ function editAlias(_id, newAlias) {
});
}

module.exports = { checkIfCardExists, generateAlias, deleteCard, editAlias };
module.exports = { verifyCard, generateAlias, deleteCard, editAlias };
4 changes: 2 additions & 2 deletions src/APIFunctions/CardReader.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export async function getAllCardsFromDb({
return status;
}

export async function deleteCardFromDb(token, alias) {
export async function deleteCardFromDb(token, _id) {
let status = new ApiResponse();
try {
const url = new URL('/api/OfficeAccessCard/delete', BASE_API_URL);
Expand All @@ -41,7 +41,7 @@ export async function deleteCardFromDb(token, alias) {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ alias, }),
body: JSON.stringify({ _id }),
});
if (res.ok) {
const result = await res.json();
Expand Down
2 changes: 1 addition & 1 deletion src/Pages/CardReader/CardReader.js
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ export default function CardReader() {
cancelText: 'No, keep the card',
confirmClassAddons: 'bg-red-600 hover:bg-red-500',
handleConfirmation: async () => {
await deleteCardFromDb(token, cardToDelete.alias);
await deleteCardFromDb(token, cardToDelete._id);
await getAllCards();
setToggleDelete(!toggleDelete);
},
Expand Down
15 changes: 7 additions & 8 deletions test/api/OfficeAccessCard.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ const {
SERVER_ERROR,
FORBIDDEN,
} = require('../../api/util/constants').STATUS_CODES;
const { MEMBERSHIP_STATE } = require('../../api/util/constants');
const {
initializeTokenMock,
setTokenStatus,
Expand All @@ -45,16 +44,15 @@ const token = '';

describe('OfficeAccessCard', () => {
let deleteCardStub = null;
let getAllCardsStub = null;
let editAliasStub = null;
let testCardId = null;

const VALID_CARD_BYTES = 'wesleys card';
const NEW_CARD_BYTES = 'dials card';
const INVALID_CARD_BYTES = 'evans card';

const VALID_ID = id.toString();
const INVALID_ID = 'tiffanys id';
const VALID_ALIAS = 'gauravs card';
const INVALID_ALIAS = 'bobs card';
const NEW_ALIAS = 'updated test card';
const EMPTY_ALIAS = '';
const WHITESPACE_ALIAS = ' ';
Expand All @@ -76,6 +74,7 @@ describe('OfficeAccessCard', () => {
// Before each test we empty the database
tools.emptySchema(OfficeAccessCard);
const testOfficeAccessCard = new OfficeAccessCard({
_id: VALID_ID,
cardBytes: VALID_CARD_BYTES,
alias: VALID_ALIAS,
verifiedCount: INCREMENT_VERIFY_COUNT,
Expand Down Expand Up @@ -194,9 +193,9 @@ describe('OfficeAccessCard', () => {

it('Should return 404 if the card attempted to be deleted was not found', async () => {
setTokenStatus(true);
deleteCardStub.resolves(false);
deleteCardStub.resolves(null);
const result = await test.sendPostRequestWithToken(token,
DELETE_API_PATH, { alias: INVALID_ALIAS },
DELETE_API_PATH, { _id: INVALID_ID },
);
expect(result).to.have.status(NOT_FOUND);
});
Expand All @@ -205,7 +204,7 @@ describe('OfficeAccessCard', () => {
setTokenStatus(true);
deleteCardStub.resolves(true);
const result = await test.sendPostRequestWithToken(token,
DELETE_API_PATH, { alias: VALID_ALIAS },
DELETE_API_PATH, { _id: VALID_ID },
);
expect(result).to.have.status(OK);
});
Expand All @@ -214,7 +213,7 @@ describe('OfficeAccessCard', () => {
setTokenStatus(true);
deleteCardStub.resolves(false);
const result = await test.sendPostRequestWithToken(token,
DELETE_API_PATH, { alias: VALID_ALIAS },
DELETE_API_PATH, { _id: VALID_ID },
);
expect(result).to.have.status(SERVER_ERROR);
});
Expand Down