kadenios/shared/auth/backends.py

61 lines
1.8 KiB
Python
Raw Permalink 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
from django.core.exceptions import PermissionDenied
2020-12-21 00:07:07 +01:00
2021-05-29 11:58:42 +02:00
User = get_user_model()
2020-12-21 00:07:07 +01:00
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-05-29 11:58:42 +02:00
return User.objects.create_user(username=username, email=email, full_name=name)
2020-12-21 00:07:07 +01:00
def _get_or_create(self, cas_login, attributes):
try:
return super()._get_or_create(cas_login, attributes)
except ValueError:
raise PermissionDenied
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-05-29 11:58:42 +02:00
user = User.objects.get(
2021-01-26 14:26:35 +01:00
username=f"{election_id}__{login}", election=election_id
)
2021-05-29 11:58:42 +02:00
except User.DoesNotExist:
2020-12-21 00:07:07 +01:00
return None
if user.check_password(password):
return user