Example #1
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')

        # 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.
        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.verify_new_password(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.generate_password_hash(self.passwd),
                language=self.preferredLanguage,
                created=iredutils.get_gmttime(),
                active='1',
            )

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

            web.logger(msg="Create admin: %s." % (self.mail), event='create',)
            return (True,)
        except Exception, e:
            return (False, str(e))
Example #2
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')

        # 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.
        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.verify_new_password(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.generate_password_hash(self.passwd),
                language=self.preferredLanguage,
                created=iredutils.get_gmttime(),
                active='1',
            )

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

            web.logger(msg="Create admin: %s." % (self.mail), event='create',)
            return (True,)
        except Exception, e:
            return (False, str(e))
Example #3
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))
Example #4
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))
Example #5
0
    def update(self, profile_type, mail, data):
        self.profile_type = web.safestr(profile_type)
        self.mail = str(mail).lower()
        self.domain = self.mail.split('@', 1)[-1]

        # Pre-defined update key:value.
        updates = {'modified': iredutils.get_gmttime()}

        if self.profile_type == 'general':
            # Get settings of domain admin and global admin
            managed_domain = ''
            if 'domainadmin' in data:
                # isadmin=1
                updates['isadmin'] = 1
                managed_domain = self.domain
            else:
                updates['isadmin'] = 0

            if session.get('domainGlobalAdmin'):
                if 'domainGlobalAdmin' in data:
                    updates['isadmin'] = 1
                    updates['isglobaladmin'] = 1
                    managed_domain = 'ALL'
                else:
                    updates['isglobaladmin'] = 0

            # Delete records in domain_admins first
            self.conn.delete('domain_admins',
                             vars={'username': self.mail},
                             where='username=$username')

            if updates.get('isadmin') == 1:
                try:
                    self.conn.insert('domain_admins',
                                     username=self.mail,
                                     domain=managed_domain,
                                     created=iredutils.get_gmttime(),
                                     active=1)
                except:
                    pass

            # Get name
            cn = data.get('cn', '')
            updates['name'] = cn

            # Get preferred language: short lang code. e.g. en_US, de_DE.
            preferred_lang = web.safestr(data.get('preferredLanguage',
                                                  'en_US'))
            # Must be equal to or less than 5 characters.
            if len(preferred_lang) > 5:
                preferred_lang = preferred_lang[:5]
            updates['language'] = preferred_lang
            # Update language immediately.
            if session.get('username') == self.mail and \
               session.get('lang', 'en_US') != preferred_lang:
                session['lang'] = preferred_lang

            # Get account status
            if 'accountStatus' in list(data.keys()):
                updates['active'] = 1
            else:
                updates['active'] = 0

            # Get mail quota size.
            mailQuota = str(data.get('mailQuota'))
            if mailQuota.isdigit():
                updates['quota'] = int(mailQuota)

            # Get employee id.
            employeeNumber = data.get('employeeNumber', '')
            updates['employeeid'] = employeeNumber

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

            # Verify new passwords.
            qr = iredutils.verify_new_password(newpw, confirmpw)
            if qr[0] is True:
                pwscheme = None
                if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                    pwscheme = 'PLAIN'
                passwd = iredutils.generate_password_hash(qr[1],
                                                          pwscheme=pwscheme)
            else:
                return qr

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

            # Update password last change date in column: passwordlastchange.
            #
            # Old iRedMail version doesn't have column mailbox.passwordlastchange,
            # so we update it with a seperate SQL command with exception handle.
            try:
                self.conn.update(
                    'mailbox',
                    vars={
                        'username': self.mail,
                    },
                    where='username=$username',
                    passwordlastchange=iredutils.get_gmttime(),
                )
            except:
                pass
        else:
            return (True, )

        # Update SQL db
        try:
            self.conn.update('mailbox',
                             vars={
                                 'username': self.mail,
                                 'domain': self.domain,
                             },
                             where='username=$username AND domain=$domain',
                             **updates)

            # Update session immediately after updating SQL.
            if profile_type == 'general':
                if 'domainGlobalAdmin' not in data and \
                   session.get('username') == self.mail:
                    session['domainGlobalAdmin'] = False

            return (True, )
        except Exception as e:
            return (False, str(e))
