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
2 changes: 1 addition & 1 deletion api/main_endpoints/models/OfficeAccessCard.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const OfficeAccessCardSchema = new Schema(
},
verifiedCount:{
type:Number,
default:0
default:1
},
lastVerified:{
type:Date,
Expand Down
132 changes: 87 additions & 45 deletions api/main_endpoints/routes/OfficeAccessCard.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const {
SERVER_ERROR,
NOT_FOUND,
OK,
FORBIDDEN,
} = require('../../util/constants').STATUS_CODES;
const express = require('express');
const router = express.Router();
Expand All @@ -12,29 +13,34 @@ const OfficeAccessCard = require('../models/OfficeAccessCard.js');
const logger = require('../../util/logger');
const { officeAccessCard = {} } = require('../../config/config.json');
const { API_KEY = 'NOTHING_REALLY' } = officeAccessCard;
const { decodeTokenFromBodyOrQuery } = require('../util/token-functions.js');
const {
decodeTokenFromBodyOrQuery,
decodeToken,
checkIfTokenSent,
checkIfTokenValid
} = require('../util/token-functions.js');
const ROWS_PER_PAGE = 25;

router.use(bodyParser.json());

function checkIfCardExists(cardBytes) {
return new Promise((resolve) => {
try {
OfficeAccessCard.findOneAndUpdate(
{ cardBytes:cardBytes},
{ cardBytes },
{
$inc: { verifiedCount: 1 },
$set: { lastVerified: Date.now() }
}, {
useFindAndModify: false, new:true, upsert:false
useFindAndModify: false, new: true, upsert: false
}
, (error, result) => {
if (error) {
logger.error('checkIfCardExists got an error querying mongodb: ', error);
return resolve(false);
}
if(!result){
if (!result) {
logger.info(`Card:${cardBytes} not found in the database`);
return resolve(false);
}
return resolve(!!result);
});
Expand All @@ -56,7 +62,7 @@ function deleteCard(cardBytes) {
return resolve(false);
}
if (!result) {
logger.info(`Card:${cardBytes} not found in the database`);
logger.info(`Card ${cardBytes} not found in the database`);
}
return resolve(!!result);
}
Expand All @@ -70,18 +76,33 @@ function deleteCard(cardBytes) {

let clients = [];

const defaultResponse = {
cardWasAdded: false,
const defaultGetResponse = {
message: 'Card authorized!',
endpoint: '/verify',
requestType: 'GET',
};

const writeRequestResponse = ({ statusCode, ...rest }) => {
const response = {
statusCode,
...defaultResponse,
...rest,
};
const defaultPostResponse = {
message: 'Card deleted!',
endpoint: '/delete',
requestType: 'POST',
};

const writeLogToClient = (requestType, { statusCode, ...rest }) => {
let response = {};
if (requestType === 'GET') {
response = {
statusCode,
...defaultGetResponse,
...rest,
};
} else {
response = {
statusCode,
...defaultPostResponse,
...rest,
};
}
clients.forEach(client => {
client.res.write(`data: ${JSON.stringify(response)}\n\n`);
});
Expand All @@ -98,7 +119,7 @@ router.get('/verify', async (req, res) =>{
const missingValue = required.find(({ value }) => !value);

if (missingValue) {
writeRequestResponse({ statusCode: BAD_REQUEST, message: `${missingValue.title} missing from request` });
writeLogToClient(req.method, { statusCode: BAD_REQUEST, message: `${missingValue.title} missing from request` });
return res.status(BAD_REQUEST).send(` ${missingValue.title} missing from request`);
}

Expand All @@ -108,30 +129,28 @@ router.get('/verify', async (req, res) =>{

const cardExists = await checkIfCardExists(cardBytes);
if (cardExists) {
writeRequestResponse({ statusCode: OK });
writeLogToClient(req.method, { statusCode: OK });
return res.sendStatus(OK);
}
// if a card doesnt exist and we arent trying
// to add a new one, that means we were trying
// to verify a card, and that card isnt found.
// therefore return a non OK status
if (!add) {
writeRequestResponse({ statusCode: NOT_FOUND, message: 'Card not found' });
writeLogToClient(req.method, { statusCode: NOT_FOUND, message: 'Card not found' });
return res.sendStatus(NOT_FOUND);
}

// if we reached here, the card does not exist and is trying to be added
try {
if (add) {
logger.info('adding a new card');
await new OfficeAccessCard({
cardBytes
}).save();
writeRequestResponse({ statusCode: OK, message: 'Card added!', endpoint: '/verify?add=1' });
return res.sendStatus(OK);
}
logger.info('adding a new card');
await new OfficeAccessCard({
cardBytes,
}).save();
writeLogToClient(req.method, { statusCode: OK, message: 'Card added!', endpoint: '/verify?add=1' });
return res.sendStatus(OK);
} catch (error) {
logger.error('Error creating OfficeAccessCard: ', error);
writeRequestResponse({
writeLogToClient(req.method, {
statusCode: SERVER_ERROR,
endpoint: '/verify?add=1',
message: `Error creating Office AccessCard: ${error}`
Expand All @@ -140,44 +159,67 @@ router.get('/verify', async (req, res) =>{
}
});

router.get('/delete', async (req, res) => {
if (!await decodeTokenFromBodyOrQuery(req)) {
router.post('/delete', async (req, res) => {
if (!await decodeToken(req)) {
return res.sendStatus(UNAUTHORIZED);
}

const { cardBytes } = req.query;
const { cardBytes } = req.body;
if (!cardBytes) {
writeRequestResponse({
writeLogToClient(req.method, {
statusCode: BAD_REQUEST,
endpoint: '/delete',
message: 'cardBytes missing from request'
message: 'cardBytes missing from request',
requestType: req.method,
});
return res.sendStatus(BAD_REQUEST);
}

if (!await checkIfCardExists(cardBytes)) {
logger.info('Card does not exist');
writeRequestResponse({
writeLogToClient(req.method, {
statusCode: NOT_FOUND,
endpoint: '/delete',
message: 'Card does not exist',
requestType: req.method,
});
return res.sendStatus(NOT_FOUND);
}

const tryDeleteCard = await deleteCard(cardBytes);
if (!tryDeleteCard) {
logger.info('Error deleting card');
writeRequestResponse({
statusCode: SERVER_ERROR,
endpoint: '/delete',
message: 'Error deleting card'
if (await deleteCard(cardBytes)) { // successful
logger.info('Successfully deleted card');
writeLogToClient(req.method, {
statusCode: OK,
message: 'Card deleted!',
});
return res.sendStatus(OK);
}
writeLogToClient({
statusCode: SERVER_ERROR,
message: 'Error deleting card',
});
return res.sendStatus(SERVER_ERROR);
});

router.post('/getAllCards', async (req, res) => {
if (!checkIfTokenSent(req)) {
return res.sendStatus(FORBIDDEN);
} else if (!checkIfTokenValid(req)) {
return res.sendStatus(UNAUTHORIZED);
}

const skip = Math.max(Number(req.body.page) || 0, 0) * ROWS_PER_PAGE;

try {
const total = await OfficeAccessCard.count({});
const items = await OfficeAccessCard.find({}, {}, { skip, limit: ROWS_PER_PAGE });
return res.status(OK).send({
items,
total,
rowsPerPage: ROWS_PER_PAGE,
});
} catch (error) {
logger.error('Error fetching cards: ', error);
return res.sendStatus(SERVER_ERROR);
}
logger.info('Successfully deleted card');
writeRequestResponse({ statusCode: OK, endpoint: '/delete', message: 'Card deleted!' });
return res.sendStatus(OK);
});

router.get('/listen', async (req, res) => {
Expand Down
57 changes: 57 additions & 0 deletions src/APIFunctions/CardReader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { ApiResponse } from './ApiResponses';
import { BASE_API_URL } from '../Enums';

export async function getAllCardsFromDb({
token,
page = null,
}) {
let status = new ApiResponse();
try {
const url = new URL('/api/OfficeAccessCard/getAllCards', BASE_API_URL);
const res = await fetch(url.href, {
method: 'POST',
body: JSON.stringify({
page,
}),
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
}
});
if (res.ok) {
const result = await res.json();
status.responseData = result;
} else {
status.error = true;
}
} catch (err) {
status.error = true;
status.responseData = err;
}
return status;
}

export async function deleteCardFromDb(token, cardBytes) {
let status = new ApiResponse();
try {
const url = new URL('/api/OfficeAccessCard/delete', BASE_API_URL);
const res = await fetch(url.href, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ cardBytes, }),
});
if (res.ok) {
const result = await res.json();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

is there a json response from the delete endpoint?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

i believe its a boolean of success/failure

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

double check if this res.json() returns an error

status.responseData = result;
} else {
status.error = true;
}
} catch (err) {
status.error = true;
status.responseData = err;
}
return status;
}
2 changes: 1 addition & 1 deletion src/APIFunctions/Messaging.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function sendMessage(id, token, message) {
}
} catch(err) {
status.error = true;
status.responseData = error;
status.responseData = err;
}
return status;
}
Expand Down
Loading