If you call the sign_up API (AWS Cognito) using Python3, you can use the following code.
def registerUser(userObj): ''' Registers the user to AWS Cognito. ''' # Mobile number is not a mandatory field. if(len(userObj['user_mob_no']) == 0): mobilenumber = '' else: mobilenumber = userObj['user_country_code']+userObj['user_mob_no'] secretKey = bytes(settings.SOCIAL_AUTH_COGNITO_SECRET, 'latin-1') clientId = settings.SOCIAL_AUTH_COGNITO_KEY digest = hmac.new(secretKey, msg=(userObj['user_name'] + clientId).encode('utf-8'), digestmod=hashlib.sha256 ).digest() signature = base64.b64encode(digest).decode() client = boto3.client('cognito-idp', region_name='eu-west-1' ) try: response = client.sign_up( ClientId=clientId, Username=userObj['user_name'], Password=userObj['password1'], SecretHash=signature, UserAttributes=[ { 'Name': 'given_name', 'Value': userObj['given_name'] }, { 'Name': 'family_name', 'Value': userObj['family_name'] }, { 'Name': 'email', 'Value': userObj['user_email'] }, { 'Name': 'phone_number', 'Value': mobilenumber } ], ValidationData=[ { 'Name': 'email', 'Value': userObj['user_email'] }, ] , AnalyticsMetadata={ 'AnalyticsEndpointId': 'string' }, UserContextData={ 'EncodedData': 'string' } ) except ClientError as error: return {"errorcode": error.response['Error']['Code'] } except Exception as e: return {"errorcode": "Something went wrong. Try later or contact the admin" } return {"success": "User registered successfully. "}
error.response ['Error'] ['Code'] will be InvalidPasswordException, UsernameExistsException, etc. Thus, in the main function or in the place where you call the function, you can write logic to provide a meaningful message to the user.
Example for the answer (error.response):
{ "Error": { "Message": "Password did not conform with policy: Password must have symbol characters", "Code": "InvalidPasswordException" }, "ResponseMetadata": { "RequestId": "c8a591d5-8c51-4af9-8fad-b38b270c3ca2", "HTTPStatusCode": 400, "HTTPHeaders": { "date": "Wed, 17 Jul 2019 09:38:32 GMT", "content-type": "application/x-amz-json-1.1", "content-length": "124", "connection": "keep-alive", "x-amzn-requestid": "c8a591d5-8c51-4af9-8fad-b38b270c3ca2", "x-amzn-errortype": "InvalidPasswordException:", "x-amzn-errormessage": "Password did not conform with policy: Password must have symbol characters" }, "RetryAttempts": 0 } }
For further reference: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-idp.html#CognitoIdentityProvider.Client.sign_up