46 lines
1.3 KiB
Python
46 lines
1.3 KiB
Python
import logging
|
|
|
|
try:
|
|
import ldap
|
|
import ldap.modlist
|
|
import ldap.sasl
|
|
from ldap.filter import filter_format
|
|
except ImportError:
|
|
ldap = None
|
|
|
|
from django.conf import settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def get_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(username, password, **kwargs):
|
|
connection = get_connection()
|
|
if connection:
|
|
attrs = {'objectClass': ['radiusObjectProfile'],
|
|
'uid': username,
|
|
'userPassword': password,
|
|
'cn': username}
|
|
attrs.update(kwargs)
|
|
ldif = ldap.modlist.addModlist(attrs)
|
|
dn = 'uid=%s,%s' % (username, settings.LDAP_CONF['dn'])
|
|
log.debug('creating new radius user: %s' % dn)
|
|
connection.add_s(dn, ldif)
|