Skip to content

Commit

Permalink
fix: urls
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Dec 6, 2024
1 parent 883da0a commit 87f3213
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 76 deletions.
18 changes: 3 additions & 15 deletions codeforlife/settings/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@
# The name of the current service.
SERVICE_NAME = os.getenv("SERVICE_NAME", "REPLACE_ME")

# If the current service the root service. This will only be true for portal.
SERVICE_IS_ROOT = bool(int(os.getenv("SERVICE_IS_ROOT", "0")))

# The protocol, domain and port of the current service.
SERVICE_PROTOCOL = os.getenv("SERVICE_PROTOCOL", "http")
SERVICE_DOMAIN = os.getenv("SERVICE_DOMAIN", "localhost")
Expand All @@ -28,18 +25,9 @@
# The base url of the current service.
# The root service does not need its name included in the base url.
SERVICE_BASE_URL = f"{SERVICE_PROTOCOL}://{SERVICE_DOMAIN}:{SERVICE_PORT}"
if not SERVICE_IS_ROOT:
SERVICE_BASE_URL += f"/{SERVICE_NAME}"

# The api url of the current service.
SERVICE_API_URL = f"{SERVICE_BASE_URL}/api"

# The website url of the current service.
SERVICE_SITE_URL = (
"http://localhost:5173"
if SERVICE_DOMAIN == "localhost"
else SERVICE_BASE_URL
)

# The frontend url of the current service.
SERVICE_SITE_URL = os.getenv("SERVICE_SITE_URL", "http://localhost:5173")

# The authorization bearer token used to authenticate with Dotdigital.
MAIL_AUTH = os.getenv("MAIL_AUTH", "REPLACE_ME")
Expand Down
4 changes: 2 additions & 2 deletions codeforlife/settings/django.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from django.utils.translation import gettext_lazy as _

from ..types import JsonDict
from .custom import ENV, SERVICE_API_URL, SERVICE_BASE_DIR, SERVICE_NAME
from .custom import ENV, SERVICE_BASE_DIR, SERVICE_BASE_URL, SERVICE_NAME
from .otp import APP_ID, AWS_S3_APP_BUCKET, AWS_S3_APP_FOLDER

if t.TYPE_CHECKING:
Expand Down Expand Up @@ -104,7 +104,7 @@ def get_databases():
# Auth
# https://docs.djangoproject.com/en/3.2/topics/auth/default/

LOGIN_URL = f"{SERVICE_API_URL}/session/expired/"
LOGIN_URL = f"{SERVICE_BASE_URL}/session/expired/"

# Authentication backends
# https://docs.djangoproject.com/en/3.2/ref/settings/#authentication-backends
Expand Down
68 changes: 19 additions & 49 deletions codeforlife/urls/patterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
import typing as t

from django.contrib import admin
from django.http import HttpResponse
from django.urls import URLPattern, URLResolver, include, path, re_path
from rest_framework import status
from django.urls import URLPattern, URLResolver, include, path

from ..settings import SERVICE_IS_ROOT, SERVICE_NAME
from ..views import CsrfCookieView, HealthCheckView, LogoutView
from ..views import (
CsrfCookieView,
HealthCheckView,
LogoutView,
session_expired_view,
)

UrlPatterns = t.List[t.Union[URLResolver, URLPattern]]

Expand All @@ -33,73 +35,41 @@ def get_urlpatterns(
"""

urlpatterns: UrlPatterns = [
path(
"health-check/",
health_check_view.as_view(),
name="health-check",
),
path(
"admin/",
admin.site.urls,
name="admin",
),
path(
"api/csrf/cookie/",
"csrf/cookie/",
CsrfCookieView.as_view(),
name="get-csrf-cookie",
),
path(
"api/session/logout/",
"session/logout/",
LogoutView.as_view(),
name="logout",
),
# Django's default behavior with the @login_required decorator is to
# redirect users to the login template found in setting LOGIN_URL.
# Because we're using a React frontend, we want to return a
# 401-Unauthorized whenever a user's session-cookie expires so we can
# redirect them to the login page. Therefore, all login redirects will
# direct to this view which will return the desired 401.
path(
"api/session/expired/",
lambda request: HttpResponse(
status=status.HTTP_401_UNAUTHORIZED,
),
"session/expired/",
session_expired_view,
name="session-expired",
),
path(
"api/",
include(api_url_patterns),
name="api",
),
*api_url_patterns,
]

if include_user_urls:
urlpatterns.append(
path(
"api/",
"",
include("codeforlife.user.urls"),
name="user",
)
)

health_check_path = path(
"health-check/",
health_check_view.as_view(),
name="health-check",
)

if SERVICE_IS_ROOT:
urlpatterns.append(health_check_path)
return urlpatterns

return [
health_check_path,
path(
f"{SERVICE_NAME}/",
include(urlpatterns),
name="service",
),
re_path(
rf"^(?!{SERVICE_NAME}/).*",
lambda request: HttpResponse(
f'The base route is "{SERVICE_NAME}/".',
status=status.HTTP_404_NOT_FOUND,
),
name="service-not-found",
),
]
return urlpatterns
3 changes: 2 additions & 1 deletion codeforlife/views/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

from .api import APIView, BaseAPIView
from .base_login import BaseLoginView
from .common import CsrfCookieView, LogoutView
from .csrf import CsrfCookieView
from .decorators import action, cron_job
from .health_check import HealthCheckView
from .model import BaseModelViewSet, ModelViewSet
from .session import LogoutView, session_expired_view
9 changes: 0 additions & 9 deletions codeforlife/views/common.py → codeforlife/views/csrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
Created on 12/04/2024 at 16:51:36(+01:00).
"""

from django.contrib.auth.views import LogoutView as _LogoutView
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie
from rest_framework.request import Request
Expand All @@ -26,10 +24,3 @@ def get(self, request: Request):
Return a response which Django will auto-insert a CSRF cookie into.
"""
return Response()


class LogoutView(_LogoutView):
"""Override Django's logout view to always return a JSON response."""

def render_to_response(self, context, **response_kwargs):
return JsonResponse({})
30 changes: 30 additions & 0 deletions codeforlife/views/session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""
© Ocado Group
Created on 06/12/2024 at 11:55:49(+00:00).
Session views.
"""

from django.contrib.auth.views import LogoutView as _LogoutView
from django.http import HttpRequest, HttpResponse, JsonResponse
from rest_framework import status


class LogoutView(_LogoutView):
"""Override Django's logout view to always return a JSON response."""

def render_to_response(self, context, **response_kwargs):
return JsonResponse({})


def session_expired_view(request: HttpRequest):
"""
Django's default behavior with the @login_required decorator is to redirect
users to the login template found in setting LOGIN_URL. Because we're using
a React frontend, we want to return a 401-Unauthorized whenever a user's
session-cookie expires so we can redirect them to the login page. Therefore,
all login redirects will direct to this view which will return the desired
401.
"""

return HttpResponse(status=status.HTTP_401_UNAUTHORIZED)

0 comments on commit 87f3213

Please sign in to comment.