summaryrefslogtreecommitdiffstats
path: root/accounts/backend/user/ldap.py
blob: da77b29110cd1019fbac1ad556b70390bc1df5de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
46
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# -*- coding: utf-8 -*-
from __future__ import absolute_import

import ldap

from . import Backend
from accounts.models import Account


class LdapBackend(Backend):

    def __init__(self, app):
        super(LdapBackend, self).__init__(app)

        self.ldap_host = self.app.config['LDAP_HOST']
        self.base_dn = self.app.config['LDAP_BASE_DN']
        self.admin_user = self.app.config['LDAP_ADMIN_USER']
        self.admin_pass = self.app.config['LDAP_ADMIN_PASS']
        self.services = self.app.all_services

        self.admin = False
        self.binded = False

    def auth(self, username, password):
        """
        Tries to authenticate a user with a given password. If the
        authentication is successful an Account object will be returned.
        """
        self._bind_anonymous()
        dn = self._format_dn([('uid', username), ('ou','users')])

        try:
            dn_user, data_user = self.connection.search_s(dn, ldap.SCOPE_SUBTREE)[0]
        except ldap.NO_SUCH_OBJECT:
            raise self.NoSuchUserError('No such user')

        self._bind_as_user(username, password)
        uid = data_user['uid'][0]
        mail = data_user['mail'][0]

        dn = self._format_dn([('ou', 'services')])
        filterstr = '(uid=%s)' % self._escape(uid)
        data_service = self.connection.search_s(dn, ldap.SCOPE_SUBTREE, filterstr)

        services = []
        for entry in data_service:
            cn = filter(lambda x: x.startswith('cn='), entry[0].split(','))[0]
            services.append(cn.split('=')[-1])

        acc = Account(uid, mail, services, dn_user, password)

        self._unbind()

        return acc

    def find(self, filters={}, wildcard=False):
        """
        Find accounts by a given filter.
        """
        self._bind_anonymous()

        filters['objectClass'] = 'inetOrgPerson'


        filter_as_list = ['(%s=%s)' % (k,self._escape(v, wildcard)) for k,v in filters.items()]
        filterstr = ''.join(filter_as_list)
        if len(filter_as_list) > 1:
            filterstr = '(&%s)' % filterstr

        dn = self._format_dn([('ou','users')])
        data = self.connection.search_s(dn, ldap.SCOPE_SUBTREE, filterstr)

        accounts = []
        for a in data:
            accounts.append(Account(a[1]['uid'][0], a[1]['mail'][0]))

        self._unbind()

        return accounts

    def register(self, account):
        """
        Persists an account in the backend.
        """
        self._bind_as_admin()

        dn = self._format_dn([('uid', account.uid),('ou','users')])
        uid = self._escape(account.uid)
        attr =  [
            ('objectClass', ['top','inetOrgPerson']),
            ('uid', uid), ('sn', 'n/a'), ('cn', uid),
            ('mail', account.attributes['mail'])
        ]
        self.connection.add_s(dn, attr)
        account.dn = dn

        account.new_password_root = (None, account.password)
        self._alter_passwords(account)

        self._unbind()

    def update(self, account, as_admin=False):
        """
        Updates account informations like passwords or email.
        """
        if as_admin:
            self._bind_as_admin()
        else:
            self._bind_as_user(account.uid, account.password)

        attr = [(ldap.MOD_REPLACE, k, v) for k, v in account.attributes.items()]
        dn = self._format_dn([('uid',account.uid),('ou','users')])
        self.connection.modify_s(dn, attr)
        self._alter_passwords(account, as_admin=as_admin)

        self._unbind()

    def delete(self, account, as_admin=False):
        """
        Deletes an account permanently.
        """
        if isinstance(account, basestring):
            raise NotImplementedError()
        else:
            user = account.uid
            password = account.password

        if as_admin:
            self._bind_as_admin()
        else:
            self._bind_as_user(user, password)

        dn = [self._format_dn([('uid',user),('cn',s),('ou','services')]) for s.id in account.services]
        dn.append(self._format_dn([('uid', user), ('ou','users')]))

        for x in dn:
            self.connection.delete_s(x)

        self._unbind()

    def _format_dn(self, attr, with_base_dn = True):
        if with_base_dn:
          attr.extend(self.base_dn)

        dn = ['%s=%s' % (item[0], self._escape(item[1])) for item in attr]

        return ','.join(dn)

    def _bind(self, dn, password):
        self.connection = ldap.initialize(self.ldap_host)
        self.connection.version = ldap.VERSION3

        try:
            self.connection.simple_bind_s(dn, password)
        except ldap.INVALID_CREDENTIALS:
            raise self.InvalidPasswordError("Invalid Password")

    def _bind_as_admin(self):
        if self.binded:
          self._unbind()

        dn = self._format_dn([('cn', self.admin_user)])
        self._bind(dn, self.admin_pass)

        self.admin = True
        self.binded = True

    def _bind_as_user(self, username, password):
        if self.binded:
          self._unbind()

        dn = self._format_dn([('uid', username),('ou', 'users')])
        self._bind(dn, password)

        self.binded = True
        self.admin = True

    def _bind_anonymous(self):
        if self.binded:
          self._unbind()

        self._bind('','')

        self.binded = True

    def _unbind(self):
        self.connection.unbind_s()
        self.admin = False
        self.binded = False

    def _alter_passwords(self, account, as_admin=False):
        if account.new_password_root:
            dn = self._format_dn([('uid',account.uid),('ou','users')])
            old, new = account.new_password_root
            if as_admin:
                self.connection.passwd_s(dn, None, new)
            else:
                try:
                    self.connection.passwd_s(dn, old, new)
                except ldap.UNWILLING_TO_PERFORM:
                    raise InvalidPasswordError()

            account.password = new

        account.new_password_root = None

        for service, passwords in account.new_password_services.items():
            dn = self._format_dn([('uid',account.uid),('cn',service),('ou','services')])
            old, new = passwords

            if new != None:
                if service not in account.services:
                    attr = [('objectClass', ['top', 'servicePassword']), ('uid', account.uid)]
                    self.connection.add_s(dn, attr)

                if as_admin:
                    self.connection.passwd_s(dn, None, new)
                else:
                    self.connection.passwd_s(dn, old, new)

            else:
                s = service.lower()
                if s in account.services:
                    self.connection.delete_s(dn)
                    account.services.remove(s)

        account.new_password_services = {}

    def _escape(self, s, wildcard=False):
        chars_to_escape = ['\\',',','=','+','<','>',';','"','\'','#','(',')','\0']

        if not wildcard:
          chars_to_escape.append('*')

        escape = lambda x,y: x.replace(y,'\%02X' % ord(y))

        return reduce(escape, chars_to_escape, s)