Add user to group
You can use defineAuth
and defineFunction
to create a Cognito post confirmation Lambda trigger that extends the behavior to perform some action when a user is confirmed.
To get started, install the AWS SDK v3 package, which will be used to perform actions against your auth resource, and the @types/aws-lambda
package, which is used to define the handler type:
npm add --save-dev @aws-sdk/client-cognito-identity-provider @types/aws-lambda
Next, create a new directory and a resource file, amplify/auth/post-confirmation/resource.ts
. Then, define the Function with defineFunction
:
import { defineFunction } from '@aws-amplify/backend';
export const postConfirmation = defineFunction({ name: 'post-confirmation', // optionally define an environment variable for your group name environment: { GROUP_NAME: 'EVERYONE' }});
After creating the Function definition you will need to:
- create the
EVERYONE
group - grant access to your auth resource to ensure it can perform the
addUserToGroup
action - set the Function as the post confirmation trigger
import { defineAuth } from "@aws-amplify/backend";import { postConfirmation } from "./post-confirmation/resource"
export const auth = defineAuth({ loginWith: { email: true, }, groups: ["EVERYONE"], triggers: { postConfirmation, }, access: (allow) => [ allow.resource(postConfirmation).to(["addUserToGroup"]), ],})
Then create the Function's corresponding handler file, amplify/auth/post-confirmation/handler.ts
, file with the following contents:
import type { PostConfirmationTriggerHandler } from 'aws-lambda';import { CognitoIdentityProviderClient, AdminAddUserToGroupCommand} from '@aws-sdk/client-cognito-identity-provider';import { env } from '$amplify/env/post-confirmation';
const client = new CognitoIdentityProviderClient();
// add user to groupexport const handler: PostConfirmationTriggerHandler = async (event) => { const command = new AdminAddUserToGroupCommand({ GroupName: env.GROUP_NAME, Username: event.userName, UserPoolId: event.userPoolId }); const response = await client.send(command); console.log('processed', response.$metadata.requestId); return event;};
After deploying the changes, whenever a user signs up and verifies their account they are automatically added to the group named "EVERYONE".