or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mddevice-authentication.mdgroup-management.mdhttp-integration.mdindex.mdmfa.mdpassword-management.mdsrp-authentication.mduser-management.md

user-management.mddocs/

0

# User Management

1

2

Comprehensive user management operations for AWS Cognito User Pools, including user registration, profile management, user retrieval, deletion, and administrative user operations. Supports both user-level operations (using access tokens) and admin-level operations (using admin privileges).

3

4

## Capabilities

5

6

### User Registration

7

8

Register new users in the Cognito User Pool with attributes and optional email/SMS verification.

9

10

```python { .api }

11

def register(self, username: str, password: str, attr_map: dict = None, client_metadata: dict = None) -> dict:

12

"""

13

Register a new user in the user pool.

14

15

Args:

16

username (str): Unique username for the user

17

password (str): User's password (must meet pool requirements)

18

attr_map (dict, optional): Map custom attribute names to Cognito attributes

19

client_metadata (dict, optional): Custom workflow metadata

20

21

Returns:

22

dict: Registration response with confirmation details

23

{

24

'UserConfirmed': bool,

25

'CodeDeliveryDetails': {

26

'Destination': str, # Obfuscated email/phone

27

'DeliveryMedium': str, # 'SMS' or 'EMAIL'

28

'AttributeName': str

29

}

30

}

31

32

Note:

33

Use set_base_attributes() and add_custom_attributes() before calling

34

to set user attributes during registration.

35

"""

36

37

def set_base_attributes(self, **kwargs) -> None:

38

"""

39

Set base user attributes for registration and updates.

40

41

Args:

42

**kwargs: Attribute name-value pairs

43

44

Common attributes:

45

- email: Email address

46

- given_name: First name

47

- family_name: Last name

48

- phone_number: Phone number (+1234567890 format)

49

- birthdate: Birth date (YYYY-MM-DD)

50

- gender: Gender

51

- locale: Locale preference

52

- picture: Profile picture URL

53

- website: Website URL

54

"""

55

56

def add_custom_attributes(self, **kwargs) -> None:

57

"""

58

Add custom attributes with 'custom:' prefix.

59

60

Args:

61

**kwargs: Custom attribute name-value pairs

62

63

Note:

64

Custom attributes must be defined in the User Pool schema

65

and the client must have write permissions for them.

66

"""

67

```

68

69

**Usage Example:**

70

71

```python

72

from pycognito import Cognito

73

74

u = Cognito('your-user-pool-id', 'your-client-id')

75

76

# Set user attributes

77

u.set_base_attributes(

78

email='user@example.com',

79

given_name='John',

80

family_name='Doe',

81

phone_number='+1234567890'

82

)

83

84

# Add custom attributes

85

u.add_custom_attributes(

86

company='ACME Corp',

87

role='developer'

88

)

89

90

# Register user

91

response = u.register('johndoe', 'SecurePassword123!')

92

93

if not response['UserConfirmed']:

94

print(f"Confirmation code sent via {response['CodeDeliveryDetails']['DeliveryMedium']}")

95

```

96

97

### User Registration Confirmation

98

99

Confirm user registration using verification codes sent via email or SMS.

100

101

```python { .api }

102

def confirm_sign_up(self, confirmation_code: str, username: str = None) -> None:

103

"""

104

Confirm user registration using verification code.

105

106

Args:

107

confirmation_code (str): Code sent via email/SMS

108

username (str, optional): Username to confirm (uses instance username if not provided)

109

"""

110

111

def admin_confirm_sign_up(self, username: str = None) -> None:

112

"""

113

Admin confirm user registration without verification code.

114

115

Args:

116

username (str, optional): Username to confirm (uses instance username if not provided)

117

118

Note:

119

Requires admin privileges on the user pool.

120

"""

121

122

def resend_confirmation_code(self, username: str) -> None:

123

"""

124

Resend the confirmation code to the user.

125

126

Args:

127

username (str): Username to resend code for

128

"""

129

```

130

131

**Usage Example:**

132

133

```python

134

# Confirm registration with code

135

u.confirm_sign_up('123456', username='johndoe')

136

137

# Or admin confirm without code

138

u.admin_confirm_sign_up(username='johndoe')

139

140

# Resend confirmation if needed

141

u.resend_confirmation_code('johndoe')

142

```

143

144

