This repository has been archived by the owner on Apr 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
handler.js
91 lines (74 loc) · 2.91 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
'use strict';
var aws = require('aws-sdk');
var nodemailer = require('nodemailer');
var iam = new aws.IAM();
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
var mfaGroupName = 'MFA-enforced';
var mfaGroupUsers = [];
module.exports.handler = function(event, context) {
iam.getGroup({ GroupName: mfaGroupName }, function(err, data) {
if (err) console.log(err, err.stack);
else {
var mfaUsers = data.Users || [];
// Add users who are already in the group to an array
mfaUsers.forEach(function(user) {
mfaGroupUsers.push(user.UserName);
});
iam.listUsers({}, function(err, data) {
if (err)
console.log(err, err.stack);
else {
var allUsers = data.Users || [];
allUsers.forEach(function(user) {
// If the user has logged in to AWS Management Console atleast once and is not added to MFA-enabled group, add him
if ('PasswordLastUsed' in user && !mfaGroupUsers.includes(user.UserName)) {
console.log("Adding the user to MFA group : " + user.UserName);
var params = {
GroupName: mfaGroupName,
UserName: user.UserName
};
iam.addUserToGroup(params, function(err, data){
if (err) {
console.log(err, err.stack);
}
else {
console.log(user.UserName + " added to " + mfaGroupName + " group successfully.")
console.log(data);
if(!process.env.EMAIL || !process.env.PASSWORD) console.log("Bot email and username not set !");
if(validateEmail(user.UserName) && process.env.EMAIL && process.env.PASSWORD) {
var mailOptions = {
from: process.env.EMAIL,
to: user.UserName,
subject: process.env.EMAIL_SUBJECT,
html: process.env.EMAIL_BODY
};
transporter.sendMail(mailOptions, function(error, info){
if (error) console.log(error);
else console.log('Email sent: ' + info.response);
});
} else {
console.log("Email not sent to user: " + user.UserName);
}
}
});
}
});
// Clear all the users in mfaGroupUsers
mfaGroupUsers = [];
}
});
}
});
}
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}