Skip to content

Commit

Permalink
chore(analytics): Use a middleware instead of signals when setting us…
Browse files Browse the repository at this point in the history
…er properties, better error handling, removing useless condition
  • Loading branch information
qgerome committed Jul 23, 2024
1 parent 5b788b5 commit 8f99d5d
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 33 deletions.
3 changes: 2 additions & 1 deletion config/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"hexa.user_management.middlewares.login_required_middleware",
"hexa.analytics.middlewares.set_analytics_middleware",
]

ROOT_URLCONF = "config.urls"
Expand Down Expand Up @@ -197,7 +198,7 @@
RAW_CORS_ALLOWED_ORIGINS = os.environ.get("CORS_ALLOWED_ORIGINS")
if RAW_CORS_ALLOWED_ORIGINS is not None:
CORS_ALLOWED_ORIGINS = RAW_CORS_ALLOWED_ORIGINS.split(",")
CORS_URLS_REGEX = r"^/graphql/(\w+\/)?$"
CORS_URLS_REGEX = r"^[/graphql/(\w+\/)?|/analytics/track]$"
CORS_ALLOW_CREDENTIALS = True


Expand Down
6 changes: 3 additions & 3 deletions hexa/analytics/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@


def track(
request: HttpRequest,
request: HttpRequest | None,
event: str,
properties: dict = {},
user: User = None,
Expand All @@ -35,7 +35,7 @@ def track(

people = user if user else getattr(request, "user", None)
can_track = (
people is None or isinstance(user, AnonymousUser) or people.analytics_enabled
people is None or isinstance(people, AnonymousUser) or people.analytics_enabled
)
if can_track is False:
return
Expand Down Expand Up @@ -66,7 +66,7 @@ def set_user_properties(user: User):
return

try:
mixpanel.people_set_once(
mixpanel.people_set(
distinct_id=str(user.id),
properties={
"$email": user.email,
Expand Down
19 changes: 19 additions & 0 deletions hexa/analytics/middlewares.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from typing import Callable

from django.http import HttpRequest, HttpResponse

from hexa.analytics.api import set_user_properties


def set_analytics_middleware(
get_response: Callable[[HttpRequest], HttpResponse],
) -> Callable[[HttpRequest], HttpResponse]:
"""Send the user properties to the analytics service."""

def middleware(request: HttpRequest) -> HttpResponse:
response = get_response(request)
if getattr(request, "user") and request.user.is_authenticated:
set_user_properties(request.user)
return response

return middleware
2 changes: 1 addition & 1 deletion hexa/analytics/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
app_name = "analytics"

urlpatterns = [
path("events", views.track_event, name="track"),
path("track", views.track_event, name="track"),
]
25 changes: 11 additions & 14 deletions hexa/analytics/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,24 @@
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from hexa.user_management.models import AnonymousUser

from .api import track


@require_POST
@csrf_exempt
@require_POST
def track_event(request: HttpRequest) -> HttpResponse:
"""This API endpoint is called by the frontend to track events."""
payload = json.loads(request.body.decode("utf-8"))
try:
payload = json.loads(request.body.decode("utf-8"))
except json.JSONDecodeError:
return JsonResponse({"Bad request": "Invalid JSON payload."}, status=400)

if "event" not in payload:
return JsonResponse({"Bad request": "event name is required."}, status=400)

if isinstance(request.user, AnonymousUser) or request.user.analytics_enabled:
track(
request,
payload.get("event"),
payload.get("properties", {}),
request.user,
)
return JsonResponse({}, status=200)
else:
return JsonResponse({"error": "Analytics not enabled."}, status=401)
track(
request,
payload.get("event"),
payload.get("properties", {}),
)
return JsonResponse({}, status=200)
3 changes: 0 additions & 3 deletions hexa/user_management/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,3 @@ class UserManagementConfig(CoreAppConfig):
"password_reset_done",
"password_reset_complete",
]

def ready(self):
from . import signals # noqa
11 changes: 0 additions & 11 deletions hexa/user_management/signals.py

This file was deleted.

0 comments on commit 8f99d5d

Please sign in to comment.