Cognito user migration exception: Exception migrating user in app client...

0

Hi,
I need to migrate users from FireBase to AWS Cognito. I created a lambda function and created a user pool, for created pool i added a user migration trigger.
Now when I try to login in our Angular 5.2.6 app, I got an error:
code:"UserNotFoundException"
message:"Exception migrating user in app client 46juj1av7crqkr7a09g04vkr8r"
name:"UserNotFoundException"

Bellow is my lambda function developed using serverless+node-ts template

import { APIGatewayEvent, Callback, Context, Handler } from 'aws-lambda';
import * as firebase from 'firebase';
import { UsersManager } from './AuthManager/UsersManager';

export const signin: Handler = async (event: APIGatewayEvent, context: Context, cb: Callback) => {
  try {
    var config = {
     ...
    };
    console.log(event);
    var manager = new UsersManager(config);
    await manager.signIn(event, context, cb);
    cb(null, event);
  } catch (e) {
    console.error(e);
     cb(e, event);
  }
}

event object contains following data after call await manager.signIn(event, context, cb); :
{ version: '1',
triggerSource: 'UserMigration_Authentication',
region: 'us-east-1',
userPoolId: 'YYYYYYY',
userName: 'my@emal.com',
callerContext:
{ awsSdkVersion: 'aws-sdk-unknown-unknown',
clientId: 'XXXXX' },
request: { password: 'passwd', userAttributes: null },
response:
{ userAttributes: { email: 'my@emal.com', email_verified: 'true' },
forceAliasCreation: false,
finalUserStatus: 'CONFIRMED',
messageAction: 'SUPPRESS',
desiredDeliveryMediums: 'EMAIL' } }

What I'm doing wrong? Is ther any issue in code or maybe i forget something to cofigure?..
Thanks for help!

asked 6 years ago1512 views
8 Answers
1

I resolved this problem.

User Migration Lambda needs to have the permission which allows invoking by cognito-idp.

Configuring by Management Console, the permission is appended implicitly.
However, by CloudFormation, we need to append the permission manually.

Finally, My CloudFormation about permission is like this.

  PermissionToInvokeUserPoolMigration:  
    Type: AWS::Lambda::Permission  
    Properties:  
      FunctionName: !Ref UserPoolMigrationFunction  
      Action: lambda:InvokeFunction  
      Principal: cognito-idp.amazonaws.com  
      SourceArn: !Sub arn:aws:cognito-idp:${AWS::Region}:${AWS::AccountId}:userpool/${UserPoolId}  
hiroga
answered 5 years ago
  • This is a very valid answer, and applied to me.

1

We are experiencing the same issue. We are using CloudFormation to build the UserPool and User Migration Lambda and attaching them using the aws cli.

When we build a User pool through the console and attached our User Migration Trigger it worked.

Update ----------------------------

We resolved this issue by ensuring our PreSignUp Lambda Trigger could handle the "PreSignUp_AdminCreateUser" event trigger source.

It turns out that when the UserMigration Lambda function exits successfully, Cognito then "creates the user", which in turn calls the PreSignUp trigger (if one is configured).

This is definitely not clear in the documentation.

Edited by: alexf-noths on Mar 9, 2018 7:39 AM

answered 6 years ago
1

After hours of investigation I found that we got this error message when the User migration Lambda memory size was set too low at 128mb. Even though the cloudwatch logs showed that it was nowhere near memory limits and from all evidence in the logs exited successfully. Upping the memory limit resolved it.

gev1695
answered 4 years ago
0

So if PreSignUp trigger is not configured Cognito can't migrate user?

answered 6 years ago
0

I've managed to successfully migrate a user without the PreSignUp lambda. It's not mandatory for User Migration.

answered 6 years ago
0

Here is the problem statement:

https://stackoverflow.com/questions/52074717/aws-cognito-user-migration-exception-during-user-migration

