iredadmin-ose / libs / ldaplib / connUtils.py

Zhang Huangbin 878d625 


Zhang Huangbin cd96fce 
Zhang Huangbin 878d625 



























Zhang Huangbin 551aed9 





Zhang Huangbin 878d625 
Zhang Huangbin 551aed9 






Zhang Huangbin 878d625 
Zhang Huangbin 551aed9 






Zhang Huangbin 878d625 


Zhang Huangbin 551aed9 




Zhang Huangbin 878d625 



























Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 















Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 




















Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 









Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 
Zhang Huangbin 551aed9 


Zhang Huangbin 878d625 


Zhang Huangbin 551aed9 













Zhang Huangbin 878d625 


Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 

















Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 









































Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 






































Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 


























Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 

Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 

















































Zhang Huangbin 551aed9 

Zhang Huangbin 878d625 

Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 


Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 
Zhang Huangbin 551aed9 
Zhang Huangbin 878d625 
































Zhang Huangbin 551aed9 


























Zhang Huangbin bce71cf 



Zhang Huangbin 92b7778 



Zhang Huangbin bce71cf 


Zhang Huangbin 92b7778 

Zhang Huangbin bce71cf 




  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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# Author: Zhang Huangbin <zhb@iredmail.org>

import web
import ldap
from ldap.filter import escape_filter_chars
from libs import iredutils
from libs.ldaplib import core, ldaputils, decorators, attrs, deltree

cfg = web.iredconfig
session = web.config.get('_session')

try:
    import cStringIO as StringIO
except ImportError:
    import StringIO


