Esempio n. 1
0
    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))
Esempio n. 2
0
    def enableOrDisableAccount(
        self,
        domains,
        action,
        attr='accountStatus',
    ):
        if domains is None or len(domains) == 0:
            return (False, 'NO_DOMAIN_SELECTED')

        result = {}
        connutils = connUtils.Utils()
        for domain in domains:
            self.domain = web.safestr(domain)
            self.dn = ldaputils.convert_keyword_to_dn(self.domain,
                                                      accountType='domain')
            if self.dn[0] is False:
                return self.dn

            try:
                connutils.enableOrDisableAccount(
                    domain=self.domain,
                    account=self.domain,
                    dn=self.dn,
                    action=web.safestr(action).strip().lower(),
                    accountTypeInLogger='domain',
                )
            except ldap.LDAPError as e:
                result[self.domain] = str(e)

        if result == {}:
            return (True, )
        else:
            return (False, ldaputils.getExceptionDesc(result))
Esempio n. 3
0
    def enableOrDisableAccount(self, mails, action, attr='accountStatus',):
        if mails is None or len(mails) == 0:
            return (False, 'NO_ACCOUNT_SELECTED')

        result = {}
        connutils = connUtils.Utils()
        for mail in mails:
            self.mail = web.safestr(mail).strip().lower()
            if not iredutils.is_email(self.mail):
                continue

            self.domain = self.mail.split('@')[-1]
            self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='admin')
            if self.dn[0] is False:
                return self.dn

            try:
                connutils.enableOrDisableAccount(
                    domain=self.domain,
                    account=self.mail,
                    dn=self.dn,
                    action=web.safestr(action).strip().lower(),
                    accountTypeInLogger='admin',
                )
            except ldap.LDAPError as e:
                result[self.mail] = str(e)

        if result == {}:
            return (True,)
        else:
            return (False, ldaputils.getExceptionDesc(result))
Esempio n. 4
0
    def listAccounts(self, domain):
        self.domain = domain
        self.domainDN = ldaputils.convert_keyword_to_dn(self.domain,
                                                        accountType='domain')
        if self.domainDN[0] is False:
            return self.domainDN

        try:
            # Use '(!([email protected]))' 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,
            )

            connutils = connUtils.Utils()
            connutils.updateAttrSingleValue(self.domainDN,
                                            'domainCurrentUserNumber',
                                            len(self.users))

            return (True, self.users)
        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))
Esempio n. 5
0
    def deleteObjWithDN(
        self,
        domain,
        dn,
        account,
        accountType,
    ):
        self.domain = web.safestr(domain)
        if not iredutils.is_domain(self.domain):
            return (False, 'INVALID_DOMAIN_NAME')

        self.dn = escape_filter_chars(dn)

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

        try:
            delete_ldap_tree(dn=self.dn, conn=self.conn)
            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))
Esempio n. 6
0
    def getManagedDomains(self, mail, attrs=attrs.ADMIN_ATTRS_ALL):
        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

        # Check admin type: global/normal admin.
        try:
            profile = self.profile(self.mail)
            if profile[1][0][1].get('domainGlobalAdmin', ['no'])[0] == 'yes':
                filter = '(objectClass=mailDomain)'
        except:
            pass

        try:
            self.managedDomains = self.conn.search_s(
                self.basedn,
                ldap.SCOPE_ONELEVEL,
                filter,
                attrs,
            )
            return (True, self.managedDomains)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 7
0
    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
            elif accountType == 'maillist':
                self.searchdn = attrs.DN_BETWEEN_MAILLIST_AND_DOMAIN + self.domaindn
                self.filter = '(objectClass=mailList)'
            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))
Esempio n. 8
0
    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.is_domain(domain):
            return (False, 'INVALID_DOMAIN_NAME')

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

        try:
            result = self.conn.search_s(
                dn,
                ldap.SCOPE_BASE,
                '(&(objectClass=mailDomain)(domainName=%s))' % domain,
                ['domainName', 'domainAliasName'],
            )

            all_domains = result[0][1].get('domainName', []) + result[0][1].get('domainAliasName', [])
            all_domains = [str(d).lower() for d in all_domains if iredutils.is_domain(d)]
            return (True, all_domains)
        except Exception as e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 9
0
    def getManagedDomains(self, mail, attrs=attrs.ADMIN_ATTRS_ALL):
        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

        # Check admin type: global/normal admin.
        try:
            profile = self.profile(self.mail)
            if profile[1][0][1].get('domainGlobalAdmin', ['no'])[0] == 'yes':
                filter = '(objectClass=mailDomain)'
        except:
            pass

        try:
            self.managedDomains = self.conn.search_s(
                self.basedn,
                ldap.SCOPE_ONELEVEL,
                filter,
                attrs,
            )
            return (True, self.managedDomains)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 10
0
    def deleteSingleUser(
        self,
        mail,
        deleteFromGroups=True,
    ):
        self.mail = web.safestr(mail)
        if not iredutils.isEmail(self.mail):
            return (False, 'INVALID_MAIL')

        # Get domain name of this account.
        self.domain = self.mail.split('@')[-1]

        # Get dn of mail user and domain.
        self.dnUser = ldaputils.convKeywordToDN(self.mail, accountType='user')

        # Delete user object.
        try:
            #deltree.DelTree(self.conn, self.dnUser, ldap.SCOPE_SUBTREE)
            self.conn.delete_s(self.dnUser)

            if deleteFromGroups:
                self.deleteSingleUserFromGroups(self.mail)

            # Log delete action.
            web.logger(
                msg="Delete user: %s." % (self.mail),
                domain=self.domain,
                event='delete',
            )
            return (True, )
        except ldap.LDAPError, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 11
0
    def getManagedDomains(self, mail, attrs=attrs.ADMIN_ATTRS_ALL, listedOnly=False):
        self.mail = web.safestr(mail)
        if not iredutils.is_email(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 as e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 12
0
 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))
Esempio n. 13
0
    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))
