adapter: add an AttributeAdapter to use an LDAP attribute to fill the LTPA token user field
This commit is contained in:
parent
e16d4e294a
commit
90626fd379
|
@ -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.
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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):
|
||||
|
|
Reference in New Issue