Skip to content

Commit

Permalink
BRS-642: Updates for facility/role handling as well as unified logger. (
Browse files Browse the repository at this point in the history
#119)

* BRS-642: Updates for facility/role handling as well as unified logger.

* Fix for isAdmin.

* Changed logic slightly.
  • Loading branch information
marklise authored Jun 28, 2022
1 parent ce66bdf commit a1f9851
Show file tree
Hide file tree
Showing 17 changed files with 233 additions and 133 deletions.
11 changes: 6 additions & 5 deletions lambda/captchaUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const PRIVATE_KEY = process.env.PRIVATE_KEY
alg: 'A256GCM',
k: 'FK3d8WvSRdxlUHs4Fs_xxYO3-6dCiUarBwiYNFw5hv8'
};
const { logger } = require('./logger');

const AWS_REGION = process.env.AWS_DEFAULT_REGION || 'ca-central-1';

Expand Down Expand Up @@ -55,7 +56,7 @@ async function getCaptcha(options) {
return responseBody;
}
} catch (err) {
console.error(err);
logger.error(err);
return {
valid: false
};
Expand Down Expand Up @@ -89,7 +90,7 @@ async function getCaptchaAudio(payload) {
audio: `data:audio/mp3;base64,${audioData.AudioStream.toString('base64')}`
};
} catch (err) {
console.error(err);
logger.error(err);
throw err;
}
}
Expand Down Expand Up @@ -137,7 +138,7 @@ function verifyJWT(token) {
};
}
} catch (e) {
console.error(e);
logger.error(e);
return {
valid: false
};
Expand All @@ -150,7 +151,7 @@ async function encrypt(body) {
const cr = await jose.JWE.createEncrypt(PRIVATE_KEY).update(buff).final();
return cr;
} catch (e) {
console.error(e);
logger.error(e);
throw e;
}
}
Expand All @@ -162,7 +163,7 @@ async function decrypt(body, private_key) {
const decryptedObject = JSON.parse(decrypted.plaintext.toString('utf8'));
return decryptedObject;
} catch (e) {
console.error(e);
logger.error(e);
throw e;
}
}
Expand Down
17 changes: 9 additions & 8 deletions lambda/checkActivation/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,19 @@ const { setStatus,
PASS_TYPE_PM,
TIMEZONE } = require('../dynamoUtil');
const { sendResponse } = require('../responseUtil');
const { logger } = require('../logger');