Esempio n. 14
0
    def profile(self, domain, mail, accountType="user"):
        self.mail = web.safestr(mail)
        self.domain = self.mail.split("@", 1)[-1]

        if self.domain != domain:
            raise web.seeother("/domains?msg=PERMISSION_DENIED")

        self.filter = "(&(objectClass=mailUser)(mail=%s))" % (self.mail,)
        if accountType == "catchall":
            self.filter = "(&(objectClass=mailUser)(mail=@%s))" % (self.mail,)
        else:
            if not self.mail.endswith("@" + self.domain):
                raise web.seeother("/domains?msg=PERMISSION_DENIED")

        if attrs.RDN_USER == "mail":
            self.searchdn = ldaputils.convert_keyword_to_dn(self.mail, accountType=accountType)
            self.scope = ldap.SCOPE_BASE

            if self.searchdn[0] is False:
                return self.searchdn
        else:
            domain_dn = ldaputils.convert_keyword_to_dn(self.domain, accountType="domain")
            if domain_dn[0] is False:
                return domain_dn

            self.searchdn = attrs.DN_BETWEEN_USER_AND_DOMAIN + domain_dn
            self.scope = ldap.SCOPE_SUBTREE

        try:
            self.user_profile = self.conn.search_s(self.searchdn, self.scope, self.filter, attrs.USER_ATTRS_ALL)
            return (True, self.user_profile)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 15
0
    def deleteSingleUser(self, mail, deleteFromGroups=True,):
        self.mail = web.safestr(mail)
        if not iredutils.isEmail(self.mail):
            return (False, 'INVALID_MAIL')

        # Get domain name of this account.
        self.domain = self.mail.split('@')[-1]

        # Get dn of mail user and domain.
        self.dnUser = ldaputils.convKeywordToDN(self.mail, accountType='user')

        # Delete user object.
        try:
            #deltree.DelTree(self.conn, self.dnUser, ldap.SCOPE_SUBTREE)
            self.conn.delete_s(self.dnUser)

            if deleteFromGroups:
                self.deleteSingleUserFromGroups(self.mail)

            # Log delete action.
            web.logger(
                    msg="Delete user: %s." % (self.mail),
                    domain=self.domain,
                    event='delete',
            )
            return (True,)
        except ldap.LDAPError, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 16
0
    def delete(self, domain, mails=[]):
        if mails is None or len(mails) == 0:
            return (False, 'NO_ACCOUNT_SELECTED')

        self.domain = web.safestr(domain)
        self.mails = [str(v) for v in mails if iredutils.isEmail(v) and str(v).endswith('@'+self.domain)]

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

        if not iredutils.isDomain(self.domain):
            return (False, 'INVALID_DOMAIN_NAME')

        result = {}
        for mail in self.mails:
            self.mail = web.safestr(mail)

            try:
                # Delete user object (ldap.SCOPE_BASE).
                self.deleteSingleUser(self.mail,)

                # Delete user object and whole sub-tree.
                # Get dn of mail user and domain.
                """
                self.userdn = ldaputils.convKeywordToDN(self.mail, accountType='user')
                deltree.DelTree(self.conn, self.userdn, ldap.SCOPE_SUBTREE)

                # Log delete action.
                web.logger(
                    msg="Delete user: %s." % (self.mail),
                    domain=self.mail.split('@')[1],
                    event='delete',
                )
                """
            except ldap.LDAPError, e:
                result[self.mail] = ldaputils.getExceptionDesc(e)
Esempio n. 17
0
    def getDomainCurrentQuotaSizeFromLDAP(self, domain):
        self.domain = web.safestr(domain).strip().lower()
        if not iredutils.is_domain(self.domain):
            return (False, 'INVALID_DOMAIN_NAME')

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

        # Initial @domainCurrentQuotaSize
        self.domainCurrentQuotaSize = 0

        try:
            # Use '(!([email protected]))' 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:
            return (False, 'NO_SUCH_OBJECT')
        except ldap.SIZELIMIT_EXCEEDED:
            return (False, 'EXCEEDED_LDAP_SERVER_SIZELIMIT')
        except Exception as e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 18
0
    def listAccounts(self, domain):
        self.domain = domain
        self.domainDN = ldaputils.convKeywordToDN(self.domain, accountType='domain')

        try:
            # Use '(!([email protected]))' 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,
            )

            connutils = connUtils.Utils()
            connutils.updateAttrSingleValue(self.domainDN, 'domainCurrentUserNumber', len(self.users))

            return (True, self.users)
        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))
Esempio n. 19
0
    def delete(self, domain, mails=None, keep_mailbox_days=0):
        if not mails:
            return (False, 'NO_ACCOUNT_SELECTED')

        self.domain = web.safestr(domain)
        self.mails = [
            str(v) for v in mails
            if iredutils.is_email(v) and str(v).endswith('@' + self.domain)
        ]
        if not len(self.mails) > 0:
            return (False, 'INVALID_MAIL')

        if not iredutils.is_domain(self.domain):
            return (False, 'INVALID_DOMAIN_NAME')

        self.domaindn = ldaputils.convert_keyword_to_dn(self.domain,
                                                        accountType='domain')

        result = {}
        for mail in self.mails:
            self.mail = web.safestr(mail)

            try:
                # Delete user object (ldap.SCOPE_BASE).
                self.deleteSingleUser(mail=self.mail,
                                      keep_mailbox_days=keep_mailbox_days)
            except ldap.LDAPError as e:
                result[self.mail] = ldaputils.getExceptionDesc(e)

        if result == {}:
            return (True, )
        else:
            return (False, str(result))
Esempio n. 20
0
    def profile(self, domain, mail, accountType='user'):
        self.mail = web.safestr(mail)
        self.domain = self.mail.split('@', 1)[-1]

        if self.domain != domain:
            return web.seeother('/domains?msg=PERMISSION_DENIED')

        self.filter = '(&(objectClass=mailUser)(mail=%s))' % (self.mail, )
        if accountType == 'catchall':
            self.filter = '(&(objectClass=mailUser)(mail=@%s))' % (self.mail, )
        else:
            if not self.mail.endswith('@' + self.domain):
                return web.seeother('/domains?msg=PERMISSION_DENIED')

        if attrs.RDN_USER == 'mail':
            self.searchdn = ldaputils.convKeywordToDN(self.mail,
                                                      accountType=accountType)
            self.scope = ldap.SCOPE_BASE
        else:
            self.searchdn = attrs.DN_BETWEEN_USER_AND_DOMAIN + ldaputils.convKeywordToDN(
                self.domain, accountType='domain')
            self.scope = ldap.SCOPE_SUBTREE

        try:
            self.user_profile = self.conn.search_s(
                self.searchdn,
                self.scope,
                self.filter,
                attrs.USER_ATTRS_ALL,
            )
            return (True, self.user_profile)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 21