Example #6
0
    def add(self, domain, data):
        # Get domain name, username, cn.
        self.domain = web.safestr(data.get('domainName')).strip().lower()
        mail_local_part = web.safestr(data.get('username')).strip().lower()
        self.mail = mail_local_part + '@' + self.domain

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

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

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

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

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

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

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

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

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

        if mailQuota.isdigit():
            mailQuota = int(mailQuota)
        else:
            mailQuota = 0

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

            spareQuota = domainProfile.maxquota - allocatedQuota

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

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

        resultOfPW = iredutils.verify_new_password(
            newpw,
            confirmpw,
            min_passwd_length=settings.min_passwd_length,
            max_passwd_length=settings.max_passwd_length,
        )
        if resultOfPW[0] is True:
            pwscheme = None
            if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                pwscheme = 'PLAIN'
            passwd = iredutils.generate_password_hash(resultOfPW[1],
                                                      pwscheme=pwscheme)
        else:
            return resultOfPW

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

        # Get storage base directory.
        tmpStorageBaseDirectory = settings.storage_base_directory.lower()
        splitedSBD = tmpStorageBaseDirectory.rstrip('/').split('/')
        storageNode = splitedSBD.pop()
        storageBaseDirectory = '/'.join(splitedSBD)

        try:
            # Store new user in SQL db.
            self.conn.insert(
                'mailbox',
                domain=self.domain,
                username=self.mail,
                password=passwd,
                name=cn,
                maildir=iredutils.generate_maildir_path(self.mail),
                quota=mailQuota,
                storagebasedirectory=storageBaseDirectory,
                storagenode=storageNode,
                mailboxformat=settings.MAILBOX_FORMAT,
                created=iredutils.get_gmttime(),
                active='1',
            )

            self.conn.insert('forwardings',
                             address=self.mail,
                             forwarding=self.mail,
                             domain=self.domain,
                             is_forwarding=1)

            web.logger(
                msg="Create user: %s." % (self.mail),
                domain=self.domain,
                event='create',
            )
            return (True, )
        except Exception as e:
            return (False, str(e))
Example #7
0
                        vars=sql_vars,
                        where='username=$username',
                        active=self.accountStatus,
                    )
                except Exception, e:
                    return (False, str(e))

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

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

            if session.get('domainGlobalAdmin') is not True:
                # Verify old password.
                auth = core.Auth()
                qr = auth.auth(username=self.mail, password=self.cur_passwd, verifyPassword=True,)
                if qr[0] is False:
                    return qr

            # Hash/Encrypt new password.
            try:
                self.conn.update(
                    'admin',
                    vars=sql_vars,
Example #8
0
                        vars=sql_vars,
                        where='username=$username',
                        active=self.accountStatus,
                    )
                except Exception, e:
                    return (False, str(e))

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

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

            if session.get('domainGlobalAdmin') is not True:
                # Verify old password.
                auth = core.Auth()
                qr = auth.auth(username=self.mail, password=self.cur_passwd, verifyPassword=True,)
                if qr[0] is False:
                    return qr

            # Hash/Encrypt new password.
            try:
                self.conn.update(
                    'admin',
                    vars=sql_vars,
Example #9
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.is_domain(self.domain) or not iredutils.is_email(self.mail):
            return (False, "MISSING_DOMAIN_OR_USERNAME")

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

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

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

        if result_domain_profile[0] is not True:
            return (False, result_domain_profile[1])

        domainProfile = result_domain_profile[1]
        domainAccountSetting = ldaputils.getAccountSettingFromLdapQueryResult(domainProfile, key="domainName").get(
            self.domain, {}
        )
        self.aliasDomains = domainProfile[0][1].get("domainAliasName", [])

        # Check account number limit.
        numberOfAccounts = domainAccountSetting.get("numberOfUsers")
        if numberOfAccounts == "-1":
            return (False, "NOT_ALLOWED")

        # 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,
            min_passwd_length=domainAccountSetting.get("minPasswordLength", "0"),
            max_passwd_length=domainAccountSetting.get("maxPasswordLength", "0"),
        )
        if result[0] is True:
            if "storePasswordInPlainText" in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                self.passwd = iredutils.generate_password_hash(result[1], pwscheme="PLAIN")
            else:
                self.passwd = iredutils.generate_password_hash(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

            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.is_email(v)
        ]

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

        # Get default mail lists 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,
        )

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

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

        elif attrs.RDN_USER == "cn":
            self.dn = "cn=" + self.cn + "," + attrs.DN_BETWEEN_USER_AND_DOMAIN + domain_dn
        elif attrs.RDN_USER == "uid":
            self.dn = "uid=" + self.username + "," + attrs.DN_BETWEEN_USER_AND_DOMAIN + domain_dn
        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))
