|
| 1 | +import { PROFILE_SVC_GITHUB_URL } from "../constants/urls"; |
| 2 | +import {addUserToGroup, createUser, fetchAwsUserIdByUsername} from "../utils/awsFunctions"; |
| 3 | +const dataAccess = require("../services/dataAccessLayer"); |
| 4 | +const userDataLevels = require('../constants/userDataLevels'); |
| 5 | + |
| 6 | +export const addUserToAWSGroup = async (req, res) => { |
| 7 | + const { groupId, userId } = req.body; |
| 8 | + |
| 9 | + try { |
| 10 | + const userInfoData = await dataAccess.retrieveUsers({ discordId: userId, level: userDataLevels.ACCESS_LEVEL.INTERNAL, role: 'cloudfare_worker'}); |
| 11 | + if (!userInfoData.userExists) { |
| 12 | + return res.status(400).json({ error: "User not found" }); |
| 13 | + } else if(!userInfoData.user.email) { |
| 14 | + return res.status(400).json({ error: `User email is required to create an AWS user. Please update your email by setting up Profile service, url : ${PROFILE_SVC_GITHUB_URL}` }); |
| 15 | + } |
| 16 | + |
| 17 | + let awsUserId = await fetchAwsUserIdByUsername(userInfoData.user.username); |
| 18 | + |
| 19 | + let userCreationResponse = null; |
| 20 | + |
| 21 | + if (awsUserId === null){ |
| 22 | + // We need to create the user in AWS before and then fetch its Id |
| 23 | + userCreationResponse = await createUser(userInfoData.user.username, userInfoData.user.email); |
| 24 | + awsUserId = userCreationResponse.UserId; |
| 25 | + } |
| 26 | + |
| 27 | + let userAdditionResponse = await addUserToGroup(groupId, awsUserId) |
| 28 | + |
| 29 | + if (userAdditionResponse){ |
| 30 | + if (userAdditionResponse.conflict){ |
| 31 | + return res.status(200).json({ |
| 32 | + message: `User ${userId} is already part of the AWS group, please try signing in.` |
| 33 | + }) |
| 34 | + } else { |
| 35 | + return res.status(200).json({ |
| 36 | + message: `User ${userId} successfully added to group ${groupId}.` |
| 37 | + }); |
| 38 | + } |
| 39 | + } |
| 40 | + } catch (error) { |
| 41 | + logger.error(`Error in adding user - ${userId} to AWS group - ${groupId} error - ${error}`); |
| 42 | + return res.status(500).json({ |
| 43 | + error: `Something went wrong, please try again` |
| 44 | + }); |
| 45 | + } |
| 46 | +}; |
0 commit comments