apf-node-common 1.0.112 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,3 @@
1
- //const log = require('./Logger/index').getLogger();
2
-
3
1
  const sendResponse= require('./exception/SendResponse')
4
2
  var jwt = require('jsonwebtoken');
5
3
  const {UserType} = require('./constants/UserType');
@@ -10,17 +8,9 @@ exports.setContextAttributes = async (req, res,httpContext, next)=>{
10
8
  log.info('httpContext : ' + httpContext);
11
9
 
12
10
  if (!authToken) {
13
-
14
- // console.log('authToken ' + authToken);
15
- // const result = sendResponse.unAuthorizedAccess(res);
16
- // res.status(result.statuscode).send(result.response);
17
11
  next();
18
-
19
12
  } else {
20
13
  try{
21
-
22
-
23
-
24
14
  authToken = authToken.replace('Bearer','').trim();
25
15
  const payload = jwt.decode(authToken, {complete: true}).payload;
26
16
 
@@ -75,6 +65,7 @@ exports.setContextAttributes = async (req, res,httpContext, next)=>{
75
65
 
76
66
  httpContext.set('username',payload.sub)
77
67
  httpContext.set('TimeZone',payload.TimeZone)
68
+ httpContext.set("IPAddress", req.ip)
78
69
 
79
70
  log.info(`username - ${httpContext.get('username')}`);
80
71
  next();
@@ -87,17 +78,3 @@ exports.setContextAttributes = async (req, res,httpContext, next)=>{
87
78
  }
88
79
  }
89
80
  }
90
-
91
- // function userMiddleware (req, res, next) {
92
- // getUserViaJWT(req.headers.authentication)
93
- // .then(function(user) {
94
- // req.user = user
95
- // next()
96
- // })
97
- // .catch(function (error) {
98
- // res.status(401).end() //replace with proper error handling
99
- // })
100
- // }
101
- // app.use(userMiddleware)
102
-
103
-
@@ -1,6 +1,6 @@
1
1
  const DATE_TIME_DB_FORMAT = "YYYY-MM-DD HH:mm:ss";
2
2
  const moment = require("moment");
3
- AuditLoggerService = require("./AuditLoggerService");
3
+ const AuditLoggerService = require("./AuditLoggerService");
4
4
 
5
5
  class AuditLogger {
6
6
 
@@ -22,7 +22,6 @@ class AuditLogger {
22
22
  entityId = String(obj[key]);
23
23
  break;
24
24
  }
25
-
26
25
  }
27
26
  return entityId;
28
27
  }
@@ -31,29 +30,23 @@ class AuditLogger {
31
30
  return moment().utc().format(DATE_TIME_DB_FORMAT);
32
31
  }
33
32
 
34
-
35
33
  async audit(message, subject, messageAttributes) {
36
34
  try {
37
-
38
-
39
-
40
35
  const entityId = this.getPropertyValue(JSON.parse(message), "id");
41
36
  const currentTime = this.UTC();
42
- const userName = (messageAttributes && messageAttributes.CurrentUserName) ? messageAttributes.CurrentUserName.Value : "system";
43
- const ipaddress = (messageAttributes && messageAttributes.IPAddress) ? messageAttributes.IPAddress.Value : "255.255.255.255";
37
+ const userName = (messageAttributes && messageAttributes.CurrentUserName) ? messageAttributes.CurrentUserName.StringValue : "system";
38
+ const ipaddress = (messageAttributes && messageAttributes.IPAddress) ? messageAttributes.IPAddress.StringValue : "255.255.255.255";
44
39
  if (entityId === undefined) {
45
40
  return;
46
41
  }
42
+
47
43
  console.log("Event Received : EntityId = " + entityId + ", Topic Name = " + subject +
48
44
  ", UserName = " + userName + ", IP Address = " + ipaddress);
49
45
 
50
-
51
46
  await this.auditLoggerService.addAuditLog(entityId, subject, message, userName, ipaddress, currentTime);
52
47
  } catch (error) {
53
48
  console.log(`AuditLogger - Logs Not Added due to Error : ${error}`);
54
49
  }
55
-
56
50
  }
57
-
58
51
  }