Example #10
0
    def add(self, domain, data):
        # Get domain name, username, cn.
        self.domain = web.safestr(data.get('domainName')).strip().lower()
        mail_local_part = web.safestr(data.get('username')).strip().lower()
        self.mail = mail_local_part + '@' + self.domain

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

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

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

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

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

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

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

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

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

        if mailQuota.isdigit():
            mailQuota = int(mailQuota)
        else:
            mailQuota = 0

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

            spareQuota = domainProfile.maxquota - allocatedQuota

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

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

        resultOfPW = iredutils.verify_new_password(
            newpw,
            confirmpw,
            min_passwd_length=settings.min_passwd_length,
            max_passwd_length=settings.max_passwd_length,
        )
        if resultOfPW[0] is True:
            pwscheme = None
            if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                pwscheme = 'PLAIN'
            passwd = iredutils.generate_password_hash(resultOfPW[1], pwscheme=pwscheme)
        else:
            return resultOfPW

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

        # Get storage base directory.
        tmpStorageBaseDirectory = settings.storage_base_directory.lower()
        splitedSBD = tmpStorageBaseDirectory.rstrip('/').split('/')
        storageNode = splitedSBD.pop()
        storageBaseDirectory = '/'.join(splitedSBD)

        try:
            # Store new user in SQL db.
            self.conn.insert(
                'mailbox',
                domain=self.domain,
                username=self.mail,
                password=passwd,
                name=cn,
                maildir=iredutils.generate_maildir_path(self.mail),
                quota=mailQuota,
                storagebasedirectory=storageBaseDirectory,
                storagenode=storageNode,
                created=iredutils.get_gmttime(),
                active='1',
                local_part=mail_local_part,
            )

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

            web.logger(msg="Create user: %s." % (self.mail), domain=self.domain, event='create',)
            return (True,)
        except Exception, e:
            return (False, str(e))
Example #11
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.is_domain(self.domain) or not iredutils.is_email(
                self.mail):
            return (False, 'MISSING_DOMAIN_OR_USERNAME')

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

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

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

        if result_domain_profile[0] is not True:
            return (False, result_domain_profile[1])

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

        # Check account number limit.
        numberOfAccounts = domainAccountSetting.get('numberOfUsers')
        if numberOfAccounts == '-1':
            return (False, 'NOT_ALLOWED')

        # 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,
            min_passwd_length=domainAccountSetting.get('minPasswordLength',
                                                       '0'),
            max_passwd_length=domainAccountSetting.get('maxPasswordLength',
                                                       '0'),
        )
        if result[0] is True:
            if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                self.passwd = iredutils.generate_password_hash(
                    result[1], pwscheme='PLAIN')
            else:
                self.passwd = iredutils.generate_password_hash(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

            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.is_email(v)
        ]

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

        # Get default mail lists 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,
        )

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

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

        elif attrs.RDN_USER == 'cn':
            self.dn = 'cn=' + self.cn + ',' + attrs.DN_BETWEEN_USER_AND_DOMAIN + domain_dn
        elif attrs.RDN_USER == 'uid':
            self.dn = 'uid=' + self.username + ',' + attrs.DN_BETWEEN_USER_AND_DOMAIN + domain_dn
        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))