0
    def profile(self, domain, mail, accountType='user'):
        self.mail = web.safestr(mail)
        self.domain = self.mail.split('@', 1)[-1]

        if self.domain != domain:
            return web.seeother('/domains?msg=PERMISSION_DENIED')

        self.filter = '(&(objectClass=mailUser)(mail=%s))' % (self.mail,)
        if accountType == 'catchall':
            self.filter = '(&(objectClass=mailUser)(mail=@%s))' % (self.mail,)
        else:
            if not self.mail.endswith('@' + self.domain):
                return web.seeother('/domains?msg=PERMISSION_DENIED')

        if attrs.RDN_USER == 'mail':
            self.searchdn = ldaputils.convKeywordToDN(self.mail, accountType=accountType)
            self.scope = ldap.SCOPE_BASE
        else:
            self.searchdn = attrs.DN_BETWEEN_USER_AND_DOMAIN + ldaputils.convKeywordToDN(self.domain, accountType='domain')
            self.scope = ldap.SCOPE_SUBTREE

        try:
            self.user_profile = self.conn.search_s(
                self.searchdn,
                self.scope,
                self.filter,
                attrs.USER_ATTRS_ALL,
            )
            return (True, self.user_profile)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 22
0
 def updateAttrSingleValue(self, dn, attr, value):
     self.mod_attrs = [(ldap.MOD_REPLACE, web.safestr(attr), web.safestr(value))]
     try:
         self.conn.modify_s(web.safestr(dn), self.mod_attrs)
         return (True,)
     except Exception as e:
         return (False, ldaputils.getExceptionDesc(e))
Esempio n. 23
0
    def add(self, data):
        # msg: {key: value}
        msg = {}
        self.domain = web.safestr(data.get('domainName', '')).strip().lower()

        # Check domain name.
        if not iredutils.is_domain(self.domain):
            return (False, 'INVALID_DOMAIN_NAME')

        # Check whether domain name already exist (domainName, domainAliasName).
        connutils = connUtils.Utils()
        if connutils.is_domain_exists(self.domain):
            return (False, 'ALREADY_EXISTS')

        self.dn = ldaputils.convert_keyword_to_dn(self.domain,
                                                  accountType='domain')
        if self.dn[0] is False:
            return self.dn

        self.cn = data.get('cn', None)
        ldif = iredldif.ldif_maildomain(
            domain=self.domain,
            cn=self.cn,
        )

        # Add domain dn.
        try:
            self.conn.add_s(self.dn, ldif)
            web.logger(
                msg="Create domain: %s." % (self.domain),
                domain=self.domain,
                event='create',
            )
        except ldap.ALREADY_EXISTS:
            msg[self.domain] = 'ALREADY_EXISTS'
        except ldap.LDAPError as e:
            msg[self.domain] = str(e)

        # Add default groups under domain.
        if len(attrs.DEFAULT_GROUPS) >= 1:
            for i in attrs.DEFAULT_GROUPS:
                try:
                    group_dn = 'ou=' + str(i) + ',' + str(self.dn)
                    group_ldif = iredldif.ldif_group(str(i))

                    self.conn.add_s(group_dn, group_ldif)
                except ldap.ALREADY_EXISTS:
                    pass
                except ldap.LDAPError as e:
                    msg[i] = str(e)
        else:
            pass

        if len(msg) == 0:
            return (True, )
        else:
            return (False, ldaputils.getExceptionDesc(msg))
Esempio n. 24
0
    def deleteSingleUserFromGroups(self, mail):
        self.mail = web.safestr(mail)
        if not iredutils.is_email(self.mail):
            return (False, 'INVALID_MAIL')

        # Get domain name of this account.
        self.domain = self.mail.split('@')[-1]

        # Get dn of mail user and domain.
        self.dnUser = ldaputils.convert_keyword_to_dn(self.mail,
                                                      accountType='user')
        self.dnDomain = ldaputils.convert_keyword_to_dn(self.domain,
                                                        accountType='domain')

        if self.dnUser[0] is False:
            return self.dnUser

        if self.dnDomain[0] is False:
            return self.dnDomain

        try:
            # Get accounts which contains destination email.
            objsHasUser = self.conn.search_s(
                self.dnDomain,
                ldap.SCOPE_SUBTREE,
                self.getFilterOfDeleteUserFromGroups(self.mail),
                ['dn'],
            )

            if len(objsHasUser) >= 1:
                connutils = connUtils.Utils()
                for obj in objsHasUser:
                    if obj[0].endswith(attrs.DN_BETWEEN_ALIAS_AND_DOMAIN + self.dnDomain) or \
                       obj[0].endswith(attrs.DN_BETWEEN_USER_AND_DOMAIN + self.dnDomain):
                        # Remove address from alias and user.
                        connutils.addOrDelAttrValue(
                            dn=obj[0],
                            attr='mailForwardingAddress',
                            value=self.mail,
                            action='delete',
                        )
                    elif obj[0].endswith('ou=Externals,' + self.domaindn):
                        # Remove address from external member list.
                        connutils.addOrDelAttrValue(
                            dn=obj[0],
                            attr='mail',
                            value=self.mail,
                            action='delete',
                        )
                    else:
                        pass
            else:
                pass

            return (True, )
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 25
0
 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))
Esempio n. 26
0
 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))
