-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.js
222 lines (190 loc) · 5.33 KB
/
handler.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
'use strict';
let AWS = require("aws-sdk")
let crypto = require("crypto")
let uuid = require("uuid/v4")
let tenants = require("./api/lib/tenants")
var sp = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});
const CLIENT_ID = process.env.clientId;
const USER_POOL_ID = process.env.userPoolId;
const USAGE_PLAN_ID = process.env.usagePlanId;
const USER_TYPE = process.env.userType;
const REGION = process.env.region;
const isNetvote = () => {
return USER_TYPE === "netvote";
}
const attr = (name, value) => {
return {
Name: name,
Value: value
}
}
const errorResp = (code, message) => {
return {
statusCode: code,
body: JSON.stringify({
message: message,
}),
};
}
const toHtml = (obj) => {
let keys = Object.keys(obj);
let result = ""
for(let i=0; i<keys.length; i++){
let k = keys[i];
let v = obj[k];
result += `${k}: ${v}<br/>`
}
return result;
}
const sendEmailToSupport = async (user) => {
// Create sendEmail params
const params = {
Destination: {
ToAddresses: ["[email protected]","[email protected]"]
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: toHtml(user)
}
},
Subject: {
Charset: "UTF-8",
Data: `Citizen Data Signup: ${user.email}`
}
},
Source: "[email protected]"
};
await new AWS.SES({ apiVersion: "2010-12-01" }).sendEmail(params).promise();
}
const generatePassword = async () => {
return new Promise((resolve, reject) => {
crypto.randomBytes(48, function(err, buffer) {
resolve(buffer.toString('hex'));
});
})
}
const createApiKey = async (name) => {
var apigateway = new AWS.APIGateway({region: REGION });
let res = await apigateway.createApiKey({enabled: true, name: name}).promise();
let params = {
keyId: res.id,
keyType: "API_KEY",
usagePlanId: USAGE_PLAN_ID
}
apigateway.createUsagePlanKey()
await apigateway.createUsagePlanKey(params).promise();
return res;
}
const loginWithUser = async (username, password) => {
var authParams = {
USERNAME : username,
PASSWORD : password,
};
let params = {
UserPoolId: USER_POOL_ID,
ClientId: CLIENT_ID,
AuthFlow: "ADMIN_NO_SRP_AUTH",
AuthParameters: authParams
}
return await sp.adminInitiateAuth(params).promise();
}
const updatePassword = async (username, tempPass) => {
let newPassword = await generatePassword();
let challenge = await loginWithUser(username, tempPass);
await sp.adminRespondToAuthChallenge({
Session: challenge.Session,
ChallengeName: challenge.ChallengeName,
ClientId: CLIENT_ID,
UserPoolId: USER_POOL_ID,
ChallengeResponses: {
USERNAME: username,
NEW_PASSWORD: newPassword
}
}).promise()
return newPassword;
}
module.exports.postCreateNetvoteAdminUser = async (event, context, callback) => {
console.log(event);
if(!event.request.userAttributes["custom:company"]){
let emailAddress = event.request.userAttributes["email"];
let tenantId = await tenants.createNewTenant(emailAddress);
await sp.adminUpdateUserAttributes({
Username: event.userName,
UserAttributes: [{Name: "custom:company", Value: tenantId}],
UserPoolId: USER_POOL_ID
}).promise()
// copy attributes and append tenantId
let attrs = JSON.parse(JSON.stringify(event.request.userAttributes));
attrs["custom:company"] = tenantId;
await sendEmailToSupport(attrs)
}
callback(null, event);
}
module.exports.createNetvoteAdminUser = async (event, context) => {
if(!event.username) {
return errorResp(400, "username is required");
}
if(!event.name){
return errorResp(400, "name is required");
}
if(!event.email){
return errorResp(400, "email is required");
}
if(!event.company){
return errorResp(400, "company is required");
}
let attrs = [
attr("name", event.name),
attr("email", event.email),
attr("custom:company", event.company)
]
await sp.adminCreateUser({
UserPoolId: USER_POOL_ID,
Username: event.username,
UserAttributes: attrs
}).promise();
}
module.exports.createApiUser = async (event, context) => {
if(!event.name){
return errorResp(400, "name is required");
}
if(!event.email){
return errorResp(400, "email is required");
}
if(!event.company){
return errorResp(400, "company is required");
}
let mainnet = event.mainnet || 0;
let username = uuid();
let tempPass = await generatePassword();
let apiKey = await createApiKey(event.email);
let attrs = [
attr("name", event.name),
attr("email", event.email),
attr("custom:company", event.company),
attr("custom:mainnet", `${mainnet}`),
attr("custom:apikey", apiKey.id)
]
await sp.adminCreateUser({
UserPoolId: USER_POOL_ID,
Username: username,
TemporaryPassword: tempPass,
MessageAction: "SUPPRESS",
UserAttributes: attrs
}).promise();
await sp.adminAddUserToGroup({
GroupName: "admin",
Username: username,
UserPoolId: USER_POOL_ID
}).promise();
let password = await updatePassword(username, tempPass);
return {
apiKey: apiKey.value,
id: username,
secret: password
}
// Use this code if you don't use the http event with the LAMBDA-PROXY integration
// return { message: 'Go Serverless v1.0! Your function executed successfully!', event };
};