Error adding a user to a group after post confirmation in Cognito

1.2k views Asked by At

I have created a userpool in Cognito.

What I would like to do is when a new user tries to sign-up using the UI, he gets a verification code. Once the user enters the code, a Post confirmation lambda must be triggered and it must add this newly created user directly to a group named users.

I found admin_add_user_to_group client and wrote the following code and deployed it as a lambda:

import boto3
import hmac
import hashlib
import base64

USER_POOL_ID = ''
CLIENT_ID = ''
CLIENT_SECRET = ''


def lambda_handler(event, context):
    client = boto3.client('cognito-idp')
    try:
        username = event['username']

        response = client.admin_add_user_to_group(
            UserPoolId=USER_POOL_ID,
            Username=username,
            GroupName='users'
        )
    except client.exceptions.InvalidParameterException:
        return {"error": True, "success": False, "message": "Username doesnt exists"}
        
    except client.exceptions.ResourceNotFoundException:
        return {"error": True, "success": False, "message": "Invalid Verification code"}

    except client.exceptions.NotAuthorizedException:
        return {"error": True, "success": False, "message": "User is already confirmed"}

    except Exception as e:
        return {"error": True, "success": False, "message": f"Unknown error {e.__str__()} "}

    return event

After deploying the code, I connected it to the Post confirmation trigger. Now, when the user tries to sign-up, a code is sent. But, when I paste the code to confirm the user two things happen:

  1. The user gets confirmed but,
  2. The user isn't added to the users group.

It shows the following error:

enter image description here

What is the mistake that I am committing?

1

There are 1 answers

0
Noel Llevares On BEST ANSWER

The post-confirmation has to return the event, always.

In your code, you are catching errors and then not returning the event.

So, what happened is that your code caught one of those errors and did not return the event.