Esempio n. 27
0
    def update(self, profile_type, mail, data):
        self.profile_type = web.safestr(profile_type)
        self.mail = web.safestr(mail)
        self.username, self.domain = self.mail.split('@', 1)

        if session.get('domainGlobalAdmin'
                       ) is not True and session.get('username') != self.mail:
            # Don't allow to view/update other admins' profile.
            return (False, 'PERMISSION_DENIED')

        self.dn = ldaputils.convert_keyword_to_dn(self.mail,
                                                  accountType='admin')
        if self.dn[0] is False:
            return self.dn

        mod_attrs = []
        if self.profile_type == 'general':
            # Get preferredLanguage.
            lang = web.safestr(data.get('preferredLanguage', 'en_US'))
            mod_attrs += [(ldap.MOD_REPLACE, 'preferredLanguage', lang)]

            # Get cn.
            cn = data.get('cn', None)
            mod_attrs += ldaputils.getSingleModAttr(attr='cn',
                                                    value=cn,
                                                    default=self.username)

            first_name = data.get('first_name', '')
            mod_attrs += ldaputils.getSingleModAttr(attr='givenName',
                                                    value=first_name,
                                                    default=self.username)

            last_name = data.get('last_name', '')
            mod_attrs += ldaputils.getSingleModAttr(attr='sn',
                                                    value=last_name,
                                                    default=self.username)

            # Get accountStatus.
            if 'accountStatus' in data.keys():
                accountStatus = 'active'
            else:
                accountStatus = 'disabled'

            mod_attrs += [(ldap.MOD_REPLACE, 'accountStatus', accountStatus)]

            try:
                # Modify profiles.
                self.conn.modify_s(self.dn, mod_attrs)
                if session.get('username') == self.mail and \
                   session.get('lang', 'en_US') != lang:
                    session['lang'] = lang
            except ldap.LDAPError, e:
                return (False, ldaputils.getExceptionDesc(e))
Esempio n. 28
0
 def listAccounts(self, attrs=attrs.ADMIN_SEARCH_ATTRS):
     filter = "(objectClass=mailAdmin)"
     try:
         result = self.conn.search_s(
             self.domainadmin_dn,
             ldap.SCOPE_ONELEVEL,
             filter,
             attrs,
         )
         return (True, result)
     except Exception, e:
         return (False, ldaputils.getExceptionDesc(e))
Esempio n. 29
0
 def listAccounts(self, attrs=attrs.ADMIN_SEARCH_ATTRS):
     filter = "(objectClass=mailAdmin)"
     try:
         result = self.conn.search_s(
             self.domainadmin_dn,
             ldap.SCOPE_ONELEVEL,
             filter,
             attrs,
         )
         return (True, result)
     except Exception, e:
         return (False, ldaputils.getExceptionDesc(e))
Esempio n. 30
0
    def add(self, data):
        self.cn = data.get('cn')
        self.mail = web.safestr(data.get('mail')).strip().lower()

        if not iredutils.is_email(self.mail):
            return (False, 'INVALID_MAIL')

        self.domainGlobalAdmin = web.safestr(
            data.get('domainGlobalAdmin', 'no'))
        if self.domainGlobalAdmin not in [
                'yes',
                'no',
        ]:
            self.domainGlobalAdmin = 'no'

        self.preferredLanguage = web.safestr(
            data.get('preferredLanguage', 'en_US'))

        # Check password.
        self.newpw = web.safestr(data.get('newpw'))
        self.confirmpw = web.safestr(data.get('confirmpw'))

        result = iredutils.verify_new_password(self.newpw, self.confirmpw)
        if result[0] is True:
            self.passwd = iredutils.generate_password_hash(result[1])
        else:
            return result

        ldif = iredldif.ldif_mailadmin(
            mail=self.mail,
            passwd=self.passwd,
            cn=self.cn,
            preferredLanguage=self.preferredLanguage,
            domainGlobalAdmin=self.domainGlobalAdmin)

        self.dn = ldaputils.convert_keyword_to_dn(self.mail,
                                                  accountType='admin')
        if self.dn[0] is False:
            return self.dn

        try:
            self.conn.add_s(self.dn, ldif)
            web.logger(
                msg="Create admin: %s." % (self.mail),
                event='create',
            )
            return (True, )
        except ldap.ALREADY_EXISTS:
            return (False, 'ALREADY_EXISTS')
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 31
0
    def update(self, profile_type, mail, data):
        self.profile_type = web.safestr(profile_type)
        self.mail = web.safestr(mail)
        self.username, self.domain = self.mail.split('@', 1)

        if session.get('domainGlobalAdmin') is not True and session.get('username') != self.mail:
            # Don't allow to view/update other admins' profile.
            return (False, 'PERMISSION_DENIED')

        self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='admin')
        if self.dn[0] is False:
            return self.dn

        mod_attrs = []
        if self.profile_type == 'general':
            # Get preferredLanguage.
            lang = web.safestr(data.get('preferredLanguage', 'en_US'))
            mod_attrs += [(ldap.MOD_REPLACE, 'preferredLanguage', lang)]

            # Get cn.
            cn = data.get('cn', None)
            mod_attrs += ldaputils.getSingleModAttr(attr='cn',
                                                    value=cn,
                                                    default=self.username)

            first_name = data.get('first_name', '')
            mod_attrs += ldaputils.getSingleModAttr(attr='givenName',
                                                    value=first_name,
                                                    default=self.username)

            last_name = data.get('last_name', '')
            mod_attrs += ldaputils.getSingleModAttr(attr='sn',
                                                    value=last_name,
                                                    default=self.username)

            # Get accountStatus.
            if 'accountStatus' in data.keys():
                accountStatus = 'active'
            else:
                accountStatus = 'disabled'

            mod_attrs += [(ldap.MOD_REPLACE, 'accountStatus', accountStatus)]

            try:
                # Modify profiles.
                self.conn.modify_s(self.dn, mod_attrs)
                if session.get('username') == self.mail and \
                   session.get('lang', 'en_US') != lang:
                    session['lang'] = lang
            except ldap.LDAPError, e:
                return (False, ldaputils.getExceptionDesc(e))
Esempio n. 32
0
def verify_bind_dn_pw(dn,
                      password,
                      uri=settings.ldap_uri,
                      close_connection=True):
    dn = web.safestr(dn.strip())
    password = password.strip()

    # Detect STARTTLS support.
    starttls = False
    if uri.startswith('ldaps://'):
        starttls = True

        # Rebuild uri, use ldap:// + STARTTLS (with normal port 389)
        # instead of ldaps:// (port 636) for secure connection.
        uri = uri.replace('ldaps://', 'ldap://')

        # Don't check CA cert
        ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

    conn = ldap.initialize(uri)

    # Set LDAP protocol version: LDAP v3.
    conn.set_option(ldap.OPT_PROTOCOL_VERSION, ldap.VERSION3)

    if starttls:
        conn.start_tls_s()

    try:
        # bind as vmailadmin
        conn.bind_s(settings.ldap_bind_dn, settings.ldap_bind_password)
        qr = conn.search_s(dn,
                           ldap.SCOPE_BASE,
                           '(objectClass=*)',
                           ['userPassword'])
        if not qr:
            return (False, 'INVALID_CREDENTIALS')

        entries = qr[0][1]
        qr_password = entries.get('userPassword', [''])[0]
        if iredutils.verify_password_hash(qr_password, password):
            if close_connection:
                conn.unbind_s()
                return (True, )
            else:
                # Return connection
                return (True, conn)
        else:
            return (False, 'INVALID_CREDENTIALS')
    except Exception as e:
        return (False, ldaputils.getExceptionDesc(e))
