Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yike5460/8fe665f22d37a45fcd004e774b918087 to your computer and use it in GitHub Desktop.
Save yike5460/8fe665f22d37a45fcd004e774b918087 to your computer and use it in GitHub Desktop.
import * as cdk from "aws-cdk-lib";
import {CfnUserPoolUserToGroupAttachment, IUserPool} from "@aws-cdk/aws-cognito";
import {AwsCustomResource, AwsCustomResourcePolicy, PhysicalResourceId} from "@aws-cdk/custom-resources";
export class UserPoolUser extends cdk.Stack {
constructor(scope: cdk.App, id: string, props: {
userPool: IUserPool,
username: string,
password: string,
groupName?: string,
}) {
super(scope, id, props);
const username = props.username;
const password = props.password;
// Refer to API details on https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html
const adminCreateUser = new AwsCustomResource(this, 'AwsCustomResource-CreateUser', {
onCreate: {
service: 'CognitoIdentityServiceProvider',
action: 'adminCreateUser',
parameters: {
UserPoolId: props.userPool.userPoolId,
Username: username,
MessageAction: 'SUPPRESS',
TemporaryPassword: password,
},
physicalResourceId: PhysicalResourceId.of(`AwsCustomResource-CreateUser-${username}`),
},
onDelete: {
service: "CognitoIdentityServiceProvider",
action: "adminDeleteUser",
parameters: {
UserPoolId: props.userPool.userPoolId,
Username: username,
},
},
policy: AwsCustomResourcePolicy.fromSdkCalls({resources: AwsCustomResourcePolicy.ANY_RESOURCE}),
installLatestAwsSdk: true,
});
// Force the password for the user, since new users created are in FORCE_PASSWORD_CHANGE status by default, such new user has no way to change it though
// Refer to API details on https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html
const adminSetUserPassword = new AwsCustomResource(this, 'AwsCustomResource-ForcePassword', {
onCreate: {
service: 'CognitoIdentityServiceProvider',
action: 'adminSetUserPassword',
parameters: {
UserPoolId: props.userPool.userPoolId,
Username: username,
Password: password,
Permanent: true,
},
physicalResourceId: PhysicalResourceId.of(`AwsCustomResource-ForcePassword-${username}`),
},
policy: AwsCustomResourcePolicy.fromSdkCalls({resources: AwsCustomResourcePolicy.ANY_RESOURCE}),
installLatestAwsSdk: true,
});
adminSetUserPassword.node.addDependency(adminCreateUser);
// add the user to Cognito UserPool Group
if (props.groupName) {
const userToAdminsGroupAttachment = new CfnUserPoolUserToGroupAttachment(this, 'AttachAdminToAdminsGroup', {
userPoolId: props.userPool.userPoolId,
groupName: props.groupName,
username: username,
});
userToAdminsGroupAttachment.node.addDependency(adminCreateUser);
userToAdminsGroupAttachment.node.addDependency(adminSetUserPassword);
userToAdminsGroupAttachment.node.addDependency(props.userPool);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment