Exemple #1
0
    def add(self, data):
        self.cn = data.get('cn', '')
        self.mail = web.safestr(data.get('mail')).strip().lower()

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

        # Check admin exist.
        connutils = connUtils.Utils()
        if connutils.isAdminExists(self.mail):
            return (False, 'ALREADY_EXISTS')

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

        # Get language setting.
        preferredLanguage = web.safestr(data.get('preferredLanguage', 'en_US'))

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

        result = iredutils.verifyNewPasswords(self.newpw, self.confirmpw)

        if result[0] is True:
            self.passwd = result[1]
        else:
            return result

        try:
            self.conn.insert(
                'dbmail_admins',
                username=self.mail,
                name=self.cn,
                password=iredutils.getSQLPassword(self.passwd),
                language=preferredLanguage,
                created=iredutils.getGMTTime(),
                active='1',
            )

            if self.domainGlobalAdmin == 'yes':
                self.conn.insert(
                    'dbmail_domain_admins',
                    username=self.mail,
                    domain='ALL',
                    created=iredutils.getGMTTime(),
                    active='1',
                )

            web.logger(msg="Create admin: %s." % (self.mail), event='create',)
            return (True,)
        except Exception, e:
            return (False, str(e))
    def add(self, data):
        self.cn = data.get('cn', '')
        self.mail = web.safestr(data.get('mail')).strip().lower()

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

        # Check admin exist.
        connutils = connUtils.Utils()
        if connutils.isAdminExists(self.mail):
            return (False, 'ALREADY_EXISTS')

        # Get domainGlobalAdmin setting.
        self.domainGlobalAdmin = 'yes'

        # Get language setting.
        self.preferredLanguage = web.safestr(data.get('preferredLanguage', 'en_US'))

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

        result = iredutils.verifyNewPasswords(self.newpw, self.confirmpw)

        if result[0] is True:
            self.passwd = result[1]
        else:
            return result

        try:
            self.conn.insert(
                'admin',
                username=self.mail,
                name=self.cn,
                password=iredutils.getSQLPassword(self.passwd),
                language=self.preferredLanguage,
                created=iredutils.sqlNOW,
                active='1',
            )

            if self.domainGlobalAdmin == 'yes':
                self.conn.insert(
                    'domain_admins',
                    username=self.mail,
                    domain='ALL',
                    created=iredutils.sqlNOW,
                    active='1',
                )

            web.logger(msg="Create admin: %s." % (self.mail), event='create',)
            return (True,)
        except Exception, e:
            return (False, str(e))