Esempio n. 33
0
def verify_bind_dn_pw(dn,
                      password,
                      uri=settings.ldap_uri,
                      close_connection=True):
    dn = web.safestr(dn.strip())
    password = password.strip()

    # Detect STARTTLS support.
    starttls = False
    if uri.startswith('ldaps://'):
        starttls = True

        # Rebuild uri, use ldap:// + STARTTLS (with normal port 389)
        # instead of ldaps:// (port 636) for secure connection.
        uri = uri.replace('ldaps://', 'ldap://')

        # Don't check CA cert
        ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

    conn = ldap.initialize(uri)

    # Set LDAP protocol version: LDAP v3.
    conn.set_option(ldap.OPT_PROTOCOL_VERSION, ldap.VERSION3)

    if starttls:
        conn.start_tls_s()

    try:
        # bind as vmailadmin
        conn.bind_s(settings.ldap_bind_dn, settings.ldap_bind_password)
        qr = conn.search_s(dn,
                           ldap.SCOPE_BASE,
                           '(objectClass=*)',
                           ['userPassword'])
        if not qr:
            return (False, 'INVALID_CREDENTIALS')

        entries = qr[0][1]
        qr_password = entries.get('userPassword', [''])[0]
        if iredutils.verify_password_hash(qr_password, password):
            if close_connection:
                conn.unbind_s()
                return (True, )
            else:
                # Return connection
                return (True, conn)
        else:
            return (False, 'INVALID_CREDENTIALS')
    except Exception, e:
        return (False, ldaputils.getExceptionDesc(e))
Esempio n. 34
0
 def listAccounts(self, attrs=attrs.ADMIN_SEARCH_ATTRS):
     try:
         result_admin = self.conn.search_s(
             self.domainadmin_dn, ldap.SCOPE_ONELEVEL, "(objectClass=mailAdmin)", attrs
         )
         result_user = self.conn.search_s(
             self.basedn,
             ldap.SCOPE_SUBTREE,
             "(&(objectClass=mailUser)(accountStatus=active)(enabledService=domainadmin))",
             attrs,
         )
         return (True, result_admin + result_user)
     except Exception, e:
         return (False, ldaputils.getExceptionDesc(e))
Esempio n. 35
0
    def deleteSingleUserFromGroups(self, mail):
        self.mail = web.safestr(mail)
        if not iredutils.isEmail(self.mail):
            return (False, 'INVALID_MAIL')

        # Get domain name of this account.
        self.domain = self.mail.split('@')[-1]

        # Get dn of mail user and domain.
        self.dnUser = ldaputils.convKeywordToDN(self.mail, accountType='user')
        self.dnDomain = ldaputils.convKeywordToDN(self.domain, accountType='domain')

        try:
            # Get accounts which contains destination email.
            objsHasUser = self.conn.search_s(
                self.dnDomain,
                ldap.SCOPE_SUBTREE,
                self.getFilterOfDeleteUserFromGroups(self.mail),
                ['dn'],
            )

            if len(objsHasUser) >= 1:
                connutils = connUtils.Utils()
                for obj in objsHasUser:
                    if obj[0].endswith(attrs.DN_BETWEEN_ALIAS_AND_DOMAIN + self.dnDomain) or \
                       obj[0].endswith(attrs.DN_BETWEEN_USER_AND_DOMAIN + self.dnDomain):
                        # Remove address from alias and user.
                        connutils.addOrDelAttrValue(
                            dn=obj[0],
                            attr='mailForwardingAddress',
                            value=self.mail,
                            action='delete',
                        )
                    elif obj[0].endswith('ou=Externals,' + self.domaindn):
                        # Remove address from external member list.
                        connutils.addOrDelAttrValue(
                            dn=obj[0],
                            attr='mail',
                            value=self.mail,
                            action='delete',
                        )
                    else:
                        pass
            else:
                pass

            return (True,)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 36
0
 def profile(self, mail):
     self.mail = web.safestr(mail)
     self.dn = ldaputils.convKeywordToDN(self.mail, accountType='admin')
     try:
         self.admin_profile = self.conn.search_s(
             self.dn,
             ldap.SCOPE_BASE,
             '(&(objectClass=mailAdmin)(mail=%s))' % self.mail,
             attrs.ADMIN_ATTRS_ALL,
         )
         return (True, self.admin_profile)
     except ldap.NO_SUCH_OBJECT:
         return (False, 'NO_SUCH_OBJECT')
     except Exception, e:
         return (False, ldaputils.getExceptionDesc(e))
Esempio n. 37
0
 def profile(self, mail):
     self.mail = web.safestr(mail)
     self.dn = ldaputils.convKeywordToDN(self.mail, accountType='admin')
     try:
         self.admin_profile = self.conn.search_s(
             self.dn,
             ldap.SCOPE_BASE,
             '(&(objectClass=mailAdmin)(mail=%s))' % self.mail,
             attrs.ADMIN_ATTRS_ALL,
         )
         return (True, self.admin_profile)
     except ldap.NO_SUCH_OBJECT:
         return (False, 'NO_SUCH_OBJECT')
     except Exception, e:
         return (False, ldaputils.getExceptionDesc(e))
Esempio n. 38
0
    def profile(self, mail, attributes=attrs.ADMIN_ATTRS_ALL):
        self.mail = web.safestr(mail)
        self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType="admin")
        if self.dn[0] is False:
            return self.dn

        try:
            self.admin_profile = self.conn.search_s(
                self.dn, ldap.SCOPE_BASE, "(&(objectClass=mailAdmin)(mail=%s))" % self.mail, attributes
            )
            return (True, self.admin_profile)
        except ldap.NO_SUCH_OBJECT:
            return (False, "NO_SUCH_OBJECT")
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 39
0
    def deleteObjWithDN(self, domain, dn, account, accountType):
        self.domain = web.safestr(domain)
        if not iredutils.is_domain(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))
