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

group-management.mddocs/

0

# Group Management

1

2

Group operations for AWS Cognito User Pools, including group retrieval, user group membership management, and administrative group operations. Groups provide a way to organize users and assign permissions or roles within your application.

3

4

## Capabilities

5

6

### Group Retrieval

7

8

Retrieve group information and list all groups in the user pool.

9

10

```python { .api }

11

def get_group(self, group_name: str) -> GroupObj:

12

"""

13

Get a specific group by name.

14

15

Args:

16

group_name (str): Name of the group to retrieve

17

18

Returns:

19

GroupObj: Group object with properties and metadata

20

21

Raises:

22

Exception: If group doesn't exist or access is denied

23

"""

24

25

def get_groups(self) -> list[GroupObj]:

26

"""

27

Get all groups in the user pool.

28

29

Returns:

30

list[GroupObj]: List of all groups in the user pool

31

32

Note:

33

Returns empty list if no groups exist or user lacks permissions

34

"""

35

```

36

37

**Usage Example:**

38

39

```python

40

from pycognito import Cognito

41

42

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

43

44

# Get specific group

45

admin_group = u.get_group('administrators')

46

print(f"Group: {admin_group.group_name}")

47

print(f"Description: {admin_group.description}")

48

print(f"Precedence: {admin_group.precedence}")

49

50

# Get all groups

51

all_groups = u.get_groups()

52

print(f"Total groups: {len(all_groups)}")

53

54

for group in all_groups:

55

print(f"- {group.group_name}: {group.description}")

56

```

57

58

### User Group Membership

59

60

Manage user membership in groups using administrative operations.

61

62

```python { .api }

63

def admin_add_user_to_group(self, username: str, group_name: str) -> None:

64

"""

65

Add a user to a specific group.

66

67

Args:

68

username (str): Username to add to group

69

group_name (str): Name of the group

70

71

Requirements:

72

- Group must exist in the user pool

73

- User must exist in the user pool

74

- Requires admin privileges on the user pool

75

76

Actions:

77

- Adds user to group membership

78

- User inherits group permissions/roles

79

- Multiple group memberships are allowed

80

"""

81

82

def admin_remove_user_from_group(self, username: str, group_name: str) -> None:

83

"""

84

Remove a user from a specific group.

85

86

Args:

87

username (str): Username to remove from group

88

group_name (str): Name of the group

89

90

Actions:

91

- Removes user from group membership

92

- User loses group permissions/roles

93

- Does not affect other group memberships

94

"""

95

96

def admin_list_groups_for_user(self, username: str) -> list[str]:

97

"""

98

Get list of groups a user belongs to.

99

100

Args:

101

username (str): Username to check group membership for

102

103

Returns:

104

list[str]: List of group names the user belongs to

105

106

Note:

107

Handles pagination automatically for users with many group memberships

108

"""

109

```

110

111

**Usage Example:**

112

113

```python

114

# Add user to groups

115

u.admin_add_user_to_group('john.doe', 'developers')

116

u.admin_add_user_to_group('john.doe', 'beta-testers')

117

print("User added to groups")

118

119

# Check user's group memberships

120

user_groups = u.admin_list_groups_for_user('john.doe')

121

print(f"User belongs to groups: {user_groups}")

122

123

# Remove user from a group

124

u.admin_remove_user_from_group('john.doe', 'beta-testers')

125

print("User removed from beta-testers group")

126

127

# Verify removal

128

updated_groups = u.admin_list_groups_for_user('john.doe')

129

print(f"Updated group memberships: {updated_groups}")

130

```

131

132

### User Account Status Management

133

134

Enable and disable user accounts administratively.

135

136