Exemple #3
0
    def add(self, data):
        self.cn = data.get('cn')
        self.mail = web.safestr(data.get('mail')).strip().lower()

        if not iredutils.isEmail(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.verifyNewPasswords(self.newpw, self.confirmpw)
        if result[0] is True:
            self.passwd = ldaputils.generatePasswd(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.convKeywordToDN(self.mail, accountType='admin')

        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))
    def add(self, data):
        self.cn = data.get('cn')
        self.mail = web.safestr(data.get('mail')).strip().lower()

        if not iredutils.isEmail(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.verifyNewPasswords(self.newpw, self.confirmpw)
        if result[0] is True:
            self.passwd = ldaputils.generatePasswd(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.convKeywordToDN(self.mail, accountType='admin')

        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))
    def add(self, domain, data):
        # Get domain name, username, cn.
        self.domain = web.safestr(data.get('domainName')).strip().lower()
        self.username = web.safestr(data.get('username')).strip().lower()
        self.mail = self.username + '@' + self.domain
        self.groups = data.get('groups', [])

        if not iredutils.isDomain(self.domain) or not iredutils.isEmail(self.mail):
            return (False, 'MISSING_DOMAIN_OR_USERNAME')

        # Check account existing.
        connutils = connUtils.Utils()
        if connutils.isAccountExists(domain=self.domain, filter='(mail=%s)' % self.mail):
            return (False, 'ALREADY_EXISTS')

        # Get @domainAccountSetting.
        domainLib = domainlib.Domain()
        result_domain_profile = domainLib.profile(self.domain)

        # Initial parameters.
        domainAccountSetting = {}
        self.aliasDomains = []

        if result_domain_profile[0] is True:
            domainProfile = result_domain_profile[1]
            domainAccountSetting = ldaputils.getAccountSettingFromLdapQueryResult(domainProfile, key='domainName').get(self.domain, {})
            self.aliasDomains = domainProfile[0][1].get('domainAliasName', [])

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

        result = iredutils.verifyNewPasswords(self.newpw, self.confirmpw,
                                          min_passwd_length=domainAccountSetting.get('minPasswordLength', '0'),
                                          max_passwd_length=domainAccountSetting.get('maxPasswordLength', '0'),
                                         )
        if result[0] is True:
            self.passwd = ldaputils.generatePasswd(result[1])
        else:
            return result

        # Get display name.
        self.cn = data.get('cn')

        # Get user quota. Unit is MB.
        # 0 or empty is not allowed if domain quota is set, set to
        # @defaultUserQuota or @domainSpareQuotaSize

        # Initial final mailbox quota.
        self.quota = 0

        # Get mail quota from web form.
        defaultUserQuota = domainLib.getDomainDefaultUserQuota(self.domain, domainAccountSetting)
        self.mailQuota = str(data.get('mailQuota')).strip()
        if self.mailQuota.isdigit():
            self.mailQuota = int(self.mailQuota)
        else:
            self.mailQuota = defaultUserQuota

        # 0 means unlimited.
        domainQuotaSize, domainQuotaUnit = domainAccountSetting.get('domainQuota', '0:GB').split(':')
        if int(domainQuotaSize) == 0:
            # Unlimited.
            self.quota = self.mailQuota
        else:
            # Get domain quota, convert to MB.
            if domainQuotaUnit == 'TB':
                domainQuota = int(domainQuotaSize) * 1024 * 1024 # TB
            elif domainQuotaUnit == 'GB':
                domainQuota = int(domainQuotaSize) * 1024  # GB
            else:
                domainQuota = int(domainQuotaSize)  # MB

            # TODO Query whole domain and calculate current quota size, not read from domain profile.
            #domainCurrentQuotaSize = int(domainProfile[0][1].get('domainCurrentQuotaSize', ['0'])[0]) / (1024*1024)
            result = connutils.getDomainCurrentQuotaSizeFromLDAP(domain=self.domain)
            if result[0] is True:
                domainCurrentQuotaSize = result[1]
            else:
                domainCurrentQuotaSize = 0

            # Spare quota.
            domainSpareQuotaSize = domainQuota - domainCurrentQuotaSize/(1024*1024)

            if domainSpareQuotaSize <= 0:
                return (False, 'EXCEEDED_DOMAIN_QUOTA_SIZE')

            # Get FINAL mailbox quota.
            if self.mailQuota == 0:
                self.quota = domainSpareQuotaSize
            else:
                if domainSpareQuotaSize > self.mailQuota:
                    self.quota = self.mailQuota
                else:
                    self.quota = domainSpareQuotaSize

        # Get default groups.
        self.groups = [ web.safestr(v)
                       for v in domainAccountSetting.get('defaultList', '').split(',')
                       if iredutils.isEmail(v)
                      ]

        self.defaultStorageBaseDirectory = domainAccountSetting.get('defaultStorageBaseDirectory', None)

        # Get default mail list which set in domain accountSetting.
        ldif = iredldif.ldif_mailuser(
            domain=self.domain,
            aliasDomains=self.aliasDomains,
            username=self.username,
            cn=self.cn,
            passwd=self.passwd,
            quota=self.quota,
            groups=self.groups,
            storageBaseDirectory=self.defaultStorageBaseDirectory,
        )

        if attrs.RDN_USER == 'mail':
            self.dn = ldaputils.convKeywordToDN(self.mail, accountType='user')
        elif attrs.RDN_USER == 'cn':
            self.dn = 'cn=' + self.cn + ',' + attrs.DN_BETWEEN_USER_AND_DOMAIN + \
                    ldaputils.convKeywordToDN(self.domain, accountType='domain')
        elif attrs.RDN_USER == 'uid':
            self.dn = 'uid=' + self.username + ',' + attrs.DN_BETWEEN_USER_AND_DOMAIN + \
                    ldaputils.convKeywordToDN(self.domain, accountType='domain')
        else:
            return (False, 'UNSUPPORTED_USER_RDN')

        try:
            self.conn.add_s(ldap.filter.escape_filter_chars(self.dn), ldif,)
            web.logger(msg="Create user: %s." % (self.mail), domain=self.domain, event='create',)
            return (True,)
        except ldap.ALREADY_EXISTS:
            return (False, 'ALREADY_EXISTS')
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
            else:
                accountStatus = 'disabled'
            mod_attrs += [ (ldap.MOD_REPLACE, 'accountStatus', accountStatus) ]

        elif self.profile_type == 'password':
            # Get password length from @domainAccountSetting.
            minPasswordLength = domainAccountSetting.get('minPasswordLength', cfg.general.get('min_passwd_length', '0'))
            maxPasswordLength = domainAccountSetting.get('maxPasswordLength', cfg.general.get('max_passwd_length', '0'))

            # Get new passwords from user input.
            self.newpw = str(data.get('newpw', None))
            self.confirmpw = str(data.get('confirmpw', None))

            result = iredutils.verifyNewPasswords(
                newpw=self.newpw,
                confirmpw=self.confirmpw,
                min_passwd_length=minPasswordLength,
                max_passwd_length=maxPasswordLength,
            )
            if result[0] is True:
                self.passwd = ldaputils.generatePasswd(result[1])
                mod_attrs += [ (ldap.MOD_REPLACE, 'userPassword', self.passwd) ]
            else:
                return result

        try:
            self.conn.modify_s(self.dn, mod_attrs)
            return (True,)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Exemple #7
