63 lines
1.7 KiB
Python
63 lines
1.7 KiB
Python
import os
|
|
import logging
|
|
import json
|
|
from uuid import uuid4
|
|
|
|
try:
|
|
import ldap
|
|
import ldap.modlist
|
|
except ImportError:
|
|
ldap = None
|
|
|
|
from django.conf import settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def get_idp_list():
|
|
idp_list_file = os.path.join(settings.METADATAS_DIR, 'idps.json')
|
|
return json.load(file(idp_list_file))
|
|
|
|
def is_organization_idp(entity_id, organization):
|
|
idps = get_idp_list()
|
|
for idp in idps:
|
|
if entity_id == idp['ENTITY_ID']:
|
|
return True
|
|
return False
|
|
|
|
def get_ldap_connection(conf=settings.LDAP_CONF):
|
|
conn = ldap.initialize(conf['url'])
|
|
for key, value in conf['options']:
|
|
conn.set_option(key, value)
|
|
try:
|
|
conn.whoami_s()
|
|
except ldap.SERVER_DOWN:
|
|
logger.error('LDAP server down')
|
|
return
|
|
try:
|
|
if 'credentials' in conf:
|
|
conn.bind_s(*conf['credentials'])
|
|
elif 'bind_dn' in conf:
|
|
conn.bind_s(conf['bind_dn'], conf['bind_passwd'])
|
|
except ldap.INVALID_CREDENTIALS:
|
|
logger.warning('Invalid LDAP credentials')
|
|
return
|
|
return conn
|
|
|
|
def create_radius_user(**kwargs):
|
|
username = uuid4().get_hex()
|
|
password = uuid4().get_hex()
|
|
connection = get_ldap_connection()
|
|
if connection:
|
|
attrs = {'objectClass': ['radiusprofile', 'radiusObjectProfile'],
|
|
'uid': username,
|
|
'userPassword': password,
|
|
'cn': username}
|
|
attrs.update(kwargs)
|
|
ldif = ldap.modlist.addModlist(attrs)
|
|
dn = 'uid=%s,%s' % (username, settings.LDAP_CONF['dn'])
|
|
logger.debug('creating new radius user: %s' % dn)
|
|
connection.add_s(dn, ldif)
|
|
return username, password
|
|
else:
|
|
return False
|