Skip to content

Commit 7ba756f

Browse files
authored
added current user for django
1 parent cc3bb4d commit 7ba756f

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

DJANGO_USAGE.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Django Usage
2+
3+
A middleware to add the current user to the transactions
4+
5+
Add as low down as possible in the order so all the session, user security comes first.
6+
7+
```python
8+
from django.db import connection, transaction
9+
10+
11+
class AuditLogUserMiddleware:
12+
"""
13+
Execute the request/response cycle in an atomic transaction.
14+
Update the audit log with the current user.
15+
"""
16+
17+
def __init__(self, get_response):
18+
self.get_response = get_response
19+
20+
def __call__(self, request):
21+
if request.method in ["POST", "PUT", "PATCH", "DELETE"]:
22+
with transaction.atomic():
23+
response = self.get_response(request)
24+
if request.user.is_authenticated:
25+
with connection.cursor() as cursor:
26+
sql = """
27+
UPDATE audit.logged_actions
28+
SET meta_fields = hstore('current_user', %s)
29+
WHERE transaction_id = txid_current();
30+
"""
31+
cursor.execute(sql, [str(request.user)])
32+
return response
33+
return self.get_response(request)
34+
```

audit.sql

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ CREATE TABLE audit.logged_actions (
5353
action TEXT NOT NULL CHECK (action IN ('I','D','U', 'T')),
5454
row_data hstore,
5555
changed_fields hstore,
56-
statement_only boolean not null
56+
statement_only boolean not null,
57+
meta_fields hstore
5758
);
5859

5960
REVOKE ALL ON audit.logged_actions FROM public;
@@ -110,7 +111,8 @@ BEGIN
110111
current_query(), -- top-level query or queries (if multistatement) from client
111112
substring(TG_OP,1,1), -- action
112113
NULL, NULL, -- row_data, changed_fields
113-
'f' -- statement_only
114+
'f', -- statement_only
115+
NULL -- fields to store abritary info
114116
);
115117

116118
IF NOT TG_ARGV[0]::boolean IS DISTINCT FROM 'f'::boolean THEN

0 commit comments

Comments
 (0)