Projet

Général

Profil

Télécharger (1,34 ko) Statistiques
| Branche: | Tag: | Révision:

root / uauth / utils.py @ 09d398ce

1
import logging
2

    
3
try:
4
    import ldap
5
    import ldap.modlist
6
    import ldap.sasl
7
    from ldap.filter import filter_format
8
except ImportError:
9
    ldap = None
10

    
11
from django.conf import settings
12

    
13
logger = logging.getLogger(__name__)
14

    
15
def get_connection(conf=settings.LDAP_CONF):
16
    conn = ldap.initialize(conf['url'])
17
    for key, value in conf['options']:
18
        conn.set_option(key, value)
19
        try:
20
            conn.whoami_s()
21
        except ldap.SERVER_DOWN:
22
            logger.error('LDAP server down')
23
            return
24
        try:
25
            if 'credentials' in conf:
26
                conn.bind_s(*conf['credentials'])
27
            elif 'bind_dn' in conf:
28
                conn.bind_s(conf['bind_dn'], conf['bind_passwd'])
29
        except ldap.INVALID_CREDENTIALS:
30
            logger.warning('Invalid LDAP credentials')
31
            return
32
        return conn
33

    
34
def create_radius_user(username, password, **kwargs):
35
    connection = get_connection()
36
    if connection:
37
        attrs = {'objectClass': ['radiusObjectProfile'],
38
                 'uid': username,
39
                 'userPassword': password,
40
                 'cn': username}
41
        attrs.update(kwargs)
42
        ldif = ldap.modlist.addModlist(attrs)
43
        dn = 'uid=%s,%s' % (username, settings.LDAP_CONF['dn'])
44
        log.debug('creating new radius user: %s' % dn)
45
        connection.add_s(dn, ldif)
(5-5/7)