Skip to content

Commit 90488ab

Browse files
committed
fix: log csrf errors
1 parent 1eae70d commit 90488ab

File tree

2 files changed

+66
-11
lines changed

2 files changed

+66
-11
lines changed

src/urls.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
ContributorViewSet,
3030
LoginView,
3131
)
32+
from .views.csrf import CsrfCookieView
3233

3334
default_router.register(
3435
"agreement-signatures",
@@ -46,14 +47,21 @@
4647
basename="contributor",
4748
)
4849

49-
urlpatterns = get_urlpatterns(
50-
[
51-
*default_router.urls,
52-
path(
53-
"session/login/",
54-
LoginView.as_view(),
55-
name="session-login",
56-
),
57-
],
58-
include_user_urls=False,
59-
)
50+
urlpatterns = [
51+
path(
52+
"csrf/cookie/",
53+
CsrfCookieView.as_view(),
54+
name="get-csrf-cookie-2",
55+
),
56+
*get_urlpatterns(
57+
[
58+
*default_router.urls,
59+
path(
60+
"session/login/",
61+
LoginView.as_view(),
62+
name="session-login",
63+
),
64+
],
65+
include_user_urls=False,
66+
),
67+
]

src/views/csrf.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
© Ocado Group
3+
Created on 12/04/2024 at 16:51:36(+01:00).
4+
"""
5+
6+
import logging
7+
import traceback
8+
9+
from codeforlife.permissions import AllowAny
10+
from django.utils.decorators import method_decorator
11+
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
12+
from rest_framework.request import Request
13+
from rest_framework.response import Response
14+
from rest_framework.views import APIView
15+
16+
17+
@method_decorator(ensure_csrf_cookie, name="dispatch")
18+
@method_decorator(csrf_exempt, name="dispatch")
19+
class CsrfCookieView(APIView):
20+
"""A view to get a CSRF cookie."""
21+
22+
http_method_names = ["get"]
23+
permission_classes = [AllowAny]
24+
25+
def get(self, request: Request):
26+
"""
27+
Return a response which Django will auto-insert a CSRF cookie into.
28+
"""
29+
return Response()
30+
31+
@classmethod
32+
def as_view(cls, **initkwargs):
33+
view = super().as_view(**initkwargs)
34+
35+
def view_wrapper(request, *args, **kwargs):
36+
try:
37+
return view(request, *args, **kwargs)
38+
# pylint: disable-next=broad-exception-caught
39+
except Exception as ex:
40+
logging.exception(ex)
41+
print(ex)
42+
traceback.print_exc()
43+
print(traceback.format_exc())
44+
logging.error(traceback.format_exc())
45+
raise ex
46+
47+
return view_wrapper

0 commit comments

Comments
 (0)