Esempio n. 40
0
    def getDomainAccountSetting(self, domain,):
        result = self.getAllDomains(
            filter='(&(objectClass=mailDomain)(domainName=%s))' % domain,
            attrs=['domainName', 'accountSetting',],
        )

        if result[0] is True:
            allDomains = result[1]
        else:
            return result

        # Get accountSetting of current domain.
        try:
            allAccountSettings = ldaputils.getAccountSettingFromLdapQueryResult(allDomains, key='domainName')
            return (True, allAccountSettings.get(domain, {}))
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 41
0
 def listAccounts(self, attrs=attrs.ADMIN_SEARCH_ATTRS):
     try:
         result_admin = self.conn.search_s(
             self.domainadmin_dn,
             ldap.SCOPE_ONELEVEL,
             '(objectClass=mailAdmin)',
             attrs,
         )
         result_user = self.conn.search_s(
             self.basedn,
             ldap.SCOPE_SUBTREE,
             '(&(objectClass=mailUser)(accountStatus=active)(enabledService=domainadmin))',
             attrs,
         )
         return (True, result_admin + result_user)
     except Exception as e:
         return (False, ldaputils.getExceptionDesc(e))
Esempio n. 42
0
    def update(self, profile_type, domain, data):
        self.profile_type = web.safestr(profile_type)
        self.domain = web.safestr(domain)
        self.domaindn = ldaputils.convert_keyword_to_dn(self.domain,
                                                        accountType='domain')
        if self.domaindn[0] is False:
            return self.domaindn

        connutils = connUtils.Utils()
        self.accountSetting = []
        mod_attrs = []

        # Allow normal admin to update profiles.
        if self.profile_type == 'general':
            cn = data.get('cn', None)
            mod_attrs += ldaputils.getSingleModAttr(attr='cn',
                                                    value=cn,
                                                    default=self.domain)

        # Allow global admin to update profiles.
        if session.get('domainGlobalAdmin') is True:
            if self.profile_type == 'general':
                # Get accountStatus.
                if 'accountStatus' in data.keys():
                    accountStatus = 'active'
                else:
                    accountStatus = 'disabled'

                mod_attrs += [(ldap.MOD_REPLACE, 'accountStatus',
                               accountStatus)]

        try:
            dn = ldaputils.convert_keyword_to_dn(self.domain,
                                                 accountType='domain')
            if dn[0] is False:
                return dn

            self.conn.modify_s(dn, mod_attrs)
            web.logger(
                msg="Update domain profile: %s (%s)." % (domain, profile_type),
                domain=domain,
                event='update',
            )
            return (True, )
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 43
0
    def getDomainAccountSetting(self, domain,):
        result = self.getAllDomains(
            filter='(&(objectClass=mailDomain)(domainName=%s))' % domain,
            attrs=['domainName', 'accountSetting', ],
        )

        if result[0] is True:
            allDomains = result[1]
        else:
            return result

        # Get accountSetting of current domain.
        try:
            allAccountSettings = ldaputils.getAccountSettingFromLdapQueryResult(allDomains, key='domainName')
            return (True, allAccountSettings.get(domain, {}))
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 44
0
    def deleteSingleUserFromGroups(self, mail):
        self.mail = web.safestr(mail)
        if not iredutils.is_email(self.mail):
            return (False, "INVALID_MAIL")

        # Get domain name of this account.
        self.domain = self.mail.split("@")[-1]

        # Get dn of mail user and domain.
        self.dnUser = ldaputils.convert_keyword_to_dn(self.mail, accountType="user")
        self.dnDomain = ldaputils.convert_keyword_to_dn(self.domain, accountType="domain")

        if self.dnUser[0] is False:
            return self.dnUser

        if self.dnDomain[0] is False:
            return self.dnDomain

        try:
            # Get accounts which contains destination email.
            objsHasUser = self.conn.search_s(
                self.dnDomain, ldap.SCOPE_SUBTREE, self.getFilterOfDeleteUserFromGroups(self.mail), ["dn"]
            )

            if len(objsHasUser) >= 1:
                connutils = connUtils.Utils()
                for obj in objsHasUser:
                    if obj[0].endswith(attrs.DN_BETWEEN_ALIAS_AND_DOMAIN + self.dnDomain) or obj[0].endswith(
                        attrs.DN_BETWEEN_USER_AND_DOMAIN + self.dnDomain
                    ):
                        # Remove address from alias and user.
                        connutils.addOrDelAttrValue(
                            dn=obj[0], attr="mailForwardingAddress", value=self.mail, action="delete"
                        )
                    elif obj[0].endswith("ou=Externals," + self.domaindn):
                        # Remove address from external member list.
                        connutils.addOrDelAttrValue(dn=obj[0], attr="mail", value=self.mail, action="delete")
                    else:
                        pass
            else:
                pass

            return (True,)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 45
0
    def profile(self, mail, attributes=attrs.ADMIN_ATTRS_ALL):
        self.mail = web.safestr(mail)
        self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='admin')
        if self.dn[0] is False:
            return self.dn

        try:
            self.admin_profile = self.conn.search_s(
                self.dn,
                ldap.SCOPE_BASE,
                '(&(objectClass=mailAdmin)(mail=%s))' % self.mail,
                attributes,
            )
            return (True, self.admin_profile)
        except ldap.NO_SUCH_OBJECT:
            return (False, 'NO_SUCH_OBJECT')
        except Exception as e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 46
0
    def update(self, profile_type, mail, data):
        self.profile_type = web.safestr(profile_type)
        self.mail = web.safestr(mail)
        self.username, self.domain = self.mail.split("@", 1)

        if session.get("domainGlobalAdmin") is not True and session.get("username") != self.mail:
            # Don't allow to view/update other admins' profile.
            return (False, "PERMISSION_DENIED")

        self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType="admin")
        if self.dn[0] is False:
            return self.dn

        mod_attrs = []
        if self.profile_type == "general":
            # Get preferredLanguage.
            lang = web.safestr(data.get("preferredLanguage", "en_US"))
            mod_attrs += [(ldap.MOD_REPLACE, "preferredLanguage", lang)]

            # Get cn.
            cn = data.get("cn", None)
            mod_attrs += ldaputils.getSingleModAttr(attr="cn", value=cn, default=self.username)

            first_name = data.get("first_name", "")
            mod_attrs += ldaputils.getSingleModAttr(attr="givenName", value=first_name, default=self.username)

            last_name = data.get("last_name", "")
            mod_attrs += ldaputils.getSingleModAttr(attr="sn", value=last_name, default=self.username)

            # Get accountStatus.
            if "accountStatus" in data.keys():
                accountStatus = "active"
            else:
                accountStatus = "disabled"

            mod_attrs += [(ldap.MOD_REPLACE, "accountStatus", accountStatus)]

            try:
                # Modify profiles.
                self.conn.modify_s(self.dn, mod_attrs)
                if session.get("username") == self.mail and session.get("lang", "en_US") != lang:
                    session["lang"] = lang
            except ldap.LDAPError, e:
                return (False, ldaputils.getExceptionDesc(e))
