2020-11-09 15:28:12 +01:00
|
|
|
from django.conf import settings
|
2021-03-14 14:17:21 +01:00
|
|
|
from django.contrib import auth
|
2023-06-03 10:41:04 +02:00
|
|
|
from django.contrib.auth.middleware import PersistentRemoteUserMiddleware
|
2020-11-09 15:28:12 +01:00
|
|
|
from django.contrib.auth.models import User
|
2023-12-26 14:22:41 -08:00
|
|
|
from django.http import HttpRequest
|
2020-11-23 22:50:02 +01:00
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
2020-11-09 15:28:12 +01:00
|
|
|
from rest_framework import authentication
|
|
|
|
|
|
|
|
|
|
|
2020-11-23 22:50:02 +01:00
|
|
|
class AutoLoginMiddleware(MiddlewareMixin):
|
2023-12-26 14:22:41 -08:00
|
|
|
def process_request(self, request: HttpRequest):
|
|
|
|
|
# Dont use auto-login with token request
|
|
|
|
|
if request.path.startswith("/api/token/") and request.method == "POST":
|
|
|
|
|
return None
|
2020-11-23 22:50:02 +01:00
|
|
|
try:
|
2022-02-27 15:26:41 +01:00
|
|
|
request.user = User.objects.get(username=settings.AUTO_LOGIN_USERNAME)
|
2023-04-24 22:31:34 -07:00
|
|
|
auth.login(
|
|
|
|
|
request=request,
|
|
|
|
|
user=request.user,
|
|
|
|
|
backend="django.contrib.auth.backends.ModelBackend",
|
|
|
|
|
)
|
2020-11-23 22:50:02 +01:00
|
|
|
except User.DoesNotExist:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
2020-11-09 15:28:12 +01:00
|
|
|
class AngularApiAuthenticationOverride(authentication.BaseAuthentication):
|
2022-02-27 15:26:41 +01:00
|
|
|
"""This class is here to provide authentication to the angular dev server
|
|
|
|
|
during development. This is disabled in production.
|
2020-11-09 15:28:12 +01:00
|
|
|
"""
|
2020-10-25 23:03:02 +01:00
|
|
|
|
|
|
|
|
def authenticate(self, request):
|
2022-02-27 15:26:41 +01:00
|
|
|
if (
|
|
|
|
|
settings.DEBUG
|
|
|
|
|
and "Referer" in request.headers
|
|
|
|
|
and request.headers["Referer"].startswith("http://localhost:4200/")
|
2022-03-11 10:55:51 -08:00
|
|
|
):
|
2020-11-09 15:28:12 +01:00
|
|
|
user = User.objects.filter(is_staff=True).first()
|
2022-05-06 09:04:08 -07:00
|
|
|
print(f"Auto-Login with user {user}")
|
2020-11-09 15:28:12 +01:00
|
|
|
return (user, None)
|
2020-10-25 23:03:02 +01:00
|
|
|
else:
|
|
|
|
|
return None
|
2021-01-03 00:37:19 -08:00
|
|
|
|
|
|
|
|
|
2023-06-03 10:41:04 +02:00
|
|
|
class HttpRemoteUserMiddleware(PersistentRemoteUserMiddleware):
|
2022-02-27 15:26:41 +01:00
|
|
|
"""This class allows authentication via HTTP_REMOTE_USER which is set for
|
|
|
|
|
example by certain SSO applications.
|
2021-01-03 00:37:19 -08:00
|
|
|
"""
|
2022-02-27 15:26:41 +01:00
|
|
|
|
2021-03-02 09:07:42 +01:00
|
|
|
header = settings.HTTP_REMOTE_USER_HEADER_NAME
|