exports.handler = async (event, context) => {
console.log('Event:', event, context);
console.log('Server Time Zone:',
logger.debug('Event:', event, context);
logger.debug('Server Time Zone:',
Intl.DateTimeFormat().resolvedOptions().timeZone || 'undefined',
`(${DateTime.now().toISO()})`
);
try {
const currentPSTDateTime = DateTime.now().setZone(TIMEZONE);
const endOfPSTDayUTCDateTime = currentPSTDateTime.endOf('day').toUTC();

console.log("Checking against date:", endOfPSTDayUTCDateTime.toISO());
logger.debug("Checking against date:", endOfPSTDayUTCDateTime.toISO());

const filter = {
FilterExpression: '#theDate <= :theDate',
Expand All @@ -34,10 +35,10 @@ exports.handler = async (event, context) => {
}
};

console.log("Getting passes by status:", RESERVED_STATUS, filter);
logger.debug("Getting passes by status:", RESERVED_STATUS, filter);

const passes = await getPassesByStatus(RESERVED_STATUS, filter);
console.log("Reserved Passes:", passes.length);
logger.debug("Reserved Passes:", passes.length);

// Query the passStatus-index for passStatus = 'reserved'
// NB: Filter on date <= endOfToday for fixing previous bad data.
Expand Down Expand Up @@ -108,15 +109,15 @@ exports.handler = async (event, context) => {
passesToExpiredStatus.push(pass);
}
}
console.log("Passes => active:", passesToActiveStatus.length);
console.log("Passes => expired:", passesToExpiredStatus.length);
logger.debug("Passes => active:", passesToActiveStatus.length);
logger.debug("Passes => expired:", passesToExpiredStatus.length);

await setStatus(passesToActiveStatus, ACTIVE_STATUS);
await setStatus(passesToExpiredStatus, EXPIRED_STATUS);

return sendResponse(200, {}, context);
} catch (err) {
console.error(err);
logger.error(err);

return sendResponse(500, {}, context);
}
Expand Down
13 changes: 7 additions & 6 deletions lambda/checkExpiry/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ const { getPassesByStatus,
PASS_TYPE_AM,
TIMEZONE } = require('../dynamoUtil');
const { sendResponse } = require('../responseUtil');
const { logger } = require('../logger');

exports.handler = async (event, context) => {
console.log('Check Expiry', event, context);
console.log('Server Time Zone:',
logger.debug('Check Expiry', event, context);
logger.debug('Server Time Zone:',
Intl.DateTimeFormat().resolvedOptions().timeZone || 'undefined',
`(${DateTime.now().toISO()})`
);
Expand All @@ -22,21 +23,21 @@ exports.handler = async (event, context) => {

let passesToChange = [];
const passes = await getPassesByStatus(ACTIVE_STATUS);
console.log("Active Passes:", passes);
logger.debug("Active Passes:", passes);

for (pass of passes) {
// NOTE: Pass dates are stored in UTC.
// If pass date converted to PST is before the end of yesterday, it's definitely expire (AM/PM/DAY)
const passPSTDateTime = DateTime.fromISO(pass.date).setZone(TIMEZONE);
if (passPSTDateTime <= yesterdayEndPSTDateTime){
console.log("Expiring:", pass);
logger.debug("Expiring:", pass);
passesToChange.push(pass);
}

// If AM, see if we're currently in the afternoon or later compared to the pass date's noon time.
const passAMExpiryPSTDateTime = currentPSTDateTime.startOf('day').plus({hours: PASS_TYPE_EXPIRY_HOURS.AM});
if (pass.type === PASS_TYPE_AM && currentPSTDateTime >= passAMExpiryPSTDateTime){
console.log("Expiring:", pass);
logger.debug("Expiring:", pass);
passesToChange.push(pass);
}
}
Expand All @@ -48,7 +49,7 @@ exports.handler = async (event, context) => {

return sendResponse(200, {}, context);
} catch (err) {
console.error(err);
logger.error(err);

return sendResponse(500, {}, context);
}
Expand Down
11 changes: 6 additions & 5 deletions lambda/cloudwatchAlarm/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@ const { TIMEZONE } = require('../dynamoUtil');
const ROCKETCHAT_URL = process.env.ROCKETCHAT_URL;
const ROCKETCHAT_BEARER_TOKEN = process.env.ROCKETCHAT_BEARER_TOKEN;
const AWS_ACCOUNT_LIST = JSON.parse(process.env.AWS_ACCOUNT_LIST);
const { logger } = require('../logger');

exports.handler = async (event, context) => {
console.log('Cloudwatch Alarm Event:', event, context);
logger.debug('Cloudwatch Alarm Event:', event, context);
try {
// parse through the records
for(const record of event.Records) {
// Event this to Rocket.cat
console.log("record.body.Subject:", record.body);
logger.debug("record.body.Subject:", record.body);
const body = JSON.parse(record.body);
console.log("body:", body);
logger.debug("body:", body);
const message = JSON.parse(body.Message);

// Build the message fields.
Expand Down Expand Up @@ -65,11 +66,11 @@ exports.handler = async (event, context) => {
}
});
} catch (e) {
console.log("Error, couldn't send notification.", e);
logger.error("Error, couldn't send notification.", e);
}
}
} catch (e) {
console.log("Error parsing cloudwatch alarm data!", e);
logger.error("Error parsing cloudwatch alarm data!", e);
}

return {};
Expand Down
25 changes: 13 additions & 12 deletions lambda/deletePass/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,21 @@ const { dynamodb, runQuery, TABLE_NAME, TIMEZONE } = require('../dynamoUtil');
const { sendResponse } = require('../responseUtil');
const { decodeJWT, resolvePermissions } = require('../permissionUtil');
const { DateTime } = require('luxon');
const { logger } = require('../logger');

exports.handler = async (event, context) => {
console.log('Delete Pass', event);
console.log('event.queryStringParameters', event.queryStringParameters);
logger.debug('Delete Pass', event);
logger.debug('event.queryStringParameters', event.queryStringParameters);

try {
if (!event.queryStringParameters) {
return sendResponse(400, { msg: 'Invalid Request' }, context);
}
if (event.queryStringParameters.passId && event.queryStringParameters.park && event.queryStringParameters.code) {
console.log('Get the specific pass, this person is NOT authenticated but has a code');
logger.debug('Get the specific pass, this person is NOT authenticated but has a code');

let decodedToken = jwt.verify(event.queryStringParameters.code, process.env.JWT_SECRET);
console.log(decodedToken);
logger.debug(decodedToken);

if (decodedToken === null) {
return sendResponse(400, { msg: 'Invalid request' });
Expand All @@ -41,7 +42,7 @@ exports.handler = async (event, context) => {
UpdateExpression: 'SET passStatus = :cancelled',
TableName: TABLE_NAME
};
console.log('updatePassQuery:', updatePassQuery);
logger.debug('updatePassQuery:', updatePassQuery);

// Deduct the pass's numberOfGuests count from the trail period count.
const updateFacilityQuery = {
Expand All @@ -60,7 +61,7 @@ exports.handler = async (event, context) => {
ConditionExpression: 'attribute_exists(pk) AND attribute_exists(sk)',
TableName: TABLE_NAME
};
console.log('updateFacilityQuery:', updateFacilityQuery);
logger.debug('updateFacilityQuery:', updateFacilityQuery);

const res = await dynamodb
.transactWriteItems({
Expand All @@ -74,7 +75,7 @@ exports.handler = async (event, context) => {
]
})
.promise();
console.log('res:', res);
logger.debug('res:', res);

return sendResponse(200, { msg: 'Cancelled', pass: passNoAuth }, context);
} else if (event.queryStringParameters.passId && event.queryStringParameters.park) {
Expand All @@ -100,10 +101,10 @@ exports.handler = async (event, context) => {
UpdateExpression: 'SET passStatus = :cancelled',
TableName: TABLE_NAME
};
console.log('updatePassQuery:', updatePassQuery);
logger.debug('updatePassQuery:', updatePassQuery);

const dateselector = DateTime.fromISO(pass.date).setZone(TIMEZONE).toISODate();
console.log('dateselector', dateselector)
logger.debug('dateselector', dateselector)

const reservationCountCountQuery = {
Key: {
Expand All @@ -126,16 +127,16 @@ exports.handler = async (event, context) => {
TransactItems: [{ Update: updatePassQuery }, { Update: reservationCountCountQuery }]
})
.promise();
console.log('res:', res);
logger.debug('res:', res);

return sendResponse(200, { msg: 'Cancelled', pass: pass }, context);
}
} else {
console.log('Invalid Request');
logger.debug('Invalid Request');
return sendResponse(400, { msg: 'Invalid Request' }, context);
}
} catch (err) {
console.log(err);
logger.error(err);
return sendResponse(400, { msg: 'Invalid Request' }, context);
}
};
Expand Down
8 changes: 4 additions & 4 deletions lambda/dynamoUtil.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const AWS = require('aws-sdk');
const { logger } = require('./logger');

const TABLE_NAME = process.env.TABLE_NAME || 'parksreso';
const options = {
Expand Down Expand Up @@ -27,7 +28,6 @@ const dynamodb = new AWS.DynamoDB(options);

exports.dynamodb = new AWS.DynamoDB();

const { logger } = require('./logger');

async function setStatus(passes, status) {
for (let i = 0; i < passes.length; i++) {
Expand All @@ -52,7 +52,7 @@ async function setStatus(passes, status) {
async function runQuery(query, paginated = false) {
logger.debug('query:', query);
const data = await dynamodb.query(query).promise();
logger.debug('data:', JSON.stringify(data));
logger.debug('data:', data);
var unMarshalled = data.Items.map(item => {
return AWS.DynamoDB.Converter.unmarshall(item);
});
Expand All @@ -70,11 +70,11 @@ async function runQuery(query, paginated = false) {
async function runScan(query, paginated = false) {
logger.debug('query:', query);
const data = await dynamodb.scan(query).promise();
// logger.debug('data:', data);
logger.debug('data:', data);
var unMarshalled = data.Items.map(item => {
return AWS.DynamoDB.Converter.unmarshall(item);
});
// logger.debug(unMarshalled);
logger.debug(unMarshalled);
if (paginated) {
return {
LastEvaluatedKey: data.LastEvaluatedKey,
Expand Down
15 changes: 8 additions & 7 deletions lambda/exportPass/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ const { runQuery, TIMEZONE } = require('../dynamoUtil');
const { sendResponse } = require('../responseUtil');
const { decodeJWT, resolvePermissions } = require('../permissionUtil');
const { DateTime } = require('luxon');
const { logger } = require('../logger');

exports.handler = async (event, context) => {
console.log('Export Pass', event);
console.log('event.queryStringParameters', event.queryStringParameters);
logger.debug('Export Pass', event);
logger.debug('event.queryStringParameters', event.queryStringParameters);

let queryObj = {
TableName: process.env.TABLE_NAME
Expand Down Expand Up @@ -85,7 +86,7 @@ exports.handler = async (event, context) => {
queryObj.FilterExpression += ' AND #email =:email';
}

console.log('queryObj:', queryObj);
logger.debug('queryObj:', queryObj);

let scanResults = [];
do {
Expand Down Expand Up @@ -117,18 +118,18 @@ exports.handler = async (event, context) => {
Expires: expiryTime,
Key: '/' + token.data.idir_userid + '/passExport.csv',
});
console.log("URL:", URL);
logger.debug("URL:", URL);
return sendResponse(200, { signedURL: URL }, context);
} catch (e) {
console.log("Error uploading to S3.", e);
logger.error("Error uploading to S3.", e);
return sendResponse(400, { msg: 'Invalid Request' }, context);
}
} else {
console.log('Invalid Request');
logger.error('Invalid Request');
return sendResponse(400, { msg: 'Invalid Request' }, context);
}
} catch (err) {
console.log(err);
logger.error(err);
return sendResponse(400, err, context);
}
};
Expand Down
18 changes: 11 additions & 7 deletions lambda/logger.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, printf } = format;
const { combine, timestamp } = format;

const myFormat = printf(({ level, message, label, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
});

const LEVEL = process.env.LOG_LEVEL || 'info';
const LEVEL = process.env.LOG_LEVEL || 'error';

exports.logger = createLogger({
level: LEVEL,
format: combine(
timestamp(),
myFormat
format.printf((info) => {
let meta = ''
let symbols = Object.getOwnPropertySymbols(info)
if (symbols.length == 2) {
meta = JSON.stringify(info[symbols[1]])

}
return `${info.timestamp} ${[info.level.toUpperCase()]}: ${info.message} ${meta}`;
})
),
transports: [new transports.Console()]
});
Loading

0 comments on commit a1f9851

Please sign in to comment.