feat(account): Use a custom adpater

This commit is contained in:
Tom Hubrecht 2024-09-18 22:19:33 +02:00
parent 1732249a2d
commit 1d2f4a5866
Signed by: thubrecht
SSH key fingerprint: SHA256:r+nK/SIcWlJ0zFZJGHtlAoRwq1Rm+WcKAm5ADYMoQPc
2 changed files with 45 additions and 10 deletions

View file

@ -111,11 +111,6 @@ AUTHENTICATION_BACKENDS = [
"allauth.account.auth_backends.AuthenticationBackend",
]
ACCOUNT_ADAPTER = "shared.account.AccountAdapter"
ACCOUNT_CHANGE_EMAIL = True
ACCOUNT_EMAIL_NOTIFICATIONS = True
SOCIALACCOUNT_ONLY = True
SOCIALACCOUNT_PROVIDERS = {
"openid_connect": {
"OAUTH_PKCE_ENABLED": True,
@ -127,12 +122,25 @@ SOCIALACCOUNT_PROVIDERS = {
"secret": credentials["KANIDM_SECRET"],
"settings": {
"server_url": f"https://sso.dgnum.eu/oauth2/openid/{credentials['KANIDM_CLIENT']}",
"color": "primary",
},
}
],
},
"cas": {
"APP": {
"provider_id": "ens_cas",
"name": "CAS ENS",
"settings": {"color": "danger"},
},
},
}
SOCIALACCOUNT_ONLY = True
SOCIALACCOUNT_ADAPTER = "shared.account.SharedAccountAdapter"
ACCOUNT_EMAIL_VERIFICATION = "none"
ACCOUNT_AUTHENTICATION_METHOD = "username"
AUTH_PASSWORD_VALIDATORS = []
AUTH_USER_MODEL = "dgsi.User"
@ -206,6 +214,8 @@ if DEBUG:
"django_browser_reload.middleware.BrowserReloadMiddleware",
]
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
INTERNAL_IPS = ["127.0.0.1"]
DEBUG_TOOLBAR_CONFIG = {"INSERT_BEFORE": "</footer>"}

View file

@ -1,10 +1,35 @@
from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from allauth.socialaccount.models import SocialLogin
from dgsi.models import User
class AccountAdapter(DefaultAccountAdapter):
class SharedAccountAdapter(DefaultSocialAccountAdapter):
"""
Overrides the Account Adapter.
Overrides the Account Adapter, to allow a simpler connection via CAS.
"""
def is_open_for_signup(self, request):
return False
def pre_social_login(self, request, sociallogin):
match sociallogin.account.provider:
# TODO: Add a correspondance table between ENS logins and ours
case "ens_cas":
# In this case, the username is located in extra_data["uid"]
username = sociallogin.account.extra_data["uid"]
case "kanidm":
username = sociallogin.account.extra_data["preferred_username"]
case _p:
raise KeyError(f"No sociallogin '{_p}' is supposed to exist.")
try:
# Connect an existing user if the login already exists, even if it
# with another social method
user = User.objects.get(username=username)
sociallogin.connect(request, user)
except User.DoesNotExist:
pass
def populate_user(self, request, sociallogin, data):
return super().populate_user(request, sociallogin, data)
def save_user(self, request, sociallogin: SocialLogin, form=None):
return super().save_user(request, sociallogin, form)