### User Profile Retrieval

145

146

Retrieve user information and attributes using different access levels.

147

148

```python { .api }

149

def get_user(self, attr_map: dict = None) -> UserObj:

150

"""

151

Get current user information using access token.

152

153

Args:

154

attr_map (dict, optional): Map Cognito attributes to custom names

155

156

Returns:

157

UserObj: User object with attributes and methods

158

159

Requires:

160

Valid access token (user must be authenticated)

161

"""

162

163

def admin_get_user(self, attr_map: dict = None) -> UserObj:

164

"""

165

Get user information using admin privileges.

166

167

Args:

168

attr_map (dict, optional): Map Cognito attributes to custom names

169

170

Returns:

171

UserObj: User object with additional admin metadata

172

173

Additional metadata includes:

174

- enabled: Whether user account is enabled

175

- user_status: User status (CONFIRMED, UNCONFIRMED, etc.)

176

- create_date: Account creation date

177

- modified_date: Last modification date

178

"""

179

180

def get_users(self, attr_map: dict = None) -> list[UserObj]:

181

"""

182

Get all users in the user pool (admin operation).

183

184

Args:

185

attr_map (dict, optional): Map Cognito attributes to custom names

186

187

Returns:

188

list[UserObj]: List of all users in the pool

189

190

Note:

191

Handles pagination automatically for large user pools.

192

"""

193

```

194

195

**Usage Example:**

196

197

```python

198

# Get current authenticated user

199

user = u.get_user()

200

print(f"Username: {user.username}")

201

print(f"Email: {user.email}")

202

print(f"Name: {user.given_name} {user.family_name}")

203

204

# Get user with admin privileges

205

admin_user = u.admin_get_user()

206

print(f"User status: {admin_user.user_status}")

207

print(f"Account enabled: {admin_user.enabled}")

208

209

# Get all users (admin operation)

210

all_users = u.get_users()

211

print(f"Total users: {len(all_users)}")

212

```

213

214

### User Profile Updates

215

216

Update user attributes and profile information.

217

218

```python { .api }

219

def update_profile(self, attrs: dict, attr_map: dict = None) -> None:

220

"""

221

Update user attributes using access token.

222

223

Args:

224

attrs (dict): Attribute name-value pairs to update

225

attr_map (dict, optional): Map custom names to Cognito attributes

226

227

Note:

228

User must be authenticated. Some attributes may require verification.

229

"""

230

231

def admin_update_profile(self, attrs: dict, attr_map: dict = None) -> None:

232

"""

233

Update user attributes using admin privileges.

234

235

Args:

236

attrs (dict): Attribute name-value pairs to update

237

attr_map (dict, optional): Map custom names to Cognito attributes

238

239

Note:

240

Can update any user attribute without requiring user authentication.

241

"""

242

```

243

244

**Usage Example:**

245

246

```python

247

# Update user profile (requires authentication)

248

u.update_profile({

249

'given_name': 'Jane',

250

'family_name': 'Smith',

251

'phone_number': '+9876543210'

252

})

253

254

# Admin update (no authentication required)

255

u.admin_update_profile({

256

'email': 'newemail@example.com',

257

'email_verified': True

258

})

259

```

260

261

### Administrative User Creation

262

263

Create users with administrative privileges, including temporary passwords and custom attributes.

264

265

```python { .api }

266

def admin_create_user(self, username: str, temporary_password: str = "",

267

additional_kwargs: dict = None, attr_map: dict = None, **kwargs) -> dict:

268

"""

269

Create a user using admin privileges.

270

271

Args:

272

username (str): Username for the new user

273

temporary_password (str, optional): Temporary password (Cognito generates one if empty)

274

additional_kwargs (dict, optional): Additional AWS parameters (e.g., MessageAction)

275

attr_map (dict, optional): Map custom attribute names to Cognito attributes

276

**kwargs: User attributes (email, given_name, etc.)

277

278

Returns:

279

dict: User creation response with user details

280

281

Common additional_kwargs:

282

- MessageAction: 'SUPPRESS' to skip welcome message

283

- ForceAliasCreation: True to allow email/phone reuse

284

"""

285

```

286

287

**Usage Example:**

288

289

