-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (86 loc) · 3.38 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// const {"v4": uuidv4} = require('uuid');
var AWS = require('aws-sdk');
var dynamo = new AWS.DynamoDB();
exports.handler = function (event, context, callback) {
let cognitoSub = event.cognitoSub;
let cognitoUser
if (!cognitoSub){
cognitoUser = decodeJWT(event.jwtToken);
cognitoSub = cognitoUser.sub
}
const userid = event.pid;
if (userid === cognitoSub){
dynamo.getItem({
TableName: 'TI-PUser-Loc',
Key: {
PUser: {
S: userid
},
LocId: {
S: 'self'
}
}
}, function (err,userloc) {
if (err === null){
dynamo.query({
TableName: 'TI-TargetedDonations',
IndexName: 'LocIdProj-index',
ProjectionExpression: 'DonationId, Donation, #S ',
ExpressionAttributeNames: {'#S': 'Status'},
KeyConditionExpression: 'LocId = :locid and #S = :status ',
ExpressionAttributeValues: {':locid': {S: userloc.Item.Location .S }, ':status' : { S: 'open'}}
}, function (err, data) {
handleIdQuery(err, data, callback, [], userloc);
});
} else {
console.log(err);
callback('inactive')
}
})
} else {
callback('forbidden');
}
};
function decodeJWT(jwt){
if (!jwt) return {};
const buff = Buffer.from(jwt, 'base64');
const text = buff.toString('utf-8');
let firstObj = text.indexOf('}')+1; // address : { formated:
let second = text.indexOf('}',firstObj)+1;
second = text.indexOf('}',second)+1;
const wHeader = text.substring(firstObj, second);
console.log(wHeader);
return JSON.parse(wHeader)
}
function handleIdQuery(err, data, callback, donations, userloc) {
if (err === null) {
data.Items.forEach(function (item) {
console.log(item,item.Donation);
const donation = JSON.parse(item['Donation'].S);
donations.push({
id: item.DonationId.S,
status: item.Status.S,
gadget: donation.gadget,
loc: donation.loc
}
);
});
if (data.LastEvaluatedKey) {
dynamo.query({
TableName: 'TI-TargetedDonations',
IndexName: 'LocIdProj-index',
ProjectionExpression: 'DonationId, Donation, #S ',
ExpressionAttributeNames: {'#S': 'Status'},
KeyConditionExpression: 'LocId = :locid and #S = :status ',
ExclusiveStartKey: data.LastEvaluatedKey,
ExpressionAttributeValues: {':locid': {S: userloc.Item.Location .S }, ':status' : { S: 'open'}}
}, function (err, data) {
handleIdQuery(err, data, callback, donations, userloc);
});
} else {
callback(null, {donations: donations});
}
} else {
callback(err);
}
}