0
            for i in self.domainsAddAdmins:
                result = connutils.addOrDelAttrValue(
                    dn=ldaputils.convKeywordToDN(i, accountType='domain'),
                    attr='domainAdmin',
                    value=self.mail,
                    action='add',
                )
                if result[0] is False:
                    return result
            return (True, )
        elif self.profile_type == 'password':
            self.cur_passwd = data.get('oldpw', None)
            self.newpw = data.get('newpw')
            self.confirmpw = data.get('confirmpw')

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

            # Change password.
            if self.cur_passwd is None and session.get(
                    'domainGlobalAdmin') is True:
                # Reset password without verify old password.
                self.cur_passwd = None
            else:
                self.cur_passwd = str(self.cur_passwd)

            connutils = connUtils.Utils()
            result = connutils.changePasswd(
Exemple #8
0
    def add(self, domain, data):
        # Get domain name, username, cn.
        self.domain = web.safestr(data.get('domainName')).strip().lower()
        self.username = web.safestr(data.get('username')).strip().lower()
        self.mail = self.username + '@' + self.domain
        self.groups = data.get('groups', [])

        if not iredutils.isDomain(self.domain) or not iredutils.isEmail(
                self.mail):
            return (False, 'MISSING_DOMAIN_OR_USERNAME')

        # Check account existing.
        connutils = connUtils.Utils()
        if connutils.isAccountExists(domain=self.domain,
                                     filter='(mail=%s)' % self.mail):
            return (False, 'ALREADY_EXISTS')

        # Get @domainAccountSetting.
        domainLib = domainlib.Domain()
        result_domain_profile = domainLib.profile(self.domain)

        # Initial parameters.
        domainAccountSetting = {}
        self.aliasDomains = []

        if result_domain_profile[0] is True:
            domainProfile = result_domain_profile[1]
            domainAccountSetting = ldaputils.getAccountSettingFromLdapQueryResult(
                domainProfile, key='domainName').get(self.domain, {})
            self.aliasDomains = domainProfile[0][1].get('domainAliasName', [])

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

        result = iredutils.verifyNewPasswords(
            self.newpw,
            self.confirmpw,
            min_passwd_length=domainAccountSetting.get('minPasswordLength',
                                                       '0'),
            max_passwd_length=domainAccountSetting.get('maxPasswordLength',
                                                       '0'),
        )
        if result[0] is True:
            self.passwd = ldaputils.generatePasswd(result[1])
        else:
            return result

        # Get display name.
        self.cn = data.get('cn')

        # Get user quota. Unit is MB.
        # 0 or empty is not allowed if domain quota is set, set to
        # @defaultUserQuota or @domainSpareQuotaSize

        # Initial final mailbox quota.
        self.quota = 0

        # Get mail quota from web form.
        defaultUserQuota = domainLib.getDomainDefaultUserQuota(
            self.domain, domainAccountSetting)
        self.mailQuota = str(data.get('mailQuota')).strip()
        if self.mailQuota.isdigit():
            self.mailQuota = int(self.mailQuota)
        else:
            self.mailQuota = defaultUserQuota

        # 0 means unlimited.
        domainQuotaSize, domainQuotaUnit = domainAccountSetting.get(
            'domainQuota', '0:GB').split(':')
        if int(domainQuotaSize) == 0:
            # Unlimited.
            self.quota = self.mailQuota
        else:
            # Get domain quota, convert to MB.
            if domainQuotaUnit == 'TB':
                domainQuota = int(domainQuotaSize) * 1024 * 1024  # TB
            elif domainQuotaUnit == 'GB':
                domainQuota = int(domainQuotaSize) * 1024  # GB
            else:
                domainQuota = int(domainQuotaSize)  # MB

            # TODO Query whole domain and calculate current quota size, not read from domain profile.
            #domainCurrentQuotaSize = int(domainProfile[0][1].get('domainCurrentQuotaSize', ['0'])[0]) / (1024*1024)
            result = connutils.getDomainCurrentQuotaSizeFromLDAP(
                domain=self.domain)
            if result[0] is True:
                domainCurrentQuotaSize = result[1]
            else:
                domainCurrentQuotaSize = 0

            # Spare quota.
            domainSpareQuotaSize = domainQuota - domainCurrentQuotaSize / (
                1024 * 1024)

            if domainSpareQuotaSize <= 0:
                return (False, 'EXCEEDED_DOMAIN_QUOTA_SIZE')

            # Get FINAL mailbox quota.
            if self.mailQuota == 0:
                self.quota = domainSpareQuotaSize
            else:
                if domainSpareQuotaSize > self.mailQuota:
                    self.quota = self.mailQuota
                else:
                    self.quota = domainSpareQuotaSize

        # Get default groups.
        self.groups = [
            web.safestr(v)
            for v in domainAccountSetting.get('defaultList', '').split(',')
            if iredutils.isEmail(v)
        ]

        self.defaultStorageBaseDirectory = domainAccountSetting.get(
            'defaultStorageBaseDirectory', None)

        # Get default mail list which set in domain accountSetting.
        ldif = iredldif.ldif_mailuser(
            domain=self.domain,
            aliasDomains=self.aliasDomains,
            username=self.username,
            cn=self.cn,
            passwd=self.passwd,
            quota=self.quota,
            groups=self.groups,
            storageBaseDirectory=self.defaultStorageBaseDirectory,
        )

        if attrs.RDN_USER == 'mail':
            self.dn = ldaputils.convKeywordToDN(self.mail, accountType='user')
        elif attrs.RDN_USER == 'cn':
            self.dn = 'cn=' + self.cn + ',' + attrs.DN_BETWEEN_USER_AND_DOMAIN + \
                    ldaputils.convKeywordToDN(self.domain, accountType='domain')
        elif attrs.RDN_USER == 'uid':
            self.dn = 'uid=' + self.username + ',' + attrs.DN_BETWEEN_USER_AND_DOMAIN + \
                    ldaputils.convKeywordToDN(self.domain, accountType='domain')
        else:
            return (False, 'UNSUPPORTED_USER_RDN')

        try:
            self.conn.add_s(
                ldap.filter.escape_filter_chars(self.dn),
                ldif,
            )
            web.logger(
                msg="Create user: %s." % (self.mail),
                domain=self.domain,
                event='create',
            )
            return (True, )
        except ldap.ALREADY_EXISTS:
            return (False, 'ALREADY_EXISTS')
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Exemple #9
0
            mod_attrs += [(ldap.MOD_REPLACE, 'accountStatus', accountStatus)]

        elif self.profile_type == 'password':
            # Get password length from @domainAccountSetting.
            minPasswordLength = domainAccountSetting.get(
                'minPasswordLength', cfg.general.get('min_passwd_length', '0'))
            maxPasswordLength = domainAccountSetting.get(
                'maxPasswordLength', cfg.general.get('max_passwd_length', '0'))

            # Get new passwords from user input.
            self.newpw = str(data.get('newpw', None))
            self.confirmpw = str(data.get('confirmpw', None))

            result = iredutils.verifyNewPasswords(
                newpw=self.newpw,
                confirmpw=self.confirmpw,
                min_passwd_length=minPasswordLength,
                max_passwd_length=maxPasswordLength,
            )
            if result[0] is True:
                self.passwd = ldaputils.generatePasswd(result[1])
                mod_attrs += [(ldap.MOD_REPLACE, 'userPassword', self.passwd)]
            else:
                return result

        try:
            self.conn.modify_s(self.dn, mod_attrs)
            return (True, )
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
    def add(self, domain, data):
        # Get domain name, username, cn.
        self.domain = web.safestr(data.get('domainName')).strip().lower()
        self.username = web.safestr(data.get('username')).strip().lower()
        self.mail = self.username + '@' + self.domain

        if self.domain != domain:
            return (False, 'PERMISSION_DENIED')

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

        # Check account existing.
        connutils = connUtils.Utils()
        if connutils.isEmailExists(mail=self.mail):
            return (False, 'ALREADY_EXISTS')

        # Get domain profile.
        domainLib = domainlib.Domain()
        resultOfDomainProfile = domainLib.profile(domain=self.domain)

        if resultOfDomainProfile[0] is True:
            self.domainProfile = resultOfDomainProfile[1]
        else:
            return resultOfDomainProfile

        # Check account limit.
        adminLib = adminlib.Admin()
        numberOfExistAccounts = adminLib.getNumberOfManagedAccounts(accountType='user', domains=[self.domain])

        if self.domainProfile.mailboxes == 0:
            # Unlimited.
            pass
        elif self.domainProfile.mailboxes <= numberOfExistAccounts:
            return (False, 'EXCEEDED_DOMAIN_ACCOUNT_LIMIT')

        # Check spare quota and number of spare account limit.
        # Get quota from <form>
        self.mailQuota = str(data.get('mailQuota')).strip()
        self.defaultUserQuota = self.domainProfile.get('defaultuserquota', 0)

        if self.mailQuota.isdigit():
            self.mailQuota = int(self.mailQuota)
        else:
            self.mailQuota = self.defaultUserQuota

        # Re-calculate mail quota if this domain has limited max quota.
        if self.domainProfile.maxquota > 0:
            # Get used quota.
            qr = domainLib.getAllocatedQuotaSize(domain=self.domain)
            if qr[0] is True:
                self.allocatedQuota = qr[1]
            else:
                return qr

            spareQuota = self.domainProfile.maxquota - self.allocatedQuota

            if spareQuota > 0:
                if spareQuota < self.mailQuota:
                    self.mailQuota = spareQuota
            else:
                # No enough quota.
                return (False, 'EXCEEDED_DOMAIN_QUOTA_SIZE')

        #
        # Get password from <form>.
        #
        self.newpw = str(data.get('newpw', ''))
        self.confirmpw = str(data.get('confirmpw', ''))

        # Get password length limit from domain profile or global setting.
        self.minPasswordLength = self.domainProfile.get('minpasswordlength',cfg.general.get('min_passwd_length', '0'))
        self.maxPasswordLength = self.domainProfile.get('maxpasswordlength', cfg.general.get('max_passwd_length', '0'))

        resultOfPW = iredutils.verifyNewPasswords(
            self.newpw,
            self.confirmpw,
            min_passwd_length=self.minPasswordLength,
            max_passwd_length=self.maxPasswordLength,
        )
        if resultOfPW[0] is True:
            self.passwd = iredutils.getSQLPassword(resultOfPW[1])
        else:
            return resultOfPW

        # Get display name from <form>
        self.cn = data.get('cn', '')

        # Assign new user to default mail aliases.
        assignedAliases = [str(v).lower()
                           for v in str(self.domainProfile.defaultuseraliases).split(',')
                           if iredutils.isEmail(v)
                          ]

        try:
            # Store new user in SQL db.
            self.conn.insert(
                'mailbox',
                domain=self.domain,
                username=self.mail,
                password=self.passwd,
                name=self.cn,
                maildir=iredutils.setMailMessageStore(self.mail),
                quota=self.mailQuota,
                created=iredutils.sqlNOW,
                active='1',
                local_part=self.username,
            )

            # Assign new user to default mail aliases.
            if len(assignedAliases) > 0:
                for ali in assignedAliases:
                    try:
                        self.conn.query(
                            '''
                            UPDATE alias
                            SET goto=CONCAT(goto, %s)
                            WHERE address=%s AND domain=%s
                            ''' % (
                                web.sqlquote(','+self.mail),
                                web.sqlquote(ali),
                                web.sqlquote(self.domain),
                            )
                        )
                    except:
                        pass

            # Create an alias account: address=goto.
            self.conn.insert(
                'alias',
                address=self.mail,
                goto=self.mail,
                domain=self.domain,
                created=iredutils.sqlNOW,
                active='1',
            )

            web.logger(msg="Create user: %s." % (self.mail), domain=self.domain, event='create',)
            return (True,)
        except Exception, e:
            return (False, str(e))
                    self.conn.insert(
                        'alias',
                        **inserts
                    )
                    return (True,)
                except Exception, e:
                    return (False, str(e))
            else:
                return (True,)

        elif self.profile_type == 'password':
            self.newpw = str(data.get('newpw', ''))
            self.confirmpw = str(data.get('confirmpw', ''))

            # Verify new passwords.
            qr = iredutils.verifyNewPasswords(self.newpw, self.confirmpw)
            if qr[0] is True:
                self.passwd = iredutils.getSQLPassword(qr[1])
            else:
                return qr

            # Hash/encrypt new password.
            updates['password'] = self.passwd

        elif self.profile_type == 'advanced':
            # Get enabled services.
            self.enabledService = [str(v).lower()
                                   for v in data.get('enabledService', [])
                                   if v in ENABLED_SERVICES
                                  ]
            self.disabledService = [v for v in ENABLED_SERVICES if v not in self.enabledService]
Exemple #12
0
    def add(self, domain, data):
        # Get domain name, username, cn.
        self.domain = web.safestr(data.get('domainName')).strip().lower()
        self.username = web.safestr(data.get('username')).strip().lower()
        self.mail = self.username + '@' + self.domain

        if self.domain != domain:
            return (False, 'PERMISSION_DENIED')

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

        # Check account existing.
        connutils = connUtils.Utils()
        if connutils.isEmailExists(mail=self.mail):
            return (False, 'ALREADY_EXISTS')

        # Get domain profile.
        domainLib = domainlib.Domain()
        resultOfDomainProfile = domainLib.profile(domain=self.domain)

        if resultOfDomainProfile[0] is True:
            self.domainProfile = resultOfDomainProfile[1]
        else:
            return resultOfDomainProfile

        # Check account limit.
        adminLib = adminlib.Admin()
        numberOfExistAccounts = adminLib.getNumberOfManagedAccounts(
            accountType='user', domains=[self.domain])

        if self.domainProfile.mailboxes == 0:
            # Unlimited.
            pass
        elif self.domainProfile.mailboxes <= numberOfExistAccounts:
            return (False, 'EXCEEDED_DOMAIN_ACCOUNT_LIMIT')

        # Check spare quota and number of spare account limit.
        # Get quota from <form>
        self.mailQuota = str(data.get('mailQuota')).strip()
        self.defaultUserQuota = self.domainProfile.get('defaultuserquota', 0)

        if self.mailQuota.isdigit():
            self.mailQuota = int(self.mailQuota)
        else:
            self.mailQuota = self.defaultUserQuota

        # Re-calculate mail quota if this domain has limited max quota.
        if self.domainProfile.maxquota > 0:
            # Get used quota.
            qr = domainLib.getAllocatedQuotaSize(domain=self.domain)
            if qr[0] is True:
                self.allocatedQuota = qr[1]
            else:
                return qr

            spareQuota = self.domainProfile.maxquota - self.allocatedQuota

            if spareQuota > 0:
                if spareQuota < self.mailQuota:
                    self.mailQuota = spareQuota
            else:
                # No enough quota.
                return (False, 'EXCEEDED_DOMAIN_QUOTA_SIZE')

        #
        # Get password from <form>.
        #
        self.newpw = str(data.get('newpw', ''))
        self.confirmpw = str(data.get('confirmpw', ''))

        # Get password length limit from domain profile or global setting.
        self.minPasswordLength = self.domainProfile.get(
            'minpasswordlength', cfg.general.get('min_passwd_length', '0'))
        self.maxPasswordLength = self.domainProfile.get(
            'maxpasswordlength', cfg.general.get('max_passwd_length', '0'))

        resultOfPW = iredutils.verifyNewPasswords(
            self.newpw,
            self.confirmpw,
            min_passwd_length=self.minPasswordLength,
            max_passwd_length=self.maxPasswordLength,
        )
        if resultOfPW[0] is True:
            self.passwd = iredutils.getSQLPassword(resultOfPW[1])
        else:
            return resultOfPW

        # Get display name from <form>
        self.cn = data.get('cn', '')

        # Assign new user to default mail aliases.
        assignedAliases = [
            str(v).lower()
            for v in str(self.domainProfile.defaultuseraliases).split(',')
            if iredutils.isEmail(v)
        ]

        try:
            # Store new user in SQL db.
            self.conn.insert(
                'mailbox',
                domain=self.domain,
                username=self.mail,
                password=self.passwd,
                name=self.cn,
                maildir=iredutils.setMailMessageStore(self.mail),
                quota=self.mailQuota,
                created=iredutils.sqlNOW,
                active='1',
                local_part=self.username,
            )

            # Assign new user to default mail aliases.
            if len(assignedAliases) > 0:
                for ali in assignedAliases:
                    try:
                        self.conn.query('''
                            UPDATE alias
                            SET goto=CONCAT(goto, %s)
                            WHERE address=%s AND domain=%s
                            ''' % (
                            web.sqlquote(',' + self.mail),
                            web.sqlquote(ali),
                            web.sqlquote(self.domain),
                        ))
                    except:
                        pass

            # Create an alias account: address=goto.
            self.conn.insert(
                'alias',
                address=self.mail,
                goto=self.mail,
                domain=self.domain,
                created=iredutils.sqlNOW,
                active='1',
            )

            web.logger(
                msg="Create user: %s." % (self.mail),
                domain=self.domain,
                event='create',
            )
            return (True, )
        except Exception, e:
            return (False, str(e))
Exemple #13
0
    def add(self, domain, data):
        # Get domain name, username, cn.
        self.domain = web.safestr(data.get('domainName')).strip().lower()
        self.username = web.safestr(data.get('username')).strip().lower()
        self.mail = self.username + '@' + self.domain
        sql_vars = {
            'mail': self.mail,
        }

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

        if self.domain != domain:
            return (False, 'PERMISSION_DENIED')

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

        # Check account existing.
        connutils = connUtils.Utils()
        if connutils.isEmailExists(self.mail):
            return (False, 'ALREADY_EXISTS')

        # Get domain profile.
        domainLib = domainlib.Domain()
        resultOfDomainProfile = domainLib.profile(domain=self.domain)

        if resultOfDomainProfile[0] is True:
            self.domainProfile = resultOfDomainProfile[1]
        else:
            return resultOfDomainProfile

        # Check account limit.
        adminLib = adminlib.Admin()
        numberOfExistAccounts = adminLib.getNumberOfManagedAccounts(
            accountType='user', domains=[self.domain])

        if self.domainProfile.mailboxes == -1:
            return (False, 'NOT_ALLOWED')
        elif self.domainProfile.mailboxes > 0:
            if self.domainProfile.mailboxes <= numberOfExistAccounts:
                return (False, 'EXCEEDED_DOMAIN_ACCOUNT_LIMIT')

        columns = {
            'userid': self.mail,
            'domain': self.domain,
        }

        # Check spare quota and number of spare account limit.
        # Get quota from form.
        self.mailQuota = str(data.get('mailQuota')).strip()
        self.defaultUserQuota = self.domainProfile.get('defaultuserquota', 0)

        if self.mailQuota.isdigit():
            self.mailQuota = int(self.mailQuota)
        else:
            self.mailQuota = self.defaultUserQuota

        # Re-calculate mail quota if this domain has max quota limit.
        if self.domainProfile.maxquota > 0:
            # Get used quota.
            qr = domainLib.getAllocatedQuotaSize(domain=self.domain)
            if qr[0] is True:
                self.allocatedQuota = qr[1]
            else:
                return qr

            spareQuota = self.domainProfile.maxquota - self.allocatedQuota / 1024 / 1024

            if spareQuota > 0:
                if spareQuota < self.mailQuota:
                    self.mailQuota = spareQuota
            else:
                # No enough quota.
                return (False, 'EXCEEDED_DOMAIN_QUOTA_SIZE')

        columns['maxmail_size'] = self.mailQuota * 1024 * 1024

        #
        # Get password from <form>.
        #
        newpw = web.safestr(data.get('newpw', ''))
        confirmpw = web.safestr(data.get('confirmpw', ''))

        # Get password length limit from domain profile or global setting.
        self.minPasswordLength = self.domainProfile.get(
            'minpasswordlength', cfg.general.get('min_passwd_length', '0'))
        self.maxPasswordLength = self.domainProfile.get(
            'maxpasswordlength', cfg.general.get('max_passwd_length', '0'))

        resultOfPW = iredutils.verifyNewPasswords(
            newpw,
            confirmpw,
            min_passwd_length=self.minPasswordLength,
            max_passwd_length=self.maxPasswordLength,
        )
        if resultOfPW[0] is True:
            if 'storePasswordInPlainText' in data:
                columns['passwd'] = iredutils.getSQLPassword(resultOfPW[1],
                                                             pwscheme='PLAIN')
                columns['encryption_type'] = ''
            else:
                columns['passwd'] = iredutils.getSQLPassword(resultOfPW[1])
                columns[
                    'encryption_type'] = settings.SQL_DEFAULT_PASSWD_SCHEME.lower(
                    )

        else:
            return resultOfPW

        # Get display name from <form>
        columns['name'] = data.get('cn', '')

        # Assign new user to default mail aliases.
        assignedAliases = [
            str(addr).lower()
            for addr in str(self.domainProfile.defaultuseraliases).split(',')
            if iredutils.isEmail(addr)
        ]

        try:
            # Store new user in SQL db.
            self.conn.insert('dbmail_users', **columns)

            # Get dbmail_users.user_idnr.
            qr = self.conn.select(
                'dbmail_users',
                vars=sql_vars,
                what='user_idnr,client_idnr',
                where='userid=$mail',
                limit=1,
            )
            p = qr[0]
            user_idnr, client_idnr = p.user_idnr, p.client_idnr

            self.conn.insert(
                'dbmail_aliases',
                alias=self.mail,
                deliver_to=user_idnr,
                client_idnr=client_idnr,
            )

            # Create and subscribe to default IMAP folders.
            if settings.DBMAIL_CREATE_DEFAULT_IMAP_FOLDERS:
                # Create default IMAP folders.
                imap_folders = [
                    '(%d, "%s")' % (user_idnr, fld)
                    for fld in settings.DBMAIL_DEFAULT_IMAP_FOLDERS
                ]
                self.conn.query(
                    '''INSERT INTO dbmail_mailboxes (owner_idnr, name) VALUES %s'''
                    % ','.join(imap_folders))

                # Subscribe to folders by default.
                self.conn.query(
                    '''INSERT INTO dbmail_subscription (user_id, mailbox_id)
                                SELECT owner_idnr, mailbox_idnr FROM dbmail_mailboxes WHERE owner_idnr = %d
                                ''' % user_idnr)

            # Assign new user to default mail aliases.
            if len(assignedAliases) > 0:
                for ali in assignedAliases:
                    try:
                        self.conn.update(
                            'dbmail_aliases',
                            vars={
                                'mail': self.mail,
                                'ali': ali,
                                'user_idnr': user_idnr,
                            },
                            where='alias = $ali AND deliver_to <> $user_idnr',
                            deliver_to=web.sqlliteral(
                                'CONCAT($mail, ",", deliver_to)'),
                        )
                    except:
                        pass

            vars_addition_sql = {
                'user_idnr': user_idnr,
                'mail': self.mail,
                'username': self.username,
                'domain': self.domain,
            }
            # Execute addition SQL commands after successfully created new users.
            if settings.DBMAIL_SQL_FOR_NEWLY_CREATED_USER:
                try:
                    for sql_cmd in settings.DBMAIL_SQL_FOR_NEWLY_CREATED_USER:
                        self.conn.query(sql_cmd, vars=vars_addition_sql)
                except Exception:
                    pass

            # Create Amavisd policy for newly created user.
            if settings.AMAVISD_EXECUTE_SQL_WITHOUT_ENABLED and settings.AMAVISD_SQL_FOR_NEWLY_CREATED_USER:
                try:
                    from libs.amavisd.core import AmavisdWrap
                    amwrap = AmavisdWrap()
                    for sql_cmd in settings.AMAVISD_SQL_FOR_NEWLY_CREATED_USER:
                        amwrap.db.query(sql_cmd, vars=vars_addition_sql)
                except:
                    pass

            web.logger(
                msg="Create user: %s." % (self.mail),
                domain=self.domain,
                event='create',
            )
            return (True, )
        except Exception, e:
            return (False, str(e))
Exemple #14
0
                )

                throttleLib.updateThrottlingSetting(
                    account=self.mail,
                    accountType='recipient',
                    setting=self.recipientThrottlingSetting,
                )
            except Exception, e:
                pass

        elif self.profile_type == 'password':
            newpw = str(data.get('newpw', ''))
            confirmpw = str(data.get('confirmpw', ''))

            # Verify new passwords.
            qr = iredutils.verifyNewPasswords(newpw, confirmpw)
            if qr[0] is True:
                if 'storePasswordInPlainText' in data:
                    self.passwd = iredutils.getSQLPassword(qr[1],
                                                           pwscheme='PLAIN')
                else:
                    self.passwd = iredutils.getSQLPassword(qr[1])
            else:
                return qr

            # Hash/encrypt new password.
            updates['passwd'] = self.passwd

        elif self.profile_type == 'advanced':
            # Get enabled services.
            """