-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
191 lines (167 loc) · 5.11 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/* Amplify Params - DO NOT EDIT
API_WEB_GRAPHQLAPIENDPOINTOUTPUT
API_WEB_GRAPHQLAPIIDOUTPUT
ENV
REGION
Amplify Params - DO NOT EDIT *//* Amplify Params - DO NOT EDIT
API_WEB_GRAPHQLAPIENDPOINTOUTPUT
API_WEB_GRAPHQLAPIIDOUTPUT
ENV
REGION
Amplify Params - DO NOT EDIT */
import crypto from '@aws-crypto/sha256-js';
import { defaultProvider } from '@aws-sdk/credential-provider-node';
import { SignatureV4 } from '@aws-sdk/signature-v4';
import { HttpRequest } from '@aws-sdk/protocol-http';
import { default as fetch, Request } from 'node-fetch';
import {
SQSClient,
SendMessageCommand,
DeleteMessageCommand
} from "@aws-sdk/client-sqs";
const GRAPHQL_ENDPOINT = process.env.API_WEB_GRAPHQLAPIENDPOINTOUTPUT;
const AWS_REGION = process.env.REGION;
const ENV = process.env.ENV;
const { Sha256 } = crypto;
const sqsClient = new SQSClient({ region: AWS_REGION })
const URLS = {
createAppUserQueue: `https://sqs.us-west-1.amazonaws.com/213993515054/CreateAppUser-${ENV}`,
createConsentQueue: `https://sqs.us-west-1.amazonaws.com/213993515054/CreateConsent-${ENV}`,
createSignupQueue: `https://sqs.us-west-1.amazonaws.com/213993515054/CreateSignup-${ENV}`
}
const createRequest = (endpoint, query, variables) => new HttpRequest({
method: 'POST',
headers: {
'Content-Type': 'application/json',
host: endpoint.host
},
hostname: endpoint.host,
body: JSON.stringify({ query: query, variables: variables }),
path: endpoint.pathname
});
export const createUserMutation = /* GraphQL */ `
mutation CreateUser(
$input: CreateUserInput!
$condition: ModelUserConditionInput
) {
createUser(input: $input, condition: $condition) {
id
cognitoID
owner
createdAt
updatedAt
_version
_deleted
_lastChangedAt
__typename
}
}
`;
const graphqlOperation = async (query, variables) => {
const endpoint = new URL(GRAPHQL_ENDPOINT);
const signer = new SignatureV4({
credentials: defaultProvider(),
region: AWS_REGION,
service: 'appsync',
sha256: Sha256
});
const requestToBeSigned = createRequest(endpoint, query, variables)
const signed = await signer.sign(requestToBeSigned);
const request = new Request(endpoint, signed);
let statusCode = 200;
let body;
let response;
try {
response = await fetch(request);
body = await response.json();
if (body.errors) {
statusCode = 400;
console.error(`${statusCode} ERROR: ${JSON.stringify(body.errors)}`);
}
} catch (error) {
statusCode = 500;
console.error(`${statusCode} ERROR: ${error.message}`);
}
return body;
}
/**
* @type {import('@types/aws-lambda').APIGatewayProxyHandler}
*/
export const handler = async (event) => {
const { body, receiptHandle } = event.Records[0]
const bodyObj = JSON.parse(body)
const {
cognitoUser,
consentsToTermsAndConditions,
email,
firstName,
lastName,
sourceIp,
userAgent
} = bodyObj;
let user
// create user in dynamoDB
try {
const userVariables = {
input: {
cognitoID: cognitoUser.UserSub,
owner: cognitoUser.UserSub
}
};
const response = await graphqlOperation(createUserMutation, userVariables)
user = response.data.createUser;
} catch (error) {
console.error("creating user:", error.message);
}
// delete message from queue
try {
const deleteMessageInput = {
QueueUrl: URLS.createAppUserQueue,
ReceiptHandle: receiptHandle
}
const deleteMessageCommand = new DeleteMessageCommand(deleteMessageInput)
await sqsClient.send(deleteMessageCommand)
} catch (error) {
console.error("deletiing message from CreateAppUser queue")
}
// Send user info to CreateConsent queue
try {
const createConsentInput = {
QueueUrl: URLS.createConsentQueue,
MessageBody: JSON.stringify({
userID: user.id,
owner: cognitoUser.UserSub,
termsAndConditionsVersions: "",
IPAddress: sourceIp,
// NOTE: For some strange reason JSON.stringfy can't handle es6 object property shorthand, hence the redundancy below.
consentsToTermsAndConditions: consentsToTermsAndConditions,
userAgent: userAgent
})
}
const createConsentCommand = new SendMessageCommand(createConsentInput)
await sqsClient.send(createConsentCommand)
} catch (error) {
console.error(`sending to createAppUser queue: ${error.message}`)
return { statusCode: 400 }
}
// Send user info to CreateSignup queue
try {
const createSignupInput = {
QueueUrl: URLS.createSignupQueue,
MessageBody: JSON.stringify({
cognitoID: cognitoUser.UserSub,
userID: user.id,
// NOTE: For some strange reason JSON.stringfy can't handle es6 object property shorthand, hence the redundancy below.
email: email,
firstName: firstName,
lastName: lastName,
})
}
const createSignupCommand = new SendMessageCommand(createSignupInput)
await sqsClient.send(createSignupCommand)
} catch (error) {
console.error(`sending to createAppUser queue: ${error.message}`)
return { statusCode: 400 }
}
return { statusCode: 201 };
};