So I need to display a list of users as well as their individual groups in a custom admin screen for a client. I'm returning the results of AWS.CognitoIdentityServiceProvider.listUsers in a Lambda function and that's listing users fine, but I'm not sure on the best way to fetch the groups for each user and add them to the response.
It seems a bit surprising to me that they don't provide a listUsers like method that includes that information, personally, as it seems like it would be a common use case. Has anyone tackled this problem before? I have a solution that's working but it seems hacky and likely isn't that performant, so I'm looking for something more efficient.
It seems my options are either fetching each group in the user pool and calling AWS.CognitoIdentityServiceProvider.listUsersInGroup for each of them, then looping through all users from listUsers and checking if they're in any of those groups, or looping through each user in the response from listUsers and calling AWS.CognitoIdentityServiceProvider.adminListGroupsForUser for each of them. Are these my only options? The first option seems marginally more efficient as there will be fewer groups than users so it'll result in fewer API calls, but it just seems like this is still crazily inefficient.
According to the documentation, I would go with following solution:
AWS.CognitoIdentityServiceProvider.listGroupsCode Example:
const AWS = require('aws-sdk')
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});
const USER_POOL_ID = 'region_XXXXXXXXX'
var params = {
UserPoolId: USER_POOL_ID, /* required */
};
cognitoidentityserviceprovider.listGroups(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log('Groups list:')
data.Groups.map(groups => {
console.log(groups.GroupName)
})
data.Groups.map( groupEntity => {
var params = {
GroupName: groupEntity.GroupName, /* required */
UserPoolId: USER_POOL_ID, /* required */
};
cognitoidentityserviceprovider.listUsersInGroup(params, function(err1, data1) {
if (err1) console.log(err1, err1.stack); // an error occurred
else {
console.log(`${groupEntity.GroupName} has ${data1.Users.length} users`);
data1.Users.map(userEntity => {
console.log(userEntity.Username)
})
}
});
})
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With