class Utils(core.LDAPWrap):
    def __del__(self):
        try:
            self.conn.unbind()
        except Exception, e:
            pass

    def addOrDelAttrValue(self, dn, attr, value, action):
        """Used to add or delete value of attribute which can handle multiple values.

        @attr: ldap attribute name
        @value: value of attr
        @action: add, delete.
        """
        self.dn = escape_filter_chars(dn)
        if isinstance(value, list):
            values = value
        else:
            values = [value]

        msg = ''
        if action == 'add' or action == 'assign':
            for v in values:
                try:
                    self.conn.modify_s(self.dn, [(ldap.MOD_ADD, attr, v)])
                except (ldap.NO_SUCH_OBJECT, ldap.TYPE_OR_VALUE_EXISTS):
                    pass
                except Exception, e:
                    msg += str(e)
        elif action == 'delete' or action == 'remove':
            for v in values:
                try:
                    self.conn.modify_s(self.dn, [(ldap.MOD_DELETE, attr, v)])
                except ldap.NO_SUCH_ATTRIBUTE:
                    pass
                except Exception, e:
                    msg += str(e)
        else:
            return (False, 'UNKNOWN_ACTION')

        if len(msg) == 0:
            return (True,)
        else:
            return (False, msg)

    # Change password.
    def changePasswd(self, dn, cur_passwd, newpw):
        dn = escape_filter_chars(dn)
        try:
            # Reference: RFC3062 - LDAP Password Modify Extended Operation
            self.conn.passwd_s(dn, cur_passwd, newpw)
            return (True,)
        except ldap.UNWILLING_TO_PERFORM:
            return (False, 'INCORRECT_OLDPW')
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))

    # Update value of attribute which must be single value.
    def updateAttrSingleValue(self, dn, attr, value):
        self.mod_attrs = [
                (ldap.MOD_REPLACE, web.safestr(attr), web.safestr(value))
                ]
        try:
            result = self.conn.modify_s(web.safestr(dn), self.mod_attrs)
            return (True,)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))

    # Get number of current accounts.
    def getNumberOfCurrentAccountsUnderDomain(self, domain, accountType='user', filter=None):
        # accountType in ['user', 'list', 'alias',]
        self.domain = web.safestr(domain)
        self.domaindn = ldaputils.convKeywordToDN(self.domain, accountType='domain')

        if filter is not None:
            self.searchdn = self.domaindn
            self.filter = filter
        else:
            if accountType == 'user':
                self.searchdn = attrs.DN_BETWEEN_USER_AND_DOMAIN + self.domaindn
                self.filter = '(&(objectClass=mailUser)(!(mail=@%s)))' % self.domain
            else:
                self.searchdn = self.domaindn
                self.filter = '(&(objectClass=mailUser)(!(mail=@%s)))' % self.domain

        try:
            result = self.conn.search_s(
                self.searchdn,
                ldap.SCOPE_SUBTREE,
                self.filter,
                ['dn', ],
            )
            return (True, len(result))
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))

    # Check whether domain name already exist (domainName, domainAliasName).
    def isDomainExists(self, domain):
        # Return True if account is invalid or exist.
        self.domain = web.safestr(domain).strip().lower()

        # Check domain name.
        if not iredutils.isDomain(self.domain):
            # Return True if invalid.
            return True

        # Check domainName and domainAliasName.
        try:
            result = self.conn.search_s(
                cfg.ldap.get('basedn'),
                ldap.SCOPE_ONELEVEL,
                '(|(domainName=%s)(domainAliasName=%s))' % (self.domain, self.domain),
                ['domainName', 'domainAliasName', ],
            )
            if len(result) > 0:
                # Domain name exist.
                return True
            else:
                return False
        except Exception, e:
            return True

    # Check whether account exist or not.
    def isAccountExists(self, domain, mail,):
        # Return True if account is invalid or exist.
        self.domain = str(domain)
        self.mail = str(mail)

        if not iredutils.isDomain(self.domain):
            return True

        if not iredutils.isEmail(self.mail):
            return True

        # Check whether mail address ends with domain name or alias domain name.
        self.mail_domain = self.mail.split('@', 1)[-1]
        qr_domain_and_aliases = self.getAvailableDomainNames(self.domain)
        if qr_domain_and_aliases[0] is True:
            if self.mail_domain not in qr_domain_and_aliases[1]:
                # Mail address is invalid.
                return True

        # Filter used to search mail accounts.
        ldap_filter = '(&(|(objectClass=mailUser)(objectClass=mailList)(objectClass=mailAlias))(|(mail=%s)(shadowAddress=%s)))' % (self.mail, self.mail)

        try:
            self.number = self.getNumberOfCurrentAccountsUnderDomain(
                domain=self.domain,
                filter=ldap_filter,
            )

            if self.number[0] is True and self.number[1] == 0:
                # Account not exist.
                return False
            else:
                return True
        except Exception, e:
            # Account 'EXISTS' (fake) if ldap lookup failed.
            return True

    @decorators.require_domain_access
    def enableOrDisableAccount(self, domain, account, dn, action, accountTypeInLogger=None):
        self.domain = web.safestr(domain).strip().lower()
        self.account = web.safestr(account).strip().lower()
        self.dn = escape_filter_chars(web.safestr(dn))

        # Validate operation action.
        if action in ['enable', 'disable', ]:
            self.action = action
        else:
            return (False, 'INVALID_ACTION')

        # Set value of valid account status.
        if action == 'enable':
            self.status = attrs.ACCOUNT_STATUS_ACTIVE
        else:
            self.status = attrs.ACCOUNT_STATUS_DISABLED

        try:
            self.updateAttrSingleValue(
                dn=self.dn,
                attr='accountStatus',
                value=self.status,
            )

            if accountTypeInLogger is not None:
                web.logger(
                    msg="%s %s: %s." % (str(action).capitalize(), str(accountTypeInLogger), self.account),
                    domain=self.domain,
                    event=self.action,
                )

            return (True,)
        except ldap.LDAPError, e:
            return (False, ldaputils.getExceptionDesc(e))

    @decorators.require_domain_access
    def deleteObjWithDN(self, domain, dn, account, accountType,):
        self.domain = web.safestr(domain)
        if not iredutils.isDomain(self.domain):
            return (False, 'INVALID_DOMAIN_NAME')

        self.dn = escape_filter_chars(dn)

        # Used for logger.
        self.account = web.safestr(account)

        try:
            deltree.DelTree(self.conn, self.dn, ldap.SCOPE_SUBTREE)
            web.logger(
                msg="Delete %s: %s." % (str(accountType), self.account),
                domain=self.domain,
                event='delete',
            )

            return (True,)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))

    def getSizelimitFromAccountLists(self, accountList, sizelimit=50, curPage=1, domain=None, accountType=None,):
        # Return a dict which contains:
        #   - totalAccounts: number of total accounts
        #   - accountList: list of accounts used to display in current page
        #   - totalPages: number of total pages show be showed in account list page.
        #   - totalQuota: number of domain quota size. Only available when accountType=='user'.

        # Initial a dict to set default values.
        result = {
            'totalAccounts': 0,         # Integer
            'accountList': [],          # List
            'totalPages': 0,            # Integer
            'totalQuota': 0,            # Integer
            'currentQuota': {},     # Dict
        }

        # Get total accounts.
        totalAccounts = len(accountList)
        result['totalAccounts'] = totalAccounts

        # Get number of actual pages.
        if totalAccounts % sizelimit == 0:
            totalPages = totalAccounts / sizelimit
        else:
            totalPages = (totalAccounts / sizelimit) + 1
        result['totalPages'] = totalPages

        if curPage >= totalPages:
            curPage = totalPages

        # Sort accounts in place.
        if isinstance(accountList, list):
            accountList.sort()
        else:
            pass

        # Get total domain mailbox quota.
        if accountType == 'user':
            counter = 0
            for i in accountList:
                quota = i[1].get('mailQuota', ['0'])[0]
                if quota.isdigit():
                    result['totalQuota'] += int(quota)
                    counter += 1

            # Update number of current domain quota size in LDAP (@attrs.ATTR_DOMAIN_CURRENT_QUOTA_SIZE).
            if domain is not None:
                # Update number of current domain quota size in LDAP.
                try:
                    dnDomain = ldaputils.convKeywordToDN(domain, accountType='domain')
                    self.updateAttrSingleValue(
                        dn=dnDomain,
                        attr=attrs.ATTR_DOMAIN_CURRENT_QUOTA_SIZE,
                        value=str(result['totalQuota']),
                    )
                except Exception, e:
                    pass

        # Get account list used to display in current page.
        if totalAccounts > sizelimit and totalAccounts < (curPage - 1) * sizelimit:
            accountList = accountList[-1:-sizelimit]
        else:
            accountList = accountList[(curPage - 1) * sizelimit: (curPage - 1) * sizelimit + sizelimit]
        result['accountList'] = accountList

        return result

    @decorators.require_domain_access
    def getDomainCurrentQuotaSizeFromLDAP(self, domain):
        self.domain = web.safestr(domain).strip().lower()
        if not iredutils.isDomain(self.domain):
            return (False, 'INVALID_DOMAIN_NAME')

        self.domainDN = ldaputils.convKeywordToDN(self.domain, accountType='domain')

        # Initial @domainCurrentQuotaSize
        self.domainCurrentQuotaSize = 0

        try:
            # Use '(!(mail=@domain.ltd))' to hide catch-all account.
            self.users = self.conn.search_s(
                attrs.DN_BETWEEN_USER_AND_DOMAIN + self.domainDN,
                ldap.SCOPE_SUBTREE,
                '(&(objectClass=mailUser)(!(mail=@%s)))' % self.domain,
                attrs.USER_SEARCH_ATTRS,
            )

            # Update @domainCurrentUserNumber
            self.updateAttrSingleValue(self.domainDN, 'domainCurrentUserNumber', len(self.users))

            for i in self.users:
                quota = i[1].get('mailQuota', ['0'])[0]
                if quota.isdigit():
                    self.domainCurrentQuotaSize += int(quota)
            return (True, self.domainCurrentQuotaSize)
        except ldap.NO_SUCH_OBJECT:
            #self.conn.add_s(
            #        attrs.DN_BETWEEN_USER_AND_DOMAIN + self.domainDN,
            #        iredldif.ldif_group(attrs.GROUP_USERS),
            #        )
            return (False, 'NO_SUCH_OBJECT')
        except ldap.SIZELIMIT_EXCEEDED:
            return (False, 'EXCEEDED_LDAP_SERVER_SIZELIMIT')
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))

    @decorators.require_domain_access
    def getAvailableDomainNames(self, domain):
        '''Get list of domainName and domainAliasName by quering domainName.

        >>> getAvailableDomainNames(domain='example.com')
        (True, ['example.com', 'aliasdomain01.com', 'aliasdomain02.com', ...])
        '''
        domain = web.safestr(domain).strip().lower()
        if not iredutils.isDomain(domain):
            return (False, 'INVALID_DOMAIN_NAME')

        dn = ldaputils.convKeywordToDN(domain, accountType='domain')

        try:
            result = self.conn.search_s(
                dn,
                ldap.SCOPE_BASE,
                '(&(objectClass=mailDomain)(domainName=%s))' % domain,
                ['domainName', 'domainAliasName'],
            )
            return (True, result[0][1].get('domainName', []) + result[0][1].get('domainAliasName', []))
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))

    def getDnWithKeyword(self, value, accountType='user'):
        self.keyword = web.safestr(value)

        if accountType == 'user':
            if attrs.RDN_USER == 'mail':
                if not iredutils.isEmail(self.keyword):
                    return False
                return ldaputils.convKeywordToDN(self.keyword, accountType='user')
            else:
                self.domain = self.keyword.split('@', 1)[-1]
                self.dnOfDomain = ldaputils.convKeywordToDN(self.domain, accountType='domain',)
                try:
                    result = self.conn.search_s(
                        attrs.DN_BETWEEN_USER_AND_DOMAIN + self.dnOfDomain,
                        ldap.SCOPE_SUBTREE,
                        '(&(objectClass=mailUser)(mail=%s))' % (self.keyword),
                    )
                    if len(result) == 1:
                        self.dn = result[0][0]
                        return self.dn
                    else:
                        return False
                except Exception, e:
                    return False
        else:
            # Unsupported accountType.
            return False

    # Get domains under control.
    def getManagedDomains(self, mail, attrs=attrs.ADMIN_ATTRS_ALL, listedOnly=False):
        self.mail = web.safestr(mail)
        if not iredutils.isEmail(self.mail):
            return (False, 'INCORRECT_USERNAME')

        # Pre-defined filter.
        filter = '(&(objectClass=mailDomain)(domainAdmin=%s))' % self.mail
        if session.get('domainGlobalAdmin') is True and listedOnly is False:
            filter = '(objectClass=mailDomain)'

        try:
            self.managedDomains = self.conn.search_s(
                self.basedn,
                ldap.SCOPE_ONELEVEL,
                filter,
                attrs,
            )
            if listedOnly:
                domains = []
                for qr in self.managedDomains:
                    domains += qr[1]['domainName']
                self.managedDomains = domains
            return (True, self.managedDomains)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))


def deleteAccountFromUsedQuota(accounts):
    # @accounts: must be list/tuple of email addresses.
    if not isinstance(accounts, (list, tuple)):
        return (False, 'INVALID_MAIL')

    if accounts:
        try:
            web.admindb.delete(
                'used_quota',
                vars={'accounts': accounts},
                where='username IN $accounts',
            )
            return (True,)
        except Exception, e:
            return (False, str(e))
    else:
        return (True,)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.