Esempio n. 47
0
    def profile(self, domain):
        self.domain = web.safestr(domain)
        self.dn = ldaputils.convKeywordToDN(self.domain, accountType='domain')

        try:
            self.domain_profile = self.conn.search_s(
                self.dn,
                ldap.SCOPE_BASE,
                '(&(objectClass=mailDomain)(domainName=%s))' % self.domain,
                attrs.DOMAIN_ATTRS_ALL,
            )
            if len(self.domain_profile) == 1:
                return (True, self.domain_profile)
            else:
                return (False, 'NO_SUCH_DOMAIN')
        except ldap.NO_SUCH_OBJECT:
            return (False, 'NO_SUCH_OBJECT')
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 48
0
    def add(self, data):
        self.cn = data.get("cn")
        self.mail = web.safestr(data.get("mail")).strip().lower()

        if not iredutils.is_email(self.mail):
            return (False, "INVALID_MAIL")

        self.domainGlobalAdmin = web.safestr(data.get("domainGlobalAdmin", "no"))
        if self.domainGlobalAdmin not in ["yes", "no"]:
            self.domainGlobalAdmin = "no"

        self.preferredLanguage = web.safestr(data.get("preferredLanguage", "en_US"))

        # Check password.
        self.newpw = web.safestr(data.get("newpw"))
        self.confirmpw = web.safestr(data.get("confirmpw"))

        result = iredutils.verify_new_password(self.newpw, self.confirmpw)
        if result[0] is True:
            self.passwd = iredutils.generate_password_hash(result[1])
        else:
            return result

        ldif = iredldif.ldif_mailadmin(
            mail=self.mail,
            passwd=self.passwd,
            cn=self.cn,
            preferredLanguage=self.preferredLanguage,
            domainGlobalAdmin=self.domainGlobalAdmin,
        )

        self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType="admin")
        if self.dn[0] is False:
            return self.dn

        try:
            self.conn.add_s(self.dn, ldif)
            web.logger(msg="Create admin: %s." % (self.mail), event="create")
            return (True,)
        except ldap.ALREADY_EXISTS:
            return (False, "ALREADY_EXISTS")
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 49
0
    def delete(self, domain, mails=[]):
        if mails is None or len(mails) == 0:
            return (False, 'NO_ACCOUNT_SELECTED')

        self.domain = web.safestr(domain)
        self.mails = [
            str(v) for v in mails
            if iredutils.is_email(v) and str(v).endswith('@' + self.domain)
        ]
        if not len(self.mails) > 0:
            return (False, 'INVALID_MAIL')

        self.domaindn = ldaputils.convert_keyword_to_dn(self.domain,
                                                        accountType='domain')
        if self.domaindn[0] is False:
            return self.domaindn

        if not iredutils.is_domain(self.domain):
            return (False, 'INVALID_DOMAIN_NAME')

        result = {}
        for mail in self.mails:
            self.mail = web.safestr(mail)

            try:
                # Delete user object (ldap.SCOPE_BASE).
                self.deleteSingleUser(self.mail, )

                # Delete user object and whole sub-tree.
                # Get dn of mail user and domain.
                """
                self.userdn = ldaputils.convert_keyword_to_dn(self.mail, accountType='user')
                deltree.DelTree(self.conn, self.userdn, ldap.SCOPE_SUBTREE)

                # Log delete action.
                web.logger(
                    msg="Delete user: %s." % (self.mail),
                    domain=self.mail.split('@')[1],
                    event='delete',
                )
                """
            except ldap.LDAPError, e:
                result[self.mail] = ldaputils.getExceptionDesc(e)
Esempio n. 50
0
    def add(self, data):
        self.cn = data.get('cn')
        self.mail = web.safestr(data.get('mail')).strip().lower()

        if not iredutils.is_email(self.mail):
            return (False, 'INVALID_MAIL')

        self.domainGlobalAdmin = web.safestr(data.get('domainGlobalAdmin', 'no'))
        if self.domainGlobalAdmin not in ['yes', 'no', ]:
            self.domainGlobalAdmin = 'no'

        self.preferredLanguage = web.safestr(data.get('preferredLanguage', 'en_US'))

        # Check password.
        self.newpw = web.safestr(data.get('newpw'))
        self.confirmpw = web.safestr(data.get('confirmpw'))

        result = iredutils.verify_new_password(self.newpw, self.confirmpw)
        if result[0] is True:
            self.passwd = ldaputils.generate_ldap_password(result[1])
        else:
            return result

        ldif = iredldif.ldif_mailadmin(
                mail=self.mail,
                passwd=self.passwd,
                cn=self.cn,
                preferredLanguage=self.preferredLanguage,
                domainGlobalAdmin=self.domainGlobalAdmin,
                )

        self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='admin')
        if self.dn[0] is False:
            return self.dn

        try:
            self.conn.add_s(self.dn, ldif)
            web.logger(msg="Create admin: %s." % (self.mail), event='create',)
            return (True,)
        except ldap.ALREADY_EXISTS:
            return (False, 'ALREADY_EXISTS')
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 51
0
    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 action == 'add' or action == 'assign':
            try:
                self.conn.modify_s(self.dn, [(ldap.MOD_ADD, attr, value)])
                return (True,)
            except ldap.NO_SUCH_OBJECT:
                return (True,)
                #return (False, 'OBJECT_NOT_EXIST')
            except ldap.TYPE_OR_VALUE_EXISTS:
                return (True,)
            except Exception, e:
                return (False, ldaputils.getExceptionDesc(e))
Esempio n. 52
0
    def getManagedDomains(self, mail, attrs=attrs.ADMIN_ATTRS_ALL, listedOnly=False):
        self.mail = web.safestr(mail)
        if not iredutils.is_email(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))
