create-aws-iam-users / server / server.js
server.js
Raw
const express = require("express")
const cors = require("cors")
const { IAMClient, ListGroupsCommand, ListUsersCommand, CreateUserCommand, CreateGroupCommand, CreateAccessKeyCommand, AddUserToGroupCommand } = require("@aws-sdk/client-iam")

const PORT = 3333 || process.env.PORT
const app = express()
const client = new IAMClient({ region: "us-east-1" });

app.use(cors())
app.use(express.json())
app.use(express.urlencoded({extended:true}))

let userId
let accessKeyId
let secretAccessKey
app.post('/add-user', (req, res) => {
    //console.log(req.body)
    const userParams = {
        UserName: req.body.username
    }

    const createGroupParams = {
        GroupName: req.body.group
    }

    const addToGroupParams = {
        GroupName: req.body.group,
        UserName: req.body.username
    }
    const createUsercommand = new CreateUserCommand(userParams)
    client.send(createUsercommand)
    .then((createUserResponse) => {
        // process data.
        console.log('user added:', createUserResponse)
        userId = createUserResponse.User.UserId
        const keyCommand = new CreateAccessKeyCommand(userParams)
        client.send(keyCommand)
        .then((createKeyResponse) => {
            console.log('key created:', createKeyResponse)
            accessKeyId = createKeyResponse.AccessKey.AccessKeyId
            secretAccessKey = createKeyResponse.AccessKey.SecretAccessKey
            console.log('user details:', userId, accessKeyId, secretAccessKey)
            // Check if group already exist
            const listGroupsCommand = new ListGroupsCommand({MaxItems: 10,})
            client.send(listGroupsCommand)
            .then((listGroupsResponse) => {
                console.log('listGroupsResponse:', listGroupsResponse.Groups)
                const iamGroup = listGroupsResponse.Groups.find((group) => group.GroupName === req.body.group)
                /*let containsGroup = false
                for (const group of listGroupsResponse.Groups) {
                    if (group.GroupName === req.body.group) {
                        containsGroup = true;
                        break;
                    }
                }
                console.log('containsGroup', containsGroup)*/
                if (iamGroup) {
                    // simply add user to the group
                    const addToGroupCommand = new AddUserToGroupCommand(addToGroupParams)
                    client.send(addToGroupCommand)
                    .then((addToGroupResponse) => {
                        console.log('addToGroupResponse:', addToGroupResponse)
                        res.status(200).json({message: "user_added"})
                        // Send email to user...
                    })
                    .catch((error) => {
                        console.log('addToGroupError:', error)
                        res.status(500).json({message: "server_error"})
                    })
                }else {
                    // create group and add user to it
                    const createGroupCommand = new CreateGroupCommand(createGroupParams)
                    client.send(createGroupCommand)
                    .then((createGroupResponse) => {
                        console.log('createGroupResponse:', createGroupResponse)
                        const addToGroupCommand = new AddUserToGroupCommand(addToGroupParams)
                        client.send(addToGroupCommand)
                        .then((addToGroupResponse) => {
                            console.log('addToGroupResponse:', addToGroupResponse)
                            res.status(200).json({message: "user_added"})
                            // Send email to user...
                        })
                        .catch((error) => {
                            console.log('addToGroupError:', error)
                            res.status(500).json({message: "server_error"})
                        })
                    })
                    .catch((error) => {
                        console.log('createGroupError:', error)
                        res.status(500).json({message: "server_error"})
                    })
                }
            })
            .catch((error) => {
                console.log('listGroupError:', error)
            })
        })
        .catch((error) => {
            console.log('key creation error:', error)
            res.status(500).json({message: "server_error"})
        })
    })
    .catch((error) => {
        // error handling.
        console.log('create user error:', error)
        error.Error.Code == 'EntityAlreadyExists' ? res.status(400).json({message: "user_exist"}) : res.status(500).json({message: "server_error"})
    })
    .finally(() => {
        // finally.
    });
})

app.get('/list-groups', (req, res) => {
    const listGroupsCommand = new ListGroupsCommand({MaxItems: 10,})
    client.send(listGroupsCommand)
    .then((listGroupsResponse) => {
        console.log(listGroupsResponse)
        res.send(listGroupsResponse.Groups)
    })
    .catch((error) => {
        console.log('listGroupError:', error)
    })
})

app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`)
})