diff --git a/hc/accounts/backends.py b/hc/accounts/backends.py index a279b56a..c8c932bf 100644 --- a/hc/accounts/backends.py +++ b/hc/accounts/backends.py @@ -1,5 +1,8 @@ from django.contrib.auth.models import User from hc.accounts.models import Profile +from django.contrib.auth.backends import RemoteUserBackend +from hc.accounts import views +from django.conf import settings class BasicBackend(object): @@ -36,3 +39,14 @@ class EmailBackend(BasicBackend): if user.check_password(password): return user + +class CustomHeaderBackend(RemoteUserBackend): + def clean_username(self, username): + if settings.REMOTE_USER_HEADER_TYPE == None: return None + elif settings.REMOTE_USER_HEADER_TYPE == "ID": return username + + #else, it's the email address + try: + return User.objects.get(email=username).username + except User.DoesNotExist: + return views._make_user(username).username \ No newline at end of file diff --git a/hc/accounts/middleware.py b/hc/accounts/middleware.py index 353d492f..b759c8b4 100644 --- a/hc/accounts/middleware.py +++ b/hc/accounts/middleware.py @@ -1,4 +1,7 @@ from hc.accounts.models import Profile +from django.contrib.auth.middleware import RemoteUserMiddleware +from django.contrib.auth.backends import RemoteUserBackend +from django.conf import settings class TeamAccessMiddleware(object): @@ -11,3 +14,8 @@ class TeamAccessMiddleware(object): request.profile = Profile.objects.for_user(request.user) return self.get_response(request) + +from django.contrib.auth.middleware import RemoteUserMiddleware + +class CustomHeaderMiddleware(RemoteUserMiddleware): + header = settings.REMOTE_USER_HEADER \ No newline at end of file diff --git a/hc/settings.py b/hc/settings.py index 2ca152c1..2a2ec35a 100644 --- a/hc/settings.py +++ b/hc/settings.py @@ -58,12 +58,17 @@ INSTALLED_APPS = ( "hc.payments", ) +REMOTE_USER_HEADER = os.getenv("REMOTE_USER_HEADER", "AUTH_USER") +REMOTE_USER_HEADER_TYPE = os.getenv("REMOTE_USER_HEADER_TYPE", "").upper() +if REMOTE_USER_HEADER_TYPE not in ["EMAIL", "ID"]: REMOTE_USER_HEADER_TYPE = None + MIDDLEWARE = ( "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", + "hc.accounts.middleware.CustomHeaderMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.locale.LocaleMiddleware", @@ -73,6 +78,7 @@ MIDDLEWARE = ( AUTHENTICATION_BACKENDS = ( "hc.accounts.backends.EmailBackend", "hc.accounts.backends.ProfileBackend", + "hc.accounts.backends.CustomHeaderBackend", ) ROOT_URLCONF = "hc.urls"