Projet

Général

Profil

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

root / uauth / utils.py @ b3843f12

1
import os
2
import logging
3
import json
4
from uuid import uuid4
5

    
6
try:
7
    import ldap
8
    import ldap.modlist
9
except ImportError:
10
    ldap = None
11

    
12
from django.conf import settings
13

    
14
logger = logging.getLogger(__name__)
15

    
16
def get_idp_list():
17
    idp_list_file = os.path.join(settings.METADATAS_DIR, 'idps.json')
18
    return json.load(file(idp_list_file))
19

    
20
def is_organization_idp(entity_id, organization):
21
    idps = get_idp_list()
22
    for idp in idps:
23
        if entity_id == idp['ENTITY_ID']:
24
            return True
25
    return False
26

    
27
def get_ldap_connection(conf=settings.LDAP_CONF):
28
    conn = ldap.initialize(conf['url'])
29
    for key, value in conf['options']:
30
        conn.set_option(key, value)
31
    try:
32
        conn.whoami_s()
33
    except ldap.SERVER_DOWN:
34
        logger.error('LDAP server down')
35
        return
36
    try:
37
        if 'credentials' in conf:
38
            conn.bind_s(*conf['credentials'])
39
        elif 'bind_dn' in conf:
40
            conn.bind_s(conf['bind_dn'], conf['bind_passwd'])
41
    except ldap.INVALID_CREDENTIALS:
42
        logger.warning('Invalid LDAP credentials')
43
        return
44
    return conn
45

    
46
def create_radius_user(**kwargs):
47
    username = uuid4().get_hex()
48
    password = uuid4().get_hex()
49
    connection = get_ldap_connection()
50
    if connection:
51
        attrs = {'objectClass': ['radiusprofile', 'radiusObjectProfile'],
52
                 'uid': username,
53
                 'userPassword': password,
54
                 'cn': username}
55
        attrs.update(kwargs)
56
        ldif = ldap.modlist.addModlist(attrs)
57
        dn = 'uid=%s,%s' % (username, settings.LDAP_CONF['dn'])
58
        logger.debug('creating new radius user: %s' % dn)
59
        connection.add_s(dn, ldif)
60
        return username, password
61
    else:
62
        return False
(8-8/10)