Example #12
0
            maxPasswordLength = domainAccountSetting.get(
                'maxPasswordLength', settings.max_passwd_length)

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

            result = iredutils.verify_new_password(
                newpw=self.newpw,
                confirmpw=self.confirmpw,
                min_passwd_length=minPasswordLength,
                max_passwd_length=maxPasswordLength,
            )
            if result[0] is True:
                if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                    self.passwd = iredutils.generate_password_hash(
                        result[1], pwscheme='PLAIN')
                else:
                    self.passwd = iredutils.generate_password_hash(result[1])
                mod_attrs += [(ldap.MOD_REPLACE, 'userPassword', self.passwd)]
                mod_attrs += [(ldap.MOD_REPLACE, 'shadowLastChange',
                               str(ldaputils.getDaysOfShadowLastChange()))]
            else:
                return result

        try:
            self.conn.modify_s(self.dn, mod_attrs)
            return (True, )
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Example #13
0
    def update(self, profile_type, mail, data):
        self.profile_type = web.safestr(profile_type)
        self.mail = str(mail).lower()
        self.username, self.domain = self.mail.split('@', 1)

        domainAccountSetting = {}

        connutils = connUtils.Utils()
        domainLib = domainlib.Domain()

        # Get account dn.
        self.dn = connutils.getDnWithKeyword(self.mail, accountType='user')

        try:
            result = domainLib.getDomainAccountSetting(domain=self.domain)
            if result[0] is True:
                domainAccountSetting = result[1]
        except Exception as e:
            pass

        mod_attrs = []
        if self.profile_type == 'general':
            # Update domainGlobalAdmin=yes
            if session.get('domainGlobalAdmin') is True:
                # Update domainGlobalAdmin=yes
                if 'domainGlobalAdmin' in data:
                    mod_attrs = [(ldap.MOD_REPLACE, 'domainGlobalAdmin', 'yes')
                                 ]
                    # Update enabledService=domainadmin
                    connutils.addOrDelAttrValue(
                        dn=self.dn,
                        attr='enabledService',
                        value='domainadmin',
                        action='add',
                    )
                else:
                    mod_attrs = [(ldap.MOD_REPLACE, 'domainGlobalAdmin', None)]
                    # Remove enabledService=domainadmin
                    connutils.addOrDelAttrValue(
                        dn=self.dn,
                        attr='enabledService',
                        value='domainadmin',
                        action='delete',
                    )

            # Get display name.
            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 preferred language: short lang code. e.g. en_US, de_DE.
            preferred_lang = web.safestr(data.get('preferredLanguage',
                                                  'en_US'))
            # Must be equal to or less than 5 characters.
            if len(preferred_lang) > 5:
                preferred_lang = preferred_lang[:5]
            mod_attrs += [(ldap.MOD_REPLACE, 'preferredLanguage',
                           preferred_lang)]
            # Update language immediately.
            if session.get('username') == self.mail and \
               session.get('lang', 'en_US') != preferred_lang:
                session['lang'] = preferred_lang

            # Update employeeNumber, mobile, title.
            for tmp_attr in [
                    'employeeNumber',
                    'mobile',
                    'title',
            ]:
                mod_attrs += ldaputils.getSingleModAttr(
                    attr=tmp_attr, value=data.get(tmp_attr), default=None)

            ############
            # Get quota

            # Get mail quota from web form.
            quota = web.safestr(data.get('mailQuota', '')).strip()
            oldquota = web.safestr(data.get('oldMailQuota', '')).strip()
            if not oldquota.isdigit():
                oldquota = 0
            else:
                oldquota = int(oldquota)

            if quota == '' or not quota.isdigit():
                # Don't touch it, keep original value.
                pass
            else:
                # Assign quota which got from web form.
                mailQuota = int(quota)

                # If mailQuota > domainSpareQuotaSize, use domainSpareQuotaSize.
                # if mailQuota < domainSpareQuotaSize, use mailQuota
                # 0 means unlimited.
                domainQuotaSize, domainQuotaUnit = domainAccountSetting.get(
                    'domainQuota', '0:GB').split(':')

                if int(domainQuotaSize) == 0:
                    # Unlimited. Keep quota which got from web form.
                    mod_attrs += [(ldap.MOD_REPLACE, 'mailQuota',
                                   str(mailQuota * 1024 * 1024))]
                else:
                    # Get domain quota.
                    if domainQuotaUnit == 'TB':
                        domainQuota = int(domainQuotaSize) * 1024 * 1024  # TB
                    elif domainQuotaUnit == 'GB':
                        domainQuota = int(domainQuotaSize) * 1024  # GB
                    else:
                        domainQuota = int(domainQuotaSize)  # MB

                    # Query LDAP and get current domain quota size.
                    result = connutils.getDomainCurrentQuotaSizeFromLDAP(
                        domain=self.domain)
                    if result[0] is True:
                        domainCurrentQuotaSizeInBytes = result[1]
                    else:
                        domainCurrentQuotaSizeInBytes = 0

                    # Spare quota.
                    domainSpareQuotaSize = (domainQuota + oldquota) - (
                        domainCurrentQuotaSizeInBytes / (1024 * 1024))

                    if domainSpareQuotaSize <= 0:
                        # Set to 1MB. don't exceed domain quota size.
                        mod_attrs += [(ldap.MOD_REPLACE, 'mailQuota',
                                       str(1024 * 1024))]
                    else:
                        # Get FINAL mailbox quota.
                        if mailQuota >= domainSpareQuotaSize:
                            mailQuota = domainSpareQuotaSize
                        mod_attrs += [(ldap.MOD_REPLACE, 'mailQuota',
                                       str(mailQuota * 1024 * 1024))]
            # End quota
            ############

            # Get telephoneNumber.
            telephoneNumber = data.get('telephoneNumber', [])
            nums = [str(num) for num in telephoneNumber if len(num) > 0]
            mod_attrs += [(ldap.MOD_REPLACE, 'telephoneNumber', nums)]

            # Get accountStatus.
            if 'accountStatus' in list(data.keys()):
                accountStatus = 'active'
            else:
                accountStatus = 'disabled'
            mod_attrs += [(ldap.MOD_REPLACE, 'accountStatus', accountStatus)]

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

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

            result = iredutils.verify_new_password(
                newpw=self.newpw,
                confirmpw=self.confirmpw,
                min_passwd_length=minPasswordLength,
                max_passwd_length=maxPasswordLength,
            )
            if result[0] is True:
                if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                    self.passwd = iredutils.generate_password_hash(
                        result[1], pwscheme='PLAIN')
                else:
                    self.passwd = iredutils.generate_password_hash(result[1])
                mod_attrs += [(ldap.MOD_REPLACE, 'userPassword', self.passwd)]
                mod_attrs += [(ldap.MOD_REPLACE, 'shadowLastChange',
                               str(ldaputils.getDaysOfShadowLastChange()))]
            else:
                return result

        try:
            self.conn.modify_s(self.dn, mod_attrs)
            return (True, )
        except Exception as e:
            return (False, ldaputils.getExceptionDesc(e))