```python { .api }

137

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

138

"""

139

Enable a user account.

140

141

Args:

142

username (str): Username to enable

143

144

Actions:

145

- Enables the user account for authentication

146

- User can log in and access the application

147

- Reverses previous admin_disable_user() call

148

149

Use cases:

150

- Re-enabling temporarily suspended accounts

151

- Activating accounts after review

152

- Bulk account management operations

153

"""

154

155

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

156

"""

157

Disable a user account.

158

159

Args:

160

username (str): Username to disable

161

162

Actions:

163

- Disables the user account from authentication

164

- User cannot log in but data is preserved

165

- Existing sessions may continue until token expiry

166

167

Use cases:

168

- Temporary account suspension

169

- Security incident response

170

- Deactivating terminated employees

171

172

Note:

173

Disabled users retain all data and group memberships

174

"""

175

```

176

177

**Usage Example:**

178

179

```python

180

# Disable problematic user account

181

u.admin_disable_user('problematic.user')

182

print("User account disabled")

183

184

# Later, re-enable the account

185

u.admin_enable_user('problematic.user')

186

print("User account re-enabled")

187

```

188

189

## Group Object

190

191

The GroupObj class represents a Cognito group with properties and metadata.

192

193

```python { .api }

194

class GroupObj:

195

"""Represents a Cognito user group."""

196

197

def __init__(self, group_data: dict, cognito_obj: Cognito):

198

"""

199

Initialize group object.

200

201

Args:

202

group_data (dict): Group data from AWS Cognito

203

cognito_obj (Cognito): Parent Cognito instance

204

"""

205

206

# Properties

207

group_name: str # Group name/identifier

208

description: str # Group description

209

creation_date: datetime # When group was created

210

last_modified_date: datetime # Last modification time

211

role_arn: str # IAM role ARN for group permissions

212

precedence: int # Group precedence (lower = higher priority)

213

```

214

215

**Usage Example:**

216

217

```python

218

# Get group and examine properties

219

group = u.get_group('administrators')

220

221

print(f"Group Name: {group.group_name}")

222

print(f"Description: {group.description}")

223

print(f"Created: {group.creation_date}")

224

print(f"Modified: {group.last_modified_date}")

225

print(f"Role ARN: {group.role_arn}")

226

print(f"Precedence: {group.precedence}")

227

228

# Groups with lower precedence values have higher priority

229

if group.precedence < 10:

230

print("This is a high-priority group")

231

```

232

233

## Usage Patterns

234

235

### User Role Management

236

237

```python

238

def assign_user_role(username, role):

239

"""Assign user to role-based groups."""

240

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

241

242

# Remove from all role groups first

243

current_groups = u.admin_list_groups_for_user(username)

244

role_groups = ['admin', 'manager', 'employee', 'guest']

245

246

for group in current_groups:

247

if group in role_groups:

248

u.admin_remove_user_from_group(username, group)

249

250

# Add to new role group

251

if role in role_groups:

252

u.admin_add_user_to_group(username, role)

253

print(f"User {username} assigned role: {role}")

254

else:

255

print(f"Invalid role: {role}")

256

257

# Usage

258

assign_user_role('john.doe', 'manager')

259

```

260

261

### Group-Based Access Control

262

263

```python

264

def check_user_permissions(username, required_groups):

265

"""Check if user has required group memberships."""

266

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

267

268

user_groups = u.admin_list_groups_for_user(username)

269

270

# Check if user belongs to any required group

271

has_access = any(group in user_groups for group in required_groups)

272

273

return has_access, user_groups

274

275

def enforce_group_access(username, required_groups):

276

"""Enforce group-based access control."""

277

has_access, user_groups = check_user_permissions(username, required_groups)

278

279

if has_access:

280

print(f"Access granted. User groups: {user_groups}")

281

return True

282

else:

283

print(f"Access denied. User groups: {user_groups}, Required: {required_groups}")

284

return False

285

286

# Usage

287

if enforce_group_access('john.doe', ['admin', 'manager']):

288

# Grant access to admin functionality

289

perform_admin_operation()

290

```

291

292

### Bulk Group Management

293

294

