Last active
July 2, 2025 03:59
-
-
Save SevanBadal/f37bae7a082b2e9d115a2580e2ae303b to your computer and use it in GitHub Desktop.
AWS Amplify Gen 2 Create User Custom Mutation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // amplify/data/backend.ts | |
| import { type ClientSchema, a, defineData } from "@aws-amplify/backend"; | |
| import { createUserResolver } from "../functions/create-user-resolver/resource"; | |
| const schema = a.schema({ | |
| // Custom mutation for creating users | |
| createUser: a | |
| .mutation() | |
| .arguments({ | |
| email: a.string().required(), | |
| firstName: a.string().required(), | |
| lastName: a.string().required(), | |
| temporaryPassword: a.string().required(), | |
| }) | |
| .returns( | |
| a.customType({ | |
| success: a.boolean().required(), | |
| message: a.string().required(), | |
| user: a.customType({ | |
| username: a.string(), | |
| email: a.string(), | |
| status: a.string(), | |
| }), | |
| }) | |
| ) | |
| .authorization((allow) => [allow.authenticated()]) | |
| .handler(a.handler.function(createUserResolver)), | |
| }); | |
| export type Schema = ClientSchema<typeof schema>; | |
| export const data = defineData({ | |
| schema, | |
| authorizationModes: { | |
| defaultAuthorizationMode: "iam", | |
| }, | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // amplify/backend | |
| const backend = defineBackend({ | |
| auth, | |
| data, | |
| createUser, | |
| createUserResolver, | |
| }); | |
| // Grant the resolver function permission to create users in Cognito | |
| backend.createUserResolver.resources.lambda.addToRolePolicy( | |
| new PolicyStatement({ | |
| effect: Effect.ALLOW, | |
| actions: [ | |
| "cognito-idp:AdminCreateUser", | |
| "cognito-idp:AdminGetUser", | |
| "cognito-idp:AdminSetUserPassword", | |
| ], | |
| resources: [backend.auth.resources.userPool.userPoolArn], | |
| }) | |
| ); | |
| // Add the User Pool ID to the resolver function's environment | |
| backend.createUserResolver.addEnvironment( | |
| "AMPLIFY_AUTH_USERPOOL_ID", | |
| backend.auth.resources.userPool.userPoolId | |
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // amplify/functions/create-user-resolver/handler.ts | |
| import type { AppSyncResolverHandler } from "aws-lambda"; | |
| import { | |
| CognitoIdentityProviderClient, | |
| AdminCreateUserCommand, | |
| } from "@aws-sdk/client-cognito-identity-provider"; | |
| const cognito = new CognitoIdentityProviderClient(); | |
| type CreateUserArgs = { | |
| email: string; | |
| firstName: string; | |
| lastName: string; | |
| temporaryPassword: string; | |
| }; | |
| type CreateUserResult = { | |
| success: boolean; | |
| message: string; | |
| user?: { | |
| username?: string; | |
| email?: string; | |
| status?: string; | |
| }; | |
| }; | |
| export const handler: AppSyncResolverHandler< | |
| CreateUserArgs, | |
| CreateUserResult | |
| > = async (event) => { | |
| console.log("Create user event:", JSON.stringify(event, null, 2)); | |
| const { email, firstName, lastName, temporaryPassword } = event.arguments; | |
| // Validate input | |
| if (!email || !firstName || !lastName || !temporaryPassword) { | |
| return { | |
| success: false, | |
| message: "All fields are required", | |
| }; | |
| } | |
| if (temporaryPassword.length < 8) { | |
| return { | |
| success: false, | |
| message: "Password must be at least 8 characters long", | |
| }; | |
| } | |
| try { | |
| // Get the User Pool ID from environment | |
| const userPoolId = process.env.AMPLIFY_AUTH_USERPOOL_ID; | |
| if (!userPoolId) { | |
| throw new Error("User Pool ID not found in environment variables"); | |
| } | |
| const command = new AdminCreateUserCommand({ | |
| UserPoolId: userPoolId, | |
| Username: email, | |
| UserAttributes: [ | |
| { | |
| Name: "email", | |
| Value: email, | |
| }, | |
| { | |
| Name: "given_name", | |
| Value: firstName, | |
| }, | |
| { | |
| Name: "family_name", | |
| Value: lastName, | |
| }, | |
| { | |
| Name: "email_verified", | |
| Value: "true", | |
| }, | |
| ], | |
| TemporaryPassword: temporaryPassword, | |
| MessageAction: "SUPPRESS", // Remove to send welcome email | |
| DesiredDeliveryMediums: ["EMAIL"], | |
| }); | |
| const result = await cognito.send(command); | |
| return { | |
| success: true, | |
| message: "User created successfully", | |
| user: { | |
| username: result.User?.Username, | |
| email: email, | |
| status: result.User?.UserStatus, | |
| }, | |
| }; | |
| } catch (error: any) { | |
| console.error("Error creating user:", error); | |
| // Handle specific Cognito errors | |
| if (error.code === "UsernameExistsException") { | |
| return { | |
| success: false, | |
| message: "A user with this email already exists", | |
| }; | |
| } | |
| if (error.code === "InvalidPasswordException") { | |
| return { | |
| success: false, | |
| message: "Password does not meet requirements", | |
| }; | |
| } | |
| return { | |
| success: false, | |
| message: "Failed to create user", | |
| }; | |
| } | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // amplify/functions/create-user-resolver/resource.ts | |
| import { defineFunction } from "@aws-amplify/backend"; | |
| export const createUserResolver = defineFunction({ | |
| name: "createUserResolver", | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const client = generateClient<Schema>({ authMode: "userPool" }); | |
| const result = await client.mutations.createUser({ | |
| email: email, | |
| firstName: firstName, | |
| lastName: lastName, | |
| temporaryPassword: password, | |
| }); | |
| if (result.data?.success) { | |
| console.log("User created successfully:", result.data.user); | |
| } else { | |
| console.error("Failed to create user:", result.data?.message); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment