docs
0
# User Management & Security
1
2
Comprehensive user account management, role-based permissions, team organization, and security configuration with fine-grained access control for all CRM entities and operations.
3
4
## Capabilities
5
6
### User Model
7
8
Extended Django user model with CRM-specific functionality.
9
10
```python { .api }
11
class CremeUser(AbstractUser):
12
"""
13
Extended user model for Creme CRM with additional fields and CRM-specific functionality.
14
15
Attributes:
16
- displayed_name: str, display name shown in UI
17
- language: str, preferred language code
18
- time_zone: str, user's timezone
19
- role: UserRole, assigned permission role
20
- is_team: bool, indicates team/shared account
21
- theme: str, UI theme preference
22
- json_settings: JSONField, user preferences and configuration
23
24
Methods:
25
- get_teams(): Get teams this user belongs to
26
- has_perm_to_access(app_label): Check application access permission
27
- has_perm_to_view(entity): Check entity view permission
28
- has_perm_to_change(entity): Check entity modification permission
29
- has_perm_to_delete(entity): Check entity deletion permission
30
- has_perm_to_link(entity): Check entity relationship permission
31
- has_perm_to_unlink(entity): Check relationship removal permission
32
- get_role(): Get user's role with fallback to default
33
- is_superuser(): Check if user has administrator privileges
34
"""
35
```
36
37
### Role-Based Permissions
38
39
Hierarchical role system for organizing user permissions.
40
41
```python { .api }
42
class UserRole(models.Model):
43
"""
44
Role-based permission system defining what users can access and do.
45
46
Attributes:
47
- name: str, role name (e.g., "Sales Manager", "Administrator")
48
- allowed_apps: ManyToMany, applications this role can access
49
- admin_4_apps: ManyToMany, applications with administrative rights
50
- creatable_ctypes: ManyToMany, entity types this role can create
51
- exportable_ctypes: ManyToMany, entity types this role can export
52
53
Methods:
54
- can_access(app_label): Check if role allows access to application
55
- can_admin(app_label): Check if role has admin rights for application
56
- can_create(content_type): Check if role can create entity type
57
- can_export(content_type): Check if role can export entity type
58
- get_allowed_apps(): Get list of accessible applications
59
- get_creatable_models(): Get list of creatable entity types
60
"""
61
```
62
63
### Entity-Level Permissions
64
65
Fine-grained permissions for individual entities and entity types.
66
67
```python { .api }
68
class EntityCredentials(models.Model):
69
"""
70
Entity-level access permissions that can be granted or forbidden.
71
72
Attributes:
73
- role: UserRole, role these credentials apply to
74
- value: int, permission bitmask (VIEW|CHANGE|DELETE|LINK|UNLINK)
75
- set_type: int, whether permissions are ESET_ALL/ESET_OWN/ESET_FILTER
76
- ctype: ContentType, entity type these permissions apply to
77
- efilter: EntityFilter, optional filter limiting scope
78
- forbidden: bool, whether these permissions are forbidden
79
80
Permission Constants:
81
- VIEW = 1: Permission to view entities
82
- CHANGE = 2: Permission to modify entities
83
- DELETE = 4: Permission to delete entities
84
- LINK = 8: Permission to create relationships with entities
85
- UNLINK = 16: Permission to remove relationships from entities
86
87
Set Types:
88
- ESET_ALL = 1: Apply to all entities of this type
89
- ESET_OWN = 2: Apply only to entities owned by user
90
- ESET_FILTER = 3: Apply to entities matching filter
91
92
Methods:
93
- can_view(user, entity): Check if user can view entity
94
- can_change(user, entity): Check if user can modify entity
95
- can_delete(user, entity): Check if user can delete entity
96
- can_link(user, entity): Check if user can create relationships
97
- can_unlink(user, entity): Check if user can remove relationships
98
"""
99
100
class SetCredentials(models.Model):
101
"""
102
Permission sets for bulk credential management.
103
104
Attributes:
105
- role: UserRole, target role for these credentials
106
- value: int, permission bitmask
107
- set_type: int, scope of permission application
108
- ctype: ContentType, entity type
109
- efilter: EntityFilter, optional entity filter
110
- forbidden: bool, forbidden permission flag
111
112
Methods:
113
- apply_to_role(role): Apply credential set to role
114
- get_permissions(): Get list of granted permissions
115
- matches_entity(entity): Check if entity matches credential scope
116
"""
117
```
118
119
### Team Management
120
121
Team organization and shared permissions.
122
123
```python { .api }
124
class Team(CremeUser):
125
"""
126
Team entity for organizing users and shared permissions.
127
Inherits from CremeUser with is_team=True.
128
129
Additional Methods:
130
- get_teammates(): Get users belonging to this team
131
- add_teammate(user): Add user to team
132
- remove_teammate(user): Remove user from team
133
- get_team_permissions(): Get team-specific permissions
134
- share_entity_with_team(entity): Share entity access with team
135
"""
136
```
137
138
### Sandbox System
139
140
User data isolation and sandboxing.
141
142
```python { .api }
143
class Sandbox(models.Model):
144
"""
145
User sandboxing system for data isolation and security.
146
147
Attributes:
148
- uuid: str, unique sandbox identifier
149
- user: CremeUser, sandbox owner
150
- type: ContentType, entity type this sandbox applies to
151
- role: UserRole, role for sandbox-specific permissions
152
153
Methods:
154
- check_perm(user, perm, entity): Check permission within sandbox
155
- isolate_queryset(queryset, user): Filter queryset for sandbox
156
- get_isolated_entities(user): Get entities accessible to user
157
- is_isolated(entity, user): Check if entity is in user's sandbox
158
"""
159
```
160
161
## Usage Examples
162
163
### Creating Users and Roles
164
165
```python
166
from creme.creme_core.models import CremeUser, UserRole
167
from django.contrib.contenttypes.models import ContentType
168
169
# Create a role
170
sales_role = UserRole.objects.create(name="Sales Representative")
171
172
# Add application permissions
173
from creme.persons import get_contact_model
174
from creme.opportunities import get_opportunity_model
175
176
ContactModel = get_contact_model()
177
OpportunityModel = get_opportunity_model()
178
179
# Allow access to persons and opportunities apps
180
sales_role.allowed_apps.add('persons', 'opportunities', 'activities')
181
182
# Allow creating contacts and opportunities
183
contact_ct = ContentType.objects.get_for_model(ContactModel)
184
opportunity_ct = ContentType.objects.get_for_model(OpportunityModel)
185
sales_role.creatable_ctypes.add(contact_ct, opportunity_ct)
186
187
# Create user with role
188
user = CremeUser.objects.create_user(
189
username='john.sales',
190
email='john@company.com',
191
first_name='John',
192
last_name='Smith',
193
role=sales_role
194
)
195
user.set_password('secure_password123')
196
user.save()
197
```
198
199
### Setting Entity Permissions
200
201
```python
202
from creme.creme_core.models import EntityCredentials, SetCredentials
203
204
# Grant view and change permissions for contacts
205
EntityCredentials.objects.create(
206
role=sales_role,
207
value=EntityCredentials.VIEW | EntityCredentials.CHANGE,
208
set_type=EntityCredentials.ESET_ALL,
209
ctype=contact_ct
210
)
211
212
# Grant full permissions for own opportunities only
213
EntityCredentials.objects.create(
214
role=sales_role,
215
value=EntityCredentials.VIEW | EntityCredentials.CHANGE | EntityCredentials.DELETE,
216
set_type=EntityCredentials.ESET_OWN,
217
ctype=opportunity_ct
218
)
219
220
# Forbid deleting contacts
221
EntityCredentials.objects.create(
222
role=sales_role,
223
value=EntityCredentials.DELETE,
224
set_type=EntityCredentials.ESET_ALL,
225
ctype=contact_ct,
226
forbidden=True
227
)
228
```
229
230
### Permission Checking
231
232
```python
233
# Check user permissions
234
user = CremeUser.objects.get(username='john.sales')
235
contact = ContactModel.objects.get(id=1)
236
237
# Check various permissions
238
can_view = user.has_perm_to_view(contact)
239
can_edit = user.has_perm_to_change(contact)
240
can_delete = user.has_perm_to_delete(contact)
241
can_link = user.has_perm_to_link(contact)
242
243
print(f"User can view contact: {can_view}")
244
print(f"User can edit contact: {can_edit}")
245
print(f"User can delete contact: {can_delete}")
246
247
# Check application access
248
can_access_billing = user.has_perm_to_access('billing')
249
print(f"User can access billing: {can_access_billing}")
250
```
251
252
### Team Management
253
254
```python
255
# Create team
256
sales_team = CremeUser.objects.create(
257
username='sales_team',
258
email='sales@company.com',
259
is_team=True,
260
role=sales_role
261
)
262
263
# Add users to team
264
sales_users = CremeUser.objects.filter(role=sales_role, is_team=False)
265
for user in sales_users:
266
# Create relationship between user and team
267
from creme.creme_core.models import Relation, RelationType
268
team_rel = RelationType.objects.get(pk='creme_core-subject_has_team')
269
Relation.objects.create(
270
user=user,
271
subject_entity=user,
272
object_entity=sales_team,
273
type=team_rel
274
)
275
276
# Share entity with team
277
opportunity = OpportunityModel.objects.get(id=1)
278
share_rel = RelationType.objects.get(pk='creme_core-subject_share')
279
Relation.objects.create(
280
user=opportunity.user,
281
subject_entity=opportunity,
282
object_entity=sales_team,
283
type=share_rel
284
)
285
```
286
287
### Advanced Permission Scenarios
288
289
```python
290
from creme.creme_core.models import EntityFilter, EntityFilterCondition
291
292
# Create manager role with filtered permissions
293
manager_role = UserRole.objects.create(name="Sales Manager")
294
295
# Create filter for high-value opportunities
296
high_value_filter = EntityFilter.objects.create(
297
id='high_value_opportunities',
298
name='High Value Opportunities',
299
entity_type=opportunity_ct,
300
filter_type=EntityFilter.EF_REGULAR
301
)
302
303
EntityFilterCondition.objects.create(
304
filter=high_value_filter,
305
type=EntityFilterCondition.EFC_FIELD,
306
name='estimated_sales__gte',
307
value='10000'
308
)
309
310
# Grant special permissions for high-value opportunities only
311
EntityCredentials.objects.create(
312
role=manager_role,
313
value=EntityCredentials.VIEW | EntityCredentials.CHANGE | EntityCredentials.DELETE,
314
set_type=EntityCredentials.ESET_FILTER,
315
ctype=opportunity_ct,
316
efilter=high_value_filter
317
)
318
```
319
320
### User Preferences and Settings
321
322
```python
323
# Set user preferences
324
user.json_settings = {
325
'theme': 'dark',
326
'list_view_page_size': 50,
327
'default_currency': 'USD',
328
'email_notifications': True,
329
'dashboard_config': {
330
'show_calendar': True,
331
'show_recent_activities': True,
332
'show_statistics': False
333
}
334
}
335
user.save()
336
337
# Get user preference
338
def get_user_preference(user, key, default=None):
339
"""Get user preference with fallback to default."""
340
return user.json_settings.get(key, default)
341
342
# Set user preference
343
def set_user_preference(user, key, value):
344
"""Set user preference and save."""
345
if user.json_settings is None:
346
user.json_settings = {}
347
user.json_settings[key] = value
348
user.save()
349
350
# Usage
351
page_size = get_user_preference(user, 'list_view_page_size', 25)
352
set_user_preference(user, 'theme', 'light')
353
```
354
355
### Bulk User Management
356
357
```python
358
# Create multiple users from CSV
359
import csv
360
361
def create_users_from_csv(csv_file_path, default_role):
362
"""Create users in bulk from CSV file."""
363
created_users = []
364
365
with open(csv_file_path, 'r') as file:
366
reader = csv.DictReader(file)
367
for row in reader:
368
user = CremeUser.objects.create_user(
369
username=row['username'],
370
email=row['email'],
371
first_name=row['first_name'],
372
last_name=row['last_name'],
373
role=default_role
374
)
375
user.set_password(row['password'])
376
user.save()
377
created_users.append(user)
378
379
return created_users
380
381
# Bulk permission assignment
382
def assign_bulk_permissions(role, app_permissions, entity_permissions):
383
"""Assign permissions to role in bulk."""
384
# Add app permissions
385
role.allowed_apps.add(*app_permissions['allowed'])
386
if 'admin' in app_permissions:
387
role.admin_4_apps.add(*app_permissions['admin'])
388
389
# Add entity creation permissions
390
if 'creatable' in entity_permissions:
391
role.creatable_ctypes.add(*entity_permissions['creatable'])
392
393
# Add entity export permissions
394
if 'exportable' in entity_permissions:
395
role.exportable_ctypes.add(*entity_permissions['exportable'])
396
397
# Usage
398
sales_permissions = {
399
'allowed': ['persons', 'opportunities', 'activities', 'commercial'],
400
'admin': []
401
}
402
403
entity_permissions = {
404
'creatable': [contact_ct, opportunity_ct],
405
'exportable': [contact_ct]
406
}
407
408
assign_bulk_permissions(sales_role, sales_permissions, entity_permissions)
409
```
410
411
### Security Auditing
412
413
```python
414
# Audit user permissions
415
def audit_user_permissions(user):
416
"""Generate permission audit report for user."""
417
report = {
418
'user': user.username,
419
'role': user.role.name if user.role else 'No Role',
420
'is_superuser': user.is_superuser,
421
'allowed_apps': list(user.role.allowed_apps.values_list('name', flat=True)) if user.role else [],
422
'admin_apps': list(user.role.admin_4_apps.values_list('name', flat=True)) if user.role else [],
423
'entity_permissions': []
424
}
425
426
if user.role:
427
credentials = EntityCredentials.objects.filter(role=user.role)
428
for cred in credentials:
429
report['entity_permissions'].append({
430
'entity_type': cred.ctype.name,
431
'permissions': cred.get_permissions(),
432
'scope': cred.get_set_type_display(),
433
'forbidden': cred.forbidden
434
})
435
436
return report
437
438
# Check for security issues
439
def check_security_issues():
440
"""Check for common security configuration issues."""
441
issues = []
442
443
# Check for users without roles
444
users_without_roles = CremeUser.objects.filter(role__isnull=True, is_superuser=False)
445
if users_without_roles.exists():
446
issues.append(f"Found {users_without_roles.count()} users without assigned roles")
447
448
# Check for overprivileged roles
449
overprivileged_roles = UserRole.objects.filter(
450
admin_4_apps__isnull=False
451
).distinct()
452
453
for role in overprivileged_roles:
454
admin_apps = role.admin_4_apps.count()
455
if admin_apps > 5: # Arbitrary threshold
456
issues.append(f"Role '{role.name}' has admin access to {admin_apps} applications")
457
458
return issues
459
```
460
461
The user management system provides comprehensive security and access control that integrates with all CRM modules while maintaining flexibility for different organizational structures and security requirements.