Project

General

Profile

Download (1.63 KB) Statistics
| Branch: | Tag: | Revision:

root / uauth / utils.py @ 64438aee

1 764ef897 Serghei MIHAI
import os
2 09d398ce Serghei MIHAI
import logging
3 764ef897 Serghei MIHAI
import json
4 09d398ce Serghei MIHAI
5
try:
6
    import ldap
7
    import ldap.modlist
8
except ImportError:
9
    ldap = None
10
11
from django.conf import settings
12
13
logger = logging.getLogger(__name__)
14
15 764ef897 Serghei MIHAI
def get_idp_list():
16 318ca21b Serghei MIHAI
    idp_list_file = os.path.join(settings.METADATAS_DIR, 'idps.json')
17 764ef897 Serghei MIHAI
    return json.load(file(idp_list_file))
18
19
def is_organization_idp(entity_id, organization):
20
    idps = get_idp_list()
21
    for idp in idps:
22
        if entity_id == idp['ENTITY_ID']:
23
            return True
24
    return False
25
26
def get_ldap_connection(conf=settings.LDAP_CONF):
27 09d398ce Serghei MIHAI
    conn = ldap.initialize(conf['url'])
28
    for key, value in conf['options']:
29
        conn.set_option(key, value)
30 764ef897 Serghei MIHAI
    try:
31
        conn.whoami_s()
32
    except ldap.SERVER_DOWN:
33
        logger.error('LDAP server down')
34
        return
35
    try:
36
        if 'credentials' in conf:
37
            conn.bind_s(*conf['credentials'])
38
        elif 'bind_dn' in conf:
39
            conn.bind_s(conf['bind_dn'], conf['bind_passwd'])
40
    except ldap.INVALID_CREDENTIALS:
41
        logger.warning('Invalid LDAP credentials')
42
        return
43
    return conn
44 09d398ce Serghei MIHAI
45
def create_radius_user(username, password, **kwargs):
46 764ef897 Serghei MIHAI
    connection = get_ldap_connection()
47 09d398ce Serghei MIHAI
    if connection:
48 008a36de Serghei MIHAI
        attrs = {'objectClass': ['radiusprofile', 'radiusObjectProfile'],
49 09d398ce Serghei MIHAI
                 'uid': username,
50
                 'userPassword': password,
51
                 'cn': username}
52
        attrs.update(kwargs)
53
        ldif = ldap.modlist.addModlist(attrs)
54
        dn = 'uid=%s,%s' % (username, settings.LDAP_CONF['dn'])
55 764ef897 Serghei MIHAI
        logger.debug('creating new radius user: %s' % dn)
56 09d398ce Serghei MIHAI
        connection.add_s(dn, ldif)
57 6a622bf4 Serghei MIHAI
        return True
58
    else:
59
        return False