ldapauth.py 6.83 KB
Newer Older
Recteur LP's avatar
Recteur LP committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import hashlib
import pyrmin

try:
    import ldap
    import ldif
    import urllib
except ImportError:
    from ldap3 import Server, Connection, AUTO_BIND_NO_TLS, SUBTREE, ALL_ATTRIBUTES
    import urllib.parse

###################################
__name__ = "LDAP Authentification"
__description__ = "Module to authenticate user with Active Directory Server"
Recteur LP's avatar
Recteur LP committed
19
__version__ = "0.3.0"
Recteur LP's avatar
Recteur LP committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
__pyrmin_version__ = "0.3.1"
__namespace__ = "ldapauth"
###################################

class auth():
    "LDAP auth module"
    def __init__(self, config):
        self.config = config
        if 'server' not in self.config:
            pyrmin.returnerror("No ldap server in config")
        elif 'port' not in self.config:
            pyrmin.returnerror("No ldap port in config")
        if sys.version_info >= (3,0):
            self.connection = Connection(
                Server(
                    self.config['server'],
                    port=int(self.config['port']),
                    use_ssl=self.config['ssl']
                ),
                auto_bind=AUTO_BIND_NO_TLS,
                read_only=True,
                check_names=True,
                user=self.config['user'],
                password=self.config['password']
            )
        else:
Recteur LP's avatar
Recteur LP committed
46
            self.ld = ldap.initialize('ldap://' + self.config['server']  + ':' + str(self.config['port']))
Recteur LP's avatar
Recteur LP committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
            self.ld.protocol_version = self.config['version']
            self.ld.set_option(ldap.OPT_REFERRALS, 0)
            self.ld.simple_bind_s(self.config['user'], self.config['password'])

    def __del__(self):
        if sys.version_info < (3,0):
            try:
                self.ld.unbind_s()
            except:
                pass

    def __getresults(self, filter):
        if sys.version_info >= (3,0):
            self.connection.search(
                search_base=self.config['basedn'],
                search_filter=filter,
                search_scope=SUBTREE,
                attributes=ALL_ATTRIBUTES,
                get_operational_attributes=True
            )
            results = self.connection.response
        else:
            results = self.ld.search_s(self.config['basedn'],ldap.SCOPE_SUBTREE,filter)
        return results

    def __getgroup(self, group):
        if sys.version_info >= (3,0):
            self.connection.search(
                search_base=self.config['basedn'],
                search_filter=group,
                search_scope=SUBTREE,
                attributes=ALL_ATTRIBUTES,
                get_operational_attributes=True
            )
            results = self.connection.response
        else:
            results = self.ld.search_s(group,ldap.SCOPE_SUBTREE)
        return results

    def getusersfromgroup(self, group):
        users = []
Recteur LP's avatar
Recteur LP committed
88
89
90
91
92
93
94
        if sys.version_info >= (3,0):
            for entry in self.__getresults(group):
                if "attributes" in entry:
                    attrs = entry['attributes']
                    users.append({ "name": attrs.get('sAMAccountName', [ 'Guest' ])[0], "uid": attrs.get('uidNumber', [ 'None' ])[0] })
                else:
            for dn, attrs in self.__getresults(group):
Recteur LP's avatar
Recteur LP committed
95
96
97
98
                users.append({ "name": attrs.get('sAMAccountName', [ 'Guest' ])[0], "uid": attrs.get('uidNumber', [ 'None' ])[0] })
        return users

    def get(self, name):
Recteur LP's avatar
Recteur LP committed
99
100
101
102
103
104
        if sys.version_info >= (3,0):
            filter = "(&(samAccountName=" + name + "))"
            for entry in self.__getresults(filter):
                if "attributes" in entry:
                    attrs = entry['attributes']
                    name = attrs.get('sAMAccountName', [ 'Guest' ])[0]
Recteur LP's avatar
Recteur LP committed
105
106
107
108
109
110
                    mail = str(attrs.get('mail')[0]).lower()
                    gravatar_url = "//www.gravatar.com/avatar/" + hashlib.md5(mail.encode('utf-8')).hexdigest() + "?"
                    gravatar_url += urllib.parse.urlencode({'d':"identicon", 's':str(50)})
                    division = attrs.get('division', [ 'Guest' ])[0]
                    displayname = attrs.get('displayName', [ 'Guest' ])[0]
                    company = attrs.get('company', [ '' ])[0]
Recteur LP's avatar
Recteur LP committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137

                    isadmin = False
                    admins = []
                    for group in self.config['admin']:
                        admins = self.getusersfromgroup("(&(memberOf=" + group + "))")
                        for admin in admins:
                            pyrmin.log.debug(admin)
                            if 'name' in admin and name.lower() == admin['name'].lower():
                                isadmin = True
                                break                  
                        if isadmin:
                            break
                    return {
                        "username": name,
                        "auth": True,
                        "admin": isadmin,
                        "division": division,
                        "displayname": displayname,
                        "mobile": attrs.get('otherMobile', [ '' ])[0],
                        "company": company,
                        "mail": mail,
                        "img": gravatar_url
                    }
        else:
            filter = "(&(cn=" + name + ")(!(objectClass=computer)))"
            for dn, attrs in self.__getresults(filter):
                    name = attrs.get('sAMAccountName', [ 'Guest' ])[0]
Recteur LP's avatar
Recteur LP committed
138
139
140
141
142
143
144
                    mail = str(attrs.get('mail')[0]).decode('utf-8').lower()
                    gravatar_url = "//www.gravatar.com/avatar/" + hashlib.md5(mail).hexdigest() + "?"
                    gravatar_url += urllib.urlencode({'d':"identicon", 's':str(50)})
                    division = attrs.get('division', [ 'Guest' ])[0].decode("utf-8")
                    displayname = attrs.get('displayName', [ 'Guest' ])[0].decode("utf-8")
                    company = attrs.get('company', [ '' ])[0].decode("utf-8")

Recteur LP's avatar
Recteur LP committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
                    isadmin = False
                    admins = []
                    for group in self.config['admin']:
                        admins = self.getusersfromgroup("(&(memberOf=" + group + "))")
                        for admin in admins:
                            pyrmin.log.debug(admin)
                            if 'name' in admin and name.lower() == admin['name'].lower():
                                isadmin = True
                                break                  
                        if isadmin:
                            break
                    return {
                        "username": name,
                        "auth": True,
                        "admin": isadmin,
                        "division": division,
                        "displayname": displayname,
                        "mobile": attrs.get('otherMobile', [ '' ])[0],
                        "company": company,
                        "mail": mail,
                        "img": gravatar_url
                    }