can you share step - by - step information on User Migration followed as i have followed as per the documentation and still facing issue with Exception during user migration

Edited by: kkanand on Aug 29, 2018 3:38 PM

kkanand
answered 6 years ago
0

User hiroga is correct, changing User Migration Lambda memory from default 128MB to 256MB, fixed this issue, this should me marked as correct answer.
Also AWS should finally fix error messages in Cognito and Lambda invocations.

kgawrys
answered 3 years ago
0

Hi ! i am also facing the exact same error even after increasing the timeout and the memory size. I also set all my permissions for the function to be ran properly. No error logs are helpful and nothing in the documentation points at i could have done wrong.

Here is my code :

const handler: UserMigrationTriggerHandler = async (
	event,
	context,
	callback
) => {
	const triggerSource = event.triggerSource;
	console.log(`[TRIGGER_SOURCE] ${triggerSource}`);

	if (triggerSource == 'UserMigration_Authentication') {
                // We try to find the user into an old cognito user pool.
                // If we find the user we will migrate this user into the current user pool
		const auth = await authenticateUserCognito({
			username: event.userName,
			password: event.request.password,
		});
		let user: {} | null = null;

		if (auth) {
			user = await getCognitoUser(auth);
		}

		if (user && userHasAllProps(user)) {
			console.log('User has all props. Resume');
			event.response.userAttributes = user;
			event.response.finalUserStatus = EVENT_USER_STATUS_CONFIRMED;
			event.response.messageAction = EVENT_MESSAGE_ACTION_SUPPRESS;
			context.succeed(event);
		} else {
			try {
				const djangoUser = await authenticateUser({
					email: event.userName,
					password: event.request.password,
				});

				if (!djangoUser) {
					const errorMessage = 'Django user not found';
					Bugsnag.notify(new Error(errorMessage), (e) => {
						e.context = `User: ${event.userName}`;
					});
					return callback(errorMessage);
				}

				console.log(djangoUser);

				if (!user) {
					user = {
						email: event.userName,
						'custom:first_name': djangoUser.first_name,
						'custom:last_name': djangoUser.last_name,
						'custom:date_of_birth': djangoUser.date_of_birth || '',
						'custom:user_id': `user::${djangoUser.id}`,
						email_verified: 'true',
					};
				} else {
					user['custom:first_name'] = djangoUser.first_name;
					user['custom:last_name'] = djangoUser.last_name;
					user['custom:date_of_birth'] = djangoUser.date_of_birth || '';
					user['custom:user_id'] = `user::${djangoUser.id}`;
				}

				console.log(user);

				await migrateFromDjango({
					email: event.userName,
					existingUser: djangoUser,
				});

				event.response.userAttributes = user;
				event.response.finalUserStatus = EVENT_USER_STATUS_CONFIRMED;
				event.response.messageAction = EVENT_MESSAGE_ACTION_SUPPRESS;
				context.succeed(event);
			} catch (ex) {
				console.log(ex);
				const errorMessage = 'Error while trying to migrate user';
				Bugsnag.notify(new Error(errorMessage), (e) => {
					e.context = ex.message;
				});
				callback(errorMessage);
			}
		}
	} else if (triggerSource == 'UserMigration_ForgotPassword') {
		const user = await adminGetCognitoUser({
			email: event.userName,
		});

		if (user) {
			event.response.userAttributes = user;
			event.response.finalUserStatus = EVENT_USER_STATUS_CONFIRMED;
			event.response.messageAction = EVENT_MESSAGE_ACTION_SUPPRESS;
			context.succeed(event);
		} else {
			const errorMessage = 'Cognito user not found';
			Bugsnag.notify(new Error(errorMessage), (e) => {
				e.context = `User: ${event.userName}`;
			});
			callback(errorMessage);
		}
	} else {
		// Return error to Amazon Cognito
		callback(`Invalid triggerSource : ${triggerSource}`);
	}
};

Any idea what i could have done wrong ?

answered 3 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions