diff --git a/README.txt b/README.txt index 6ffe54b..f46826a 100644 --- a/README.txt +++ b/README.txt @@ -34,3 +34,7 @@ A2_LTPA_ADAPTER Class to adapt username for the LTPA idp, default is 'authentic2_idp_ltpa.adapter.UserAdapter' + +A2_LTPA_TOKEN_USERNAME_ATTRIBUTE: + + Use an attribute from the user to fill the user field of the LTPA token. diff --git a/authentic2_idp_ltpa/adapter.py b/authentic2_idp_ltpa/adapter.py index b2ba32c..2488169 100644 --- a/authentic2_idp_ltpa/adapter.py +++ b/authentic2_idp_ltpa/adapter.py @@ -1,8 +1,12 @@ +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: @@ -20,5 +24,32 @@ class UserAdapter(object): def can_add_token(self, request): '''Can we generate a token ?''' - return request.user.is_authenticated() \ + 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 diff --git a/authentic2_idp_ltpa/app_settings.py b/authentic2_idp_ltpa/app_settings.py index df7fbc6..8d0d487 100644 --- a/authentic2_idp_ltpa/app_settings.py +++ b/authentic2_idp_ltpa/app_settings.py @@ -3,10 +3,11 @@ class AppSettings(object): 'USE_MIDDLEWARE': True, 'TOKEN_DURATION': 8*3600, 'TOKEN_SECRET': None, + 'TOKEN_USERNAME_ATTRIBUTE': None, 'COOKIE_NAME': 'LtpaToken', 'COOKIE_DOMAIN': None, 'COOKIE_HTTP_ONLY': True, - 'ADAPTER': 'authentic2_idp_ltpa.adapter.UserAdapter', + 'ADAPTER': 'authentic2_idp_ltpa.adapter.AttributeAdapter', } def __init__(self, prefix):