This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
authentic2-idp-ltpa/authentic2_idp_ltpa/adapter.py

56 lines
1.9 KiB
Python

import logging
from django.utils.importlib import import_module
from django.core.exceptions import ImproperlyConfigured
from . import app_settings
log = logging.getLogger(__name__)
def get_adapter():
module, cls = app_settings.ADAPTER.rsplit('.', 1)
try:
module = import_module(module)
cls = getattr(module, cls)
except (ImportError, AttributeError):
msg = 'LTPA user adapter not found: %r' % app_settings.ADAPTER
raise ImproperlyConfigured(msg)
return cls()
class UserAdapter(object):
def get_username(self, request):
'''What username do we put in the token ?'''
return request.user.username
def can_add_token(self, request):
'''Can we generate a token ?'''
return hasattr(request, 'user') \
and request.user \
and request.user.is_authenticated() \
and app_settings.USE_MIDDLEWARE
class AttributeAdapter(UserAdapter):
def get_username_attribute(self, request):
if not hasattr(request.user, 'get_attributes'):
return None
attributes = request.user.get_attributes()
if app_settings.TOKEN_USERNAME_ATTRIBUTE not in attributes:
return None
v = attributes[app_settings.TOKEN_USERNAME_ATTRIBUTE][0]
return v
def get_username(self, request):
if app_settings.TOKEN_USERNAME_ATTRIBUTE:
username_attribute = self.get_username_attribute(request)
log.debug('found LTPA username attributes %s: %r',
app_settings.TOKEN_USERNAME_ATTRIBUTE, username_attribute)
if username_attribute:
return username_attribute
return super(AttributeAdapter, self).get_username(request)
def can_add_token(self, request):
ok = super(AttributeAdapter, self).can_add_token(request)
if ok:
ok = bool(self.get_username_attribute(request))
return ok