```python

290

# Create user with temporary password

291

response = u.admin_create_user(

292

username='newuser',

293

temporary_password='TempPass123!',

294

email='newuser@example.com',

295

given_name='New',

296

family_name='User',

297

additional_kwargs={'MessageAction': 'SUPPRESS'}

298

)

299

300

print(f"User created: {response['User']['Username']}")

301

```

302

303

### User Deletion

304

305

Delete user accounts with user-level or admin-level operations.

306

307

```python { .api }

308

def delete_user(self) -> None:

309

"""

310

Delete the current authenticated user.

311

312

Note:

313

User must be authenticated. This is irreversible.

314

"""

315

316

def admin_delete_user(self) -> None:

317

"""

318

Delete user using admin privileges.

319

320

Note:

321

Uses the username set on the Cognito instance.

322

This is irreversible.

323

"""

324

```

325

326

**Usage Example:**

327

328

```python

329

# User deletes their own account

330

u.delete_user()

331

332

# Admin deletes a user account

333

u = Cognito('pool-id', 'client-id', username='user-to-delete')

334

u.admin_delete_user()

335

```

336

337

### User Account Management

338

339

Enable, disable, and manage user account status.

340

341

```python { .api }

342

def admin_enable_user(self, username: str) -> None:

343

"""

344

Enable a user account.

345

346

Args:

347

username (str): Username to enable

348

"""

349

350

def admin_disable_user(self, username: str) -> None:

351

"""

352

Disable a user account.

353

354

Args:

355

username (str): Username to disable

356

357

Note:

358

Disabled users cannot authenticate but their data is preserved.

359

"""

360

```

361

362

**Usage Example:**

363

364

```python

365

# Disable user account

366

u.admin_disable_user('problematic-user')

367

368

# Re-enable user account

369

u.admin_enable_user('problematic-user')

370

```

371

372

### User Object Operations

373

374

Work with UserObj instances for convenient user operations.

375

376

```python { .api }

377

class UserObj:

378

"""User object with attributes and convenience methods."""

379

380

# Properties

381

username: str

382

sub: str # User's unique subject ID

383

email_verified: bool

384

phone_number_verified: bool

385

386

def save(self, admin: bool = False) -> None:

387

"""

388

Save user attribute changes.

389

390

Args:

391

admin (bool): Use admin privileges for update

392

"""

393

394

def delete(self, admin: bool = False) -> None:

395

"""

396

Delete this user.

397

398

Args:

399

admin (bool): Use admin privileges for deletion

400

"""

401

```

402

403

**Usage Example:**

404

405

```python

406

# Get user and modify attributes

407

user = u.get_user()

408

user.given_name = 'Updated Name'

409

user.save() # Save changes

410

411

# Delete user through object

412

user.delete() # User-level deletion

413

# or

414

user.delete(admin=True) # Admin-level deletion

415

```

416

417

## Usage Patterns

418

419

### Complete User Registration Flow

420

421

```python

422

from pycognito import Cognito

423

424

# Registration

425

u = Cognito('pool-id', 'client-id')

426

u.set_base_attributes(email='user@example.com', given_name='John')

427

response = u.register('johndoe', 'Password123!')

428

429

if not response['UserConfirmed']:

430

# Handle confirmation

431

code = input("Enter confirmation code: ")

432

u.confirm_sign_up(code, 'johndoe')

433

434

print("User registered and confirmed!")

435

```

436

437

### Admin User Management

438

439

```python

440

# Create and manage users as admin

441

u = Cognito('pool-id', 'client-id')

442

443

# Create user

444

u.admin_create_user(

445

username='employee1',

446

email='emp1@company.com',

447

given_name='Employee',

448

family_name='One'

449

)

450

451

# Update user

452

u.admin_update_profile({'department': 'Engineering'})

453

454

# List all users

455

users = u.get_users()

456

for user in users:

457

print(f"{user.username}: {user.email}")

458

```

459

460

### User Profile Management

461

462

```python

463

# Authenticated user updates profile

464

u = Cognito('pool-id', 'client-id', username='user')

465

u.authenticate(password='password')

466

467

# Get current profile

468

user = u.get_user()

469

print(f"Current email: {user.email}")

470

471

# Update profile

472

u.update_profile({

473

'given_name': 'Updated',

474

'phone_number': '+1234567890'

475

})

476

477

# Verify changes

478

updated_user = u.get_user()

479

print(f"New name: {updated_user.given_name}")

480

```