Example #14
0
    def update(self, profile_type, mail, data):
        self.profile_type = web.safestr(profile_type)
        self.mail = str(mail).lower()
        self.domain = self.mail.split("@", 1)[-1]

        # Pre-defined update key:value.
        updates = {"modified": iredutils.get_gmttime()}

        if self.profile_type == "general":
            # Get settings of domain admin and global admin
            managed_domain = ""
            if "domainadmin" in data:
                # isadmin=1
                updates["isadmin"] = 1
                managed_domain = self.domain
            else:
                updates["isadmin"] = 0

            if session.get("domainGlobalAdmin"):
                if "domainGlobalAdmin" in data:
                    updates["isadmin"] = 1
                    updates["isglobaladmin"] = 1
                    managed_domain = "ALL"
                else:
                    updates["isglobaladmin"] = 0

            # Delete records in domain_admins first
            self.conn.delete("domain_admins", vars={"username": self.mail}, where="username=$username")

            if updates.get("isadmin") == 1:
                try:
                    self.conn.insert(
                        "domain_admins",
                        username=self.mail,
                        domain=managed_domain,
                        created=iredutils.get_gmttime(),
                        active=1,
                    )
                except:
                    pass

            # Get name
            cn = data.get("cn", "")
            updates["name"] = cn

            # Get preferred language: short lang code. e.g. en_US, de_DE.
            preferred_lang = web.safestr(data.get("preferredLanguage", "en_US"))
            # Must be equal to or less than 5 characters.
            if len(preferred_lang) > 5:
                preferred_lang = preferred_lang[:5]
            updates["language"] = preferred_lang
            # Update language immediately.
            if session.get("username") == self.mail and session.get("lang", "en_US") != preferred_lang:
                session["lang"] = preferred_lang

            # Get account status
            if "accountStatus" in data.keys():
                updates["active"] = 1
            else:
                updates["active"] = 0

            # Get mail quota size.
            mailQuota = str(data.get("mailQuota"))
            if mailQuota.isdigit():
                updates["quota"] = int(mailQuota)

            # Get employee id.
            employeeNumber = data.get("employeeNumber", "")
            updates["employeeid"] = employeeNumber

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

            # Verify new passwords.
            qr = iredutils.verify_new_password(newpw, confirmpw)
            if qr[0] is True:
                pwscheme = None
                if "storePasswordInPlainText" in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                    pwscheme = "PLAIN"
                passwd = iredutils.generate_password_hash(qr[1], pwscheme=pwscheme)
            else:
                return qr

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

            # Update password last change date in column: passwordlastchange.
            #
            # Old iRedMail version doesn't have column mailbox.passwordlastchange,
            # so we update it with a seperate SQL command with exception handle.
            try:
                self.conn.update(
                    "mailbox",
                    vars={"username": self.mail},
                    where="username=$username",
                    passwordlastchange=iredutils.get_gmttime(),
                )
            except:
                pass
        else:
            return (True,)

        # Update SQL db
        try:
            self.conn.update(
                "mailbox",
                vars={"username": self.mail, "domain": self.domain},
                where="username=$username AND domain=$domain",
                **updates
            )

            # Update session immediately after updating SQL.
            if profile_type == "general":
                if not "domainGlobalAdmin" in data and session.get("username") == self.mail:
                    session["domainGlobalAdmin"] = False

            return (True,)
        except Exception, e:
            return (False, str(e))