Esempio n. 53
0
    def delete(self, mails):
        if mails is None or len(mails) == 0:
            return (False, 'NO_ACCOUNT_SELECTED')

        result = {}

        for mail in mails:
            self.mail = web.safestr(mail)
            dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='admin')
            if dn[0] is False:
                return dn

            try:
                connUtils.delete_ldap_tree(dn=dn, conn=self.conn)
                web.logger(msg="Delete admin: %s." % (self.mail,), event='delete',)
            except ldap.NO_SUCH_OBJECT:
                # This is a mail user admin
                dn = ldaputils.convert_keyword_to_dn(self.mail, accountType='user')
                try:
                    connutils = connUtils.Utils()
                    # Delete enabledService=domainadmin
                    connutils.addOrDelAttrValue(dn=dn,
                                                attr='enabledService',
                                                value='domainadmin',
                                                action='delete')

                    # Delete domainGlobalAdmin=yes
                    connutils.addOrDelAttrValue(dn=dn,
                                                attr='domainGlobalAdmin',
                                                value='yes',
                                                action='delete')
                    web.logger(msg="Delete admin: %s." % (self.mail), event='delete')
                except Exception as e:
                    result[self.mail] = str(e)
            except ldap.LDAPError as e:
                result[self.mail] = str(e)

        if result == {}:
            return (True,)
        else:
            return (False, ldaputils.getExceptionDesc(result))
Esempio n. 54
0
    def profile(self, domain):
        self.domain = web.safestr(domain)
        self.dn = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain')
        if self.dn[0] is False:
            return self.dn

        try:
            self.domain_profile = self.conn.search_s(
                self.dn,
                ldap.SCOPE_BASE,
                '(&(objectClass=mailDomain)(domainName=%s))' % self.domain,
                attrs.DOMAIN_ATTRS_ALL,
            )
            if len(self.domain_profile) == 1:
                return (True, self.domain_profile)
            else:
                return (False, 'NO_SUCH_DOMAIN')
        except ldap.NO_SUCH_OBJECT:
            return (False, 'NO_SUCH_OBJECT')
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 55
0
    def getNumberOfCurrentAccountsUnderDomain(self, domain, accountType="user", filter=None):
        # accountType in ['user', 'list', 'alias',]
        self.domain = web.safestr(domain)
        self.domaindn = ldaputils.convert_keyword_to_dn(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))
Esempio n. 56
0
    def update(self, profile_type, domain, data):
        self.profile_type = web.safestr(profile_type)
        self.domain = web.safestr(domain)
        self.domaindn = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain')
        if self.domaindn[0] is False:
            return self.domaindn

        connutils = connUtils.Utils()
        self.accountSetting = []
        mod_attrs = []

        # Allow normal admin to update profiles.
        if self.profile_type == 'general':
            cn = data.get('cn', None)
            mod_attrs += ldaputils.getSingleModAttr(attr='cn', value=cn, default=self.domain)

        # Allow global admin to update profiles.
        if session.get('domainGlobalAdmin') is True:
            if self.profile_type == 'general':
                # Get accountStatus.
                if 'accountStatus' in data.keys():
                    accountStatus = 'active'
                else:
                    accountStatus = 'disabled'

                mod_attrs += [(ldap.MOD_REPLACE, 'accountStatus', accountStatus)]

        try:
            dn = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain')
            if dn[0] is False:
                return dn

            self.conn.modify_s(dn, mod_attrs)
            web.logger(msg="Update domain profile: %s (%s)." % (domain, profile_type),
                       domain=domain,
                       event='update',
                      )
            return (True,)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 57
0
    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.is_domain(domain):
            return (False, "INVALID_DOMAIN_NAME")

        dn = ldaputils.convert_keyword_to_dn(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))
Esempio n. 58
0
    def update(self, profile_type, domain, data):
        self.profile_type = web.safestr(profile_type)
        self.domain = web.safestr(domain)
        self.domaindn = ldaputils.convKeywordToDN(self.domain, accountType='domain')

        connutils = connUtils.Utils()
        self.accountSetting = []
        mod_attrs = []

        # Allow normal admin to update profiles.
        if self.profile_type == 'general':
            cn = data.get('cn', None)
            mod_attrs += ldaputils.getSingleModAttr(attr='cn', value=cn, default=self.domain)
        else:
            pass

        # Allow global admin to update profiles.
        if session.get('domainGlobalAdmin') is True:
            if self.profile_type == 'general':
                # Get accountStatus.
                if 'accountStatus' in data.keys():
                    accountStatus = 'active'
                else:
                    accountStatus = 'disabled'

                mod_attrs += [ (ldap.MOD_REPLACE, 'accountStatus', accountStatus) ]
            else:
                pass

        else:
            pass

        try:
            dn = ldaputils.convKeywordToDN(self.domain, accountType='domain')
            self.conn.modify_s(dn, mod_attrs)
            return (True,)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Esempio n. 59
0
    def getDomainCurrentQuotaSizeFromLDAP(self, domain):
        self.domain = web.safestr(domain).strip().lower()
        if not iredutils.is_domain(self.domain):
            return (False, "INVALID_DOMAIN_NAME")

        self.domainDN = ldaputils.convert_keyword_to_dn(self.domain, accountType="domain")

        # Initial @domainCurrentQuotaSize
        self.domainCurrentQuotaSize = 0

        try:
            # Use '(!([email protected]))' 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))
Esempio n. 60
0
                try:
                    group_dn = 'ou=' + str(i) + ',' + str(self.dn)
                    group_ldif = iredldif.ldif_group(str(i))

                    self.conn.add_s(group_dn, group_ldif)
                except ldap.ALREADY_EXISTS:
                    pass
                except ldap.LDAPError, e:
                    msg[i] = str(e)
        else:
            pass

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

    # List all domain admins.
    def getDomainAdmins(self, domain):
        domain = web.safestr(domain)
        dn = ldaputils.convKeywordToDN(domain, accountType='domain')
        try:
            self.domainAdmins = self.conn.search_s(
                    dn,
                    ldap.SCOPE_BASE,
                    '(&(objectClass=mailDomain)(domainName=%s))' % domain,
                    ['domainAdmin'],
                    )
            return self.domainAdmins
        except Exception, e:
            return str(e)