59
52
  module.exports = AuditLogger;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apf-node-common",
3
- "version": "1.0.112",
3
+ "version": "2.0.1",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -1,6 +1,5 @@
1
+ const { pathToRegexp } = require('path-to-regexp')
1
2
  const swaggerJSDoc = require('swagger-jsdoc');
2
- //const swaggerDefinition = require('./controllers/swaggerDefinition')
3
- const { pathToRegexp, match, parse, compile } = require('path-to-regexp')
4
3
 
5
4
  function authorize(req, res, options, httpContext, next) {
6
5
  console.log('AccessInterceptor -> authorize');
@@ -25,6 +24,32 @@ function authorize(req, res, options, httpContext, next) {
25
24
  next();
26
25
  }
27
26
 
27
+ /**
28
+ * Authorize request based on swagger specification
29
+ * @param {Object} req - Express request object
30
+ * @param {Object} res - Express response object
31
+ * @param {Object} swaggerSpec - Pre-parsed swagger/OpenAPI specification JSON
32
+ * @param {Object} httpContext - HTTP context with user information
33
+ * @param {Function} next - Express next function
34
+ */
35
+ function authorizeWithOpenApiJson(req, res, swaggerSpec, httpContext, next) {
36
+ console.log('AccessInterceptor -> authorize');
37
+
38
+ const swaggerJson = typeof swaggerSpec === 'string' ? JSON.parse(swaggerSpec) : swaggerSpec;
39
+ try {
40
+ const isAllowed = validateAccess(swaggerJson, req, httpContext, res);
41
+ if (isAllowed === false) {
42
+ return isAllowed
43
+ }
44
+ return true;
45
+
46
+ } catch (error) {
47
+ console.log(error);
48
+ return error;
49
+ }
50
+ next();
51
+ }
52
+
28
53
 
29
54
 
30
55
  function validateAccess(jsonData, request, httpContext, res) {
@@ -86,4 +111,5 @@ function getReplacePath(path) {
86
111
  str = str.replace(/}/g, '');
87
112
  return str
88
113
  }
89
- exports.authorize = authorize;
114
+ exports.authorize = authorize;
115
+ exports.authorizeWithOpenApiJson = authorizeWithOpenApiJson;
@@ -1,34 +1,27 @@
1
1
  const log = require('../../Logger').getLogger();
2
2
  const AWS = require('aws-sdk');
3
-
4
3
  const AWSSNSUtils = require('./AWSSNSUtils');
5
- const environment = (process.env.NODE_ENVIRONMENT || 'Test');
6
4
  const awsRegion = (process.env.AWS_DEFAULT_REGION || 'us-east-2');
7
-
8
5
  AWS.config.update({ region: awsRegion });
9
6
  const topicName = "Infrastructure-EmailHandler";
10
7
  const subject = 'Infrastructure-EmailHandler';
11
8
 
12
- var sns = new AWS.SNS();
9
+ module.exports = {
13
10
 
14
- module.exports = {
15
-
16
- async dispatchNotification(tagData, context) {
17
- const messageAttributes = getAttributs(context);
18
- await AWSSNSUtils.publish(topicName, subject, JSON.stringify(tagData),messageAttributes);
11
+ async dispatchNotification(tagData, context) {
12
+ const messageAttributes = getAttributes(context);
13
+ await AWSSNSUtils.publish(topicName, subject, JSON.stringify(tagData), messageAttributes);
19
14
  log.info('email notification published!!')
20
-
21
15
  }
22
16
  }
23
17
 
24
- function getAttributs(context) {
18
+ function getAttributes(context) {
25
19
  let messageAttributes = {};
26
- context.forEach((contextValue) =>{
27
- var value = {
28
- DataType : "String",
29
- StringValue : contextValue.Value
30
- }
31
- messageAttributes[contextValue.Key] = value;
20
+ context.forEach((contextValue) => {
21
+ messageAttributes[contextValue.Key] = {
22
+ DataType: "String",
23
+ StringValue: contextValue.Value
24
+ }
32
25
  });
33
26
 
34
27
  return messageAttributes;
@@ -1,36 +1,56 @@
1
1
  const log = require('../../Logger').getLogger();
2
2
  const AWS = require('aws-sdk');
3
-
4
3
  const environment = (process.env.NODE_ENVIRONMENT || 'Test');
5
4
  const awsRegion = (process.env.AWS_DEFAULT_REGION || 'us-east-2');
5
+ const awsAccountNumber = (process.env.AWS_ACCOUNT_NUMBER);
6
6
  AWS.config.update({ region: awsRegion });
7
- AuditLogger = require("../../auditlog/AuditLogger");
8
- var sns = new AWS.SNS({apiVersion: '2010-03-31'});
7
+ const AuditLogger = require("../../auditlog/AuditLogger");
8
+ var sns = new AWS.SNS({ apiVersion: '2010-03-31' });
9
9
 
10
10
  module.exports = {
11
+ async publish(topic, subject, message, messageAttributes) {
12
+ try {
13
+ let topicARN;
14
+ if (awsAccountNumber) {
15
+ topicARN = `arn:aws:sns:${awsRegion}:${awsAccountNumber}:${environment}-${topic}`;
16
+ }
17
+ else {
18
+ log.info("Calling CreateTopic" + topicARN);
19
+ const topicName = `${environment}-${topic}`;
20
+ var response = await sns.createTopic({ Name: topicName }).promise();
21
+ topicARN = response.TopicArn;
22
+ }
23
+ log.info("Topic ARN is " + topicARN);
24
+
25
+ let updatedMessageAttributes = getAttributes(messageAttributes);
11
26
 
12
- async publish(topic, subject, message,messageAttributes) {
13
- var arn = '';
14
- try{
15
- const topicName = `${environment}-${topic}`;
27
+ const snsParameters = {
28
+ Message: message,
29
+ MessageAttributes: updatedMessageAttributes,
30
+ Subject: subject,
31
+ TopicArn: topicARN
32
+ };
16
33
 
17
- var response = await sns.createTopic({ Name: topicName }).promise();
18
- arn = response.TopicArn;
19
- const snsParameters = {
20
- Message: message,
21
- MessageAttributes:messageAttributes,
22
- Subject: subject,
23
- TopicArn: arn
24
- };
25
- log.info("Topic ARN is " + arn);
26
- var data = await sns.publish(snsParameters).promise();
34
+ var data = await sns.publish(snsParameters).promise();
27
35
 
28
- log.info("MessageID is " + data.MessageId);
29
- let auditLogger = new AuditLogger();
30
- await auditLogger.audit(message, subject,messageAttributes);
31
- }catch(error){
32
- log.error(`error occured while publishing event ${subject} to SNS `)
33
- log.error(error, error.stack);
34
- }
36
+ log.info("MessageID is " + data.MessageId);
37
+ let auditLogger = new AuditLogger();
38
+ await auditLogger.audit(message, subject, updatedMessageAttributes);
39
+ } catch (error) {
40
+ log.error(`error occured while publishing event ${subject} to SNS `)
41
+ log.error(error, error.stack);
42
+ }
35
43
  }
44
+ }
45
+
46
+ function getAttributes(context) {
47
+ let messageAttributes = {};
48
+ context.forEach((contextValue) => {
49
+ messageAttributes[contextValue.Key] = {
50
+ DataType: "String",
51
+ StringValue: contextValue.Value
52
+ }
53
+ });
54
+
55
+ return messageAttributes;
36
56
  }