Example #15
0
    def update(self, profile_type, mail, data):
        self.profile_type = web.safestr(profile_type)
        self.mail = web.safestr(mail)

        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')

        sql_vars = {
            'username': self.mail,
        }

        if self.profile_type == 'general':
            # Get name
            self.cn = data.get('cn', '')

            # Get preferred language.
            self.preferredLanguage = str(data.get('preferredLanguage',
                                                  'en_US'))

            # Update in SQL db.
            try:
                self.conn.update(
                    'admin',
                    vars=sql_vars,
                    where='username=$username',
                    name=self.cn,
                    language=self.preferredLanguage,
                )

                # Update language immediately.
                if session.get('username') == self.mail and \
                   session.get('lang', 'en_US') != self.preferredLanguage:
                    session['lang'] = self.preferredLanguage
            except Exception as e:
                return (False, str(e))

            if session.get('domainGlobalAdmin') is True:
                # Update account status
                self.accountStatus = '0'  # Disabled
                if 'accountStatus' in list(data.keys()):
                    self.accountStatus = '1'  # Active

                try:
                    self.conn.update(
                        'admin',
                        vars=sql_vars,
                        where='username=$username',
                        active=self.accountStatus,
                    )
                except Exception as e:
                    return (False, str(e))

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

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

            if session.get('domainGlobalAdmin') is not True:
                # Verify old password.
                auth = core.Auth()
                qr = auth.auth(
                    username=self.mail,
                    password=self.cur_passwd,
                    verifyPassword=True,
                )
                if qr[0] is False:
                    return qr

            # Hash/Encrypt new password.
            try:
                self.conn.update(
                    'admin',
                    vars=sql_vars,
                    where='username=$username',
                    password=self.passwd,
                    passwordlastchange=iredutils.get_gmttime(),
                )
            except Exception as e:
                raise web.seeother('/profile/admin/password/%s?msg=%s' %
                                   (self.mail, web.urlquote(e)))

        return (True, )