```python

295

def bulk_group_operations():

296

"""Perform bulk group management operations."""

297

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

298

299

# Get all groups for overview

300

all_groups = u.get_groups()

301

print(f"Managing {len(all_groups)} groups:")

302

303

for group in all_groups:

304

print(f"- {group.group_name} (precedence: {group.precedence})")

305

306

# Bulk user assignment

307

new_employees = ['emp1', 'emp2', 'emp3']

308

309

for username in new_employees:

310

try:

311

# Add to employee group

312

u.admin_add_user_to_group(username, 'employees')

313

314

# Add to department-specific group

315

u.admin_add_user_to_group(username, 'engineering')

316

317

print(f"Added {username} to employee groups")

318

319

except Exception as e:

320

print(f"Failed to add {username}: {e}")

321

322

bulk_group_operations()

323

```

324

325

### Hierarchical Group Management

326

327

```python

328

def manage_hierarchical_groups():

329

"""Manage groups with hierarchical permissions."""

330

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

331

332

# Define group hierarchy (lower precedence = higher authority)

333

group_hierarchy = {

334

'super_admin': 1,

335

'admin': 10,

336

'manager': 20,

337

'employee': 30,

338

'guest': 40

339

}

340

341

def get_user_highest_role(username):

342

"""Get user's highest authority role."""

343

user_groups = u.admin_list_groups_for_user(username)

344

345

# Find lowest precedence (highest authority) group

346

highest_precedence = float('inf')

347

highest_role = 'guest'

348

349

for group in user_groups:

350

if group in group_hierarchy:

351

precedence = group_hierarchy[group]

352

if precedence < highest_precedence:

353

highest_precedence = precedence

354

highest_role = group

355

356

return highest_role, highest_precedence

357

358

def promote_user(username, new_role):

359

"""Promote user to higher role."""

360

if new_role not in group_hierarchy:

361

print(f"Invalid role: {new_role}")

362

return

363

364

current_role, current_precedence = get_user_highest_role(username)

365

new_precedence = group_hierarchy[new_role]

366

367

if new_precedence < current_precedence:

368

# Remove from current role groups

369

current_groups = u.admin_list_groups_for_user(username)

370

for group in current_groups:

371

if group in group_hierarchy:

372

u.admin_remove_user_from_group(username, group)

373

374

# Add to new role group

375

u.admin_add_user_to_group(username, new_role)

376

print(f"Promoted {username} from {current_role} to {new_role}")

377

else:

378

print(f"Cannot promote {username} from {current_role} to {new_role}")

379

380

# Usage

381

promote_user('john.doe', 'manager')

382

383

# Check final role

384

role, precedence = get_user_highest_role('john.doe')

385

print(f"John's current role: {role} (precedence: {precedence})")

386

387

manage_hierarchical_groups()

388

```

389

390

### Group Audit and Reporting

391

392

```python

393

def generate_group_report():

394

"""Generate comprehensive group membership report."""

395

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

396

397

# Get all groups

398

all_groups = u.get_groups()

399

400

# Get all users

401

all_users = u.get_users()

402

403

print("=== GROUP MEMBERSHIP REPORT ===\n")

404

405

# Report by group

406

print("GROUPS AND THEIR MEMBERS:")

407

for group in all_groups:

408

print(f"\n{group.group_name} ({group.description})")

409

print(f" Created: {group.creation_date}")

410

print(f" Precedence: {group.precedence}")

411

412

# Find members (this requires checking each user)

413

members = []

414

for user in all_users:

415

user_groups = u.admin_list_groups_for_user(user.username)

416

if group.group_name in user_groups:

417

members.append(user.username)

418

419

print(f" Members ({len(members)}): {', '.join(members) if members else 'None'}")

420

421

# Report by user

422

print("\n\nUSERS AND THEIR GROUPS:")

423

for user in all_users:

424

user_groups = u.admin_list_groups_for_user(user.username)

425

print(f"{user.username}: {', '.join(user_groups) if user_groups else 'No groups'}")

426

427

generate_group_report()

428

```