kadenios/shared/auth/backends.py

57 lines
1.6 KiB
Python
Raw Normal View History

2021-01-26 14:26:35 +01:00
from authens.backends import ENSCASBackend
2020-12-21 00:07:07 +01:00
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
UserModel = get_user_model()
2021-01-26 14:26:35 +01:00
class CASBackend(ENSCASBackend):
"""ENS CAS authentication backend, customized to get the full name at connection."""
2020-12-21 00:07:07 +01:00
def clean_cas_login(self, cas_login):
2021-01-26 14:26:35 +01:00
return f"cas__{cas_login.strip().lower()}"
2020-12-21 00:07:07 +01:00
2021-01-26 14:26:35 +01:00
def create_user(self, username, attributes):
2020-12-21 00:07:07 +01:00
email = attributes.get("email")
2020-12-23 18:04:39 +01:00
name = attributes.get("name")
2020-12-21 00:07:07 +01:00
2021-01-26 14:26:35 +01:00
return UserModel.objects.create_user(
username=username, email=email, full_name=name
)
2020-12-21 00:07:07 +01:00
2021-01-26 14:26:35 +01:00
class PwdBackend(ModelBackend):
"""Password authentication"""
def authenticate(self, request, username=None, password=None):
if username is None or password is None:
2020-12-21 00:07:07 +01:00
return None
2021-01-26 14:26:35 +01:00
return super().authenticate(
request, username=f"pwd__{username}", password=password
)
2020-12-21 00:07:07 +01:00
class ElectionBackend(ModelBackend):
"""Authentication for a specific election.
Given a login and an election, we check if the user `{election.id}__{login}`
exists, and then if the password matches.
"""
def authenticate(self, request, login=None, password=None, election_id=None):
if login is None or password is None or election_id is None:
return None
try:
2021-01-26 14:26:35 +01:00
user = UserModel.objects.get(
username=f"{election_id}__{login}", election=election_id
)
2020-12-21 00:07:07 +01:00
except UserModel.DoesNotExist:
return None
if user.check_password(password):
return user
return None