Example #16
0
    def update(self, profile_type, mail, data):
        self.profile_type = web.safestr(profile_type)
        self.mail = str(mail).lower()
        self.domain = self.mail.split('@', 1)[-1]

        # Pre-defined update key:value.
        updates = {'modified': iredutils.get_gmttime()}

        if self.profile_type == 'general':
            # Get settings of domain admin and global admin
            managed_domain=''
            if 'domainadmin' in data:
                # isadmin=1
                updates['isadmin'] = 1
                managed_domain=self.domain
            else:
                updates['isadmin'] = 0

            if session.get('domainGlobalAdmin'):
                if 'domainGlobalAdmin' in data:
                    updates['isadmin'] = 1
                    updates['isglobaladmin'] = 1
                    managed_domain='ALL'
                else:
                    updates['isglobaladmin'] = 0

            # Delete records in domain_admins first
            self.conn.delete('domain_admins',
                             vars={'username': self.mail},
                             where='username=$username',
                            )

            if updates.get('isadmin') == 1:
                try:
                    self.conn.insert('domain_admins',
                                     username=self.mail,
                                     domain=managed_domain,
                                     created=iredutils.get_gmttime(),
                                     active=1,
                                    )
                except:
                    pass

            # Get name
            cn = data.get('cn', '')
            updates['name'] = cn

            # Get preferred language: short lang code. e.g. en_US, de_DE.
            preferred_lang = web.safestr(data.get('preferredLanguage', 'en_US'))
            # Must be equal to or less than 5 characters.
            if len(preferred_lang) > 5:
                preferred_lang = preferred_lang[:5]
            updates['language'] = preferred_lang
            # Update language immediately.
            if session.get('username') == self.mail and \
               session.get('lang', 'en_US') != preferred_lang:
                session['lang'] = preferred_lang

            # Get account status
            if 'accountStatus' in data.keys():
                updates['active'] = 1
            else:
                updates['active'] = 0

            # Get mail quota size.
            mailQuota = str(data.get('mailQuota'))
            if mailQuota.isdigit():
                updates['quota'] = int(mailQuota)

            # Get employee id.
            employeeNumber = data.get('employeeNumber', '')
            updates['employeeid'] = employeeNumber

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

            # Verify new passwords.
            qr = iredutils.verify_new_password(newpw, confirmpw)
            if qr[0] is True:
                pwscheme = None
                if 'storePasswordInPlainText' in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                    pwscheme = 'PLAIN'
                passwd = iredutils.generate_password_hash(qr[1], pwscheme=pwscheme)
            else:
                return qr

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

            # Update password last change date in column: passwordlastchange.
            #
            # Old iRedMail version doesn't have column mailbox.passwordlastchange,
            # so we update it with a seperate SQL command with exception handle.
            try:
                self.conn.update(
                    'mailbox',
                    vars={'username': self.mail, },
                    where='username=$username',
                    passwordlastchange=iredutils.get_gmttime(),
                )
            except:
                pass

        else:
            return (True,)

        # Update SQL db
        try:
            self.conn.update(
                'mailbox',
                vars={'username': self.mail, 'domain': self.domain, },
                where='username=$username AND domain=$domain',
                **updates
            )

            # Update session immediately after updating SQL.
            if profile_type == 'general':
                if not 'domainGlobalAdmin' in data and \
                   session.get('username') == self.mail:
                    session['domainGlobalAdmin'] = False

            return (True,)
        except Exception, e:
            return (False, str(e))
else:
    usage()

total = len(users)
logger.info('%d users in total.' % total)

count = 1
if backend == 'ldap':
    import ldap
    from libs.ldaplib.ldaputils import convert_keyword_to_dn
    conn = get_db_conn('ldap')

    for (_email, _pw) in users:
        logger.info('(%d/%d) Updating %s' % (count, total, _email))

        dn = convert_keyword_to_dn(_email, accountType='user')
        pw_hash = generate_password_hash(_pw)
        mod_attrs = [(ldap.MOD_REPLACE, 'userPassword', [pw_hash])]
        try:
            conn.modify_s(dn, mod_attrs)
        except Exception, e:
            print '<<< ERROR >>>', e
elif backend in ['mysql', 'pgsql']:
    conn = get_db_conn('vmail')
    for (_email, _pw) in users:
        logger.info('(%d/%d) Updating %s' % (count, total, _email))
        pw_hash = generate_password_hash(_pw)
        conn.update('mailbox',
                    password=pw_hash,
                    where="username='******'" % _email)
Example #18
0
        elif self.profile_type == "password":
            # Get password length from @domainAccountSetting.
            minPasswordLength = domainAccountSetting.get("minPasswordLength", settings.min_passwd_length)
            maxPasswordLength = domainAccountSetting.get("maxPasswordLength", settings.max_passwd_length)

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

            result = iredutils.verify_new_password(
                newpw=self.newpw,
                confirmpw=self.confirmpw,
                min_passwd_length=minPasswordLength,
                max_passwd_length=maxPasswordLength,
            )
            if result[0] is True:
                if "storePasswordInPlainText" in data and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                    self.passwd = iredutils.generate_password_hash(result[1], pwscheme="PLAIN")
                else:
                    self.passwd = iredutils.generate_password_hash(result[1])
                mod_attrs += [(ldap.MOD_REPLACE, "userPassword", self.passwd)]
                mod_attrs += [(ldap.MOD_REPLACE, "shadowLastChange", str(ldaputils.getDaysOfShadowLastChange()))]
            else:
                return result

        try:
            self.conn.modify_s(self.dn, mod_attrs)
            return (True,)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))