Event System API Reference¶
The CRUDAdmin event system provides comprehensive audit logging and event tracking for admin operations. This system automatically logs admin actions, authentication events, and security-related activities with full audit trails.
Core Components¶
Event Types and Status¶
Model Creation Functions¶
Source code in crudadmin/event/models.py
Source code in crudadmin/event/models.py
Event Service¶
The main service class for managing event logging and retrieval.
Source code in crudadmin/event/service.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 |
|
cleanup_old_logs(db, retention_days=90)
async
¶
Clean up old logs based on retention policy.
Source code in crudadmin/event/service.py
get_resource_history(db, resource_type, resource_id, limit=50, offset=0)
async
¶
Get audit history for a specific resource.
Source code in crudadmin/event/service.py
get_security_alerts(db, lookback_hours=24)
async
¶
Get security alerts based on event patterns.
Source code in crudadmin/event/service.py
get_user_activity(db, user_id, start_time=None, end_time=None, limit=50, offset=0)
async
¶
Get user activity logs.
Source code in crudadmin/event/service.py
Event System Integration¶
High-level integration class for simplified event logging.
Source code in crudadmin/event/integration.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
|
log_auth_event(db, event_type, user_id, session_id, request, success, details=None)
async
¶
Log authentication-related events.
Source code in crudadmin/event/integration.py
log_security_event(db, event_type, user_id, session_id, request, details)
async
¶
Log security-related events with high priority.
Source code in crudadmin/event/integration.py
Decorators¶
Convenient decorators for automatic event logging.
Source code in crudadmin/event/decorators.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
|
Source code in crudadmin/event/decorators.py
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
|
Event Schemas¶
Event Log Schemas¶
Bases: AdminEventLogBase
Audit Log Schemas¶
Bases: AdminAuditLogBase
Usage Examples¶
Basic Event Logging¶
from crudadmin.event import EventService, EventType, EventStatus
# Initialize event service
event_service = EventService(db_config)
# Log a successful login
await event_service.log_event(
db=db,
event_type=EventType.LOGIN,
status=EventStatus.SUCCESS,
user_id=user.id,
session_id=session_id,
request=request,
details={"login_method": "password"}
)
Automatic Event Logging with Decorators¶
from crudadmin.event import log_admin_action, EventType
@log_admin_action(EventType.CREATE, model=User)
async def create_user_endpoint(
request: Request,
db: AsyncSession,
admin_db: AsyncSession,
current_user: User,
event_integration=None,
user_data: UserCreate
):
# Create user logic here
user = await create_user(db, user_data)
return user
Model Event Integration¶
from crudadmin.event import EventSystemIntegration
# Initialize integration
event_integration = EventSystemIntegration(event_service)
# Log model changes
await event_integration.log_model_event(
db=admin_db,
event_type=EventType.UPDATE,
model=Product,
user_id=current_user.id,
session_id=session_id,
request=request,
resource_id=str(product.id),
previous_state={"name": "Old Name", "price": 10.00},
new_state={"name": "New Name", "price": 15.00},
details={"field_changed": "name, price"}
)
Querying Event History¶
# Get user activity
activity = await event_service.get_user_activity(
db=admin_db,
user_id=user.id,
start_time=datetime.now() - timedelta(days=7),
limit=100
)
# Get resource audit history
history = await event_service.get_resource_history(
db=admin_db,
resource_type="Product",
resource_id="123",
limit=50
)
Event Configuration¶
Enabling Event Tracking¶
from crudadmin import CRUDAdmin
# Enable event tracking
crud_admin = CRUDAdmin(
track_events=True,
session_backend="database", # Required for event storage
secret_key="your-secret-key"
)
Custom Event Details¶
Events can include custom details for additional context:
await event_service.log_event(
db=admin_db,
event_type=EventType.CREATE,
status=EventStatus.SUCCESS,
user_id=user.id,
session_id=session_id,
request=request,
resource_type="Product",
resource_id="123",
details={
"category": "electronics",
"bulk_operation": True,
"import_batch_id": "batch_001",
"validation_warnings": ["price_below_cost"]
}
)
Event Model Fields¶
AdminEventLog Fields¶
Field | Type | Description |
---|---|---|
id |
int | Primary key |
timestamp |
datetime | When the event occurred |
event_type |
EventType | Type of event (CREATE, UPDATE, DELETE, LOGIN, etc.) |
status |
EventStatus | Event status (SUCCESS, FAILURE, WARNING) |
user_id |
int | ID of the user who performed the action |
session_id |
str | Session ID for the request |
ip_address |
str | IP address of the client |
user_agent |
str | User agent string from the request |
resource_type |
str | Type of resource affected (model name) |
resource_id |
str | ID of the specific resource |
details |
dict | Additional event-specific details |
AdminAuditLog Fields¶
Field | Type | Description |
---|---|---|
id |
int | Primary key |
event_id |
int | Reference to AdminEventLog |
timestamp |
datetime | When the audit record was created |
resource_type |
str | Type of resource (model name) |
resource_id |
str | ID of the specific resource |
action |
str | Action performed (create, update, delete) |
previous_state |
dict | State before the change |
new_state |
dict | State after the change |
changes |
dict | Computed differences between states |
audit_metadata |
dict | Additional audit metadata |
Security Considerations¶
Event Integrity¶
- Events are stored in append-only fashion
- Original event records are never modified
- All changes maintain full audit trails
- Events include request context for security analysis
Data Privacy¶
- Sensitive fields can be excluded from audit logs
- Password fields are automatically excluded
- PII can be masked or hashed in event details
- Event retention policies can be implemented
Performance Impact¶
- Event logging is asynchronous where possible
- Failed event logging doesn't interrupt main operations
- Database indexes optimize event querying
- Cleanup routines prevent unbounded growth
Error Handling¶
The event system includes robust error handling:
try:
await event_service.log_event(...)
except Exception as e:
# Event logging failure doesn't interrupt main operation
logger.error(f"Event logging failed: {e}")
# Continue with main business logic
Monitoring and Alerting¶
High-Priority Events¶
await event_integration.log_security_event(
db=admin_db,
event_type=EventType.FAILED_LOGIN,
user_id=user.id,
session_id=session_id,
request=request,
details={
"priority": "high",
"requires_attention": True,
"failed_attempts": 5,
"suspicious_activity": True
}
)
Event Metrics¶
Use event data for monitoring:
- Failed login attempt patterns
- Admin activity volume
- Resource modification frequency
- User behavior analysis
The event system provides a complete audit trail for compliance, security monitoring, and operational insights into your CRUDAdmin instance.