Exemplo n.º 1
0
    def add(self, data):
        domain = web.safestr(data.get('domainName', '')).strip().lower()

        # Get company/organization name.
        cn = data.get('cn', '')

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

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

        # Add domain in database.
        try:
            self.conn.insert(
                'domain',
                domain=domain,
                description=cn,
                transport=settings.default_mta_transport,
                created=iredutils.get_gmttime(),
                active='1',
            )
            web.logger(
                msg="Create domain: %s." % (domain),
                domain=domain,
                event='create',
            )
        except Exception, e:
            return (False, str(e))
Exemplo n.º 2
0
    def add(self, data):
        self.domain = web.safestr(data.get('domainName', '')).strip().lower()

        # Get company/organization name.
        self.cn = data.get('cn', '')

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

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

        # Add domain in database.
        try:
            self.conn.insert(
                'domain',
                domain=self.domain,
                description=self.cn,
                transport=cfg.general.get('transport', 'dovecot'),
                created=iredutils.sqlNOW,
                active='1',
            )
            web.logger(msg="Create domain: %s." % (self.domain), domain=self.domain, event='create',)
        except Exception, e:
            return (False, str(e))
Exemplo n.º 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')

        # 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))
Exemplo n.º 4
0
    def GET(
        self,
        domain=None,
    ):
        if domain is None:
            self.cur_domain = None
        else:
            self.cur_domain = str(domain)
            if not iredutils.is_domain(self.cur_domain):
                raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME')

        i = web.input()

        # Get all managed domains.
        connutils = connUtils.Utils()
        qr = connutils.getManagedDomains(
            admin=session.get('username'),
            domainNameOnly=True,
        )

        if qr[0] is True:
            allDomains = qr[1]
        else:
            raise web.seeother('/domains?msg=%s' % web.urlquote(qr[1]))

        # Set first domain as current domain.
        if self.cur_domain is None:
            if len(allDomains) > 0:
                raise web.seeother('/create/user/%s' % str(allDomains[0]))
            else:
                raise web.seeother('/domains?msg=NO_DOMAIN_AVAILABLE')

        # Get domain profile.
        domainLib = domainlib.Domain()
        resultOfProfile = domainLib.profile(domain=self.cur_domain)
        if resultOfProfile[0] is True:
            self.profile = resultOfProfile[1]
        else:
            raise web.seeother('/domains?msg=%s' %
                               web.urlquote(resultOfProfile[1]))

        return web.render(
            'mysql/user/create.html',
            cur_domain=self.cur_domain,
            allDomains=allDomains,
            profile=self.profile,
            min_passwd_length=settings.min_passwd_length,
            max_passwd_length=settings.max_passwd_length,
            msg=i.get('msg'),
        )
Exemplo n.º 5
0
    def listAccounts(self, domain, cur_page=1):
        '''List all users.'''
        if not iredutils.is_domain(domain):
            return (False, 'INVALID_DOMAIN_NAME')

        domain = str(domain)
        connutils = connUtils.Utils()
        if not connutils.is_domain_exists(domain):
            return (False, 'PERMISSION_DENIED')

        # Pre-defined.
        sql_vars = {
            'domain': domain,
        }
        total = 0

        try:
            resultOfTotal = self.conn.select(
                'mailbox',
                vars=sql_vars,
                what='COUNT(username) AS total',
                where='domain=$domain',
            )
            if len(resultOfTotal) == 1:
                total = resultOfTotal[0].total or 0

            resultOfRecords = self.conn.select(
                'mailbox',
                vars=sql_vars,
                # Just query what we need to reduce memory use.
                what='username,name,quota,employeeid,active',
                where='domain=$domain',
                order='username ASC',
                limit=settings.PAGE_SIZE_LIMIT,
                offset=(cur_page - 1) * settings.PAGE_SIZE_LIMIT,
            )

            return (True, total, list(resultOfRecords))
        except Exception as e:
            return (False, str(e))
Exemplo n.º 6
0
    def getNumberOfManagedAccounts(
        self,
        admin=None,
        accountType='domain',
        domains=[],
    ):
        if admin is None:
            self.admin = session.get('username')
        else:
            self.admin = str(admin)

        if not iredutils.is_email(self.admin):
            return 0

        self.domains = []
        if accountType == 'user':
            if len(domains) > 0:
                self.domains = [
                    str(d).lower() for d in domains if iredutils.is_domain(d)
                ]
            else:
                connutils = connUtils.Utils()
                qr = connutils.getManagedDomains(admin=self.admin,
                                                 domainNameOnly=True)
                if qr[0] is True:
                    self.domains = qr[1]

        sql_vars = {
            'admin': self.admin,
            'domains': self.domains,
        }
        if accountType == 'domain':
            try:
                if self.is_global_admin(self.admin):
                    result = self.conn.select(
                        'domain',
                        what='COUNT(domain) AS total',
                    )
                else:
                    result = self.conn.query(
                        """
                        SELECT COUNT(domain.domain) AS total
                        FROM domain
                        LEFT JOIN domain_admins ON (domain.domain=domain_admins.domain)
                        WHERE domain_admins.username=$admin
                        """,
                        vars=sql_vars,
                    )

                total = result[0].total or 0
                return total
            except Exception:
                pass
        elif accountType == 'user':
            try:
                if self.is_global_admin(self.admin):
                    if len(self.domains) >= 0:
                        result = self.conn.select(
                            'mailbox',
                            vars=sql_vars,
                            what='COUNT(username) AS total',
                            where='domain IN $domains',
                        )
                    else:
                        result = self.conn.select(
                            'mailbox', what='COUNT(username) AS total')
                else:
                    self.sql_append_where = ''
                    if len(self.domains) > 0:
                        self.sql_append_where = 'AND mailbox.domain IN %s' % web.sqlquote(
                            self.domains)

                    result = self.conn.query(
                        """
                        SELECT COUNT(mailbox.username) AS total
                        FROM mailbox
                        LEFT JOIN domain_admins ON (mailbox.domain = domain_admins.domain)
                        WHERE domain_admins.username=$admin %s
                        """ % (self.sql_append_where, ),
                        vars=sql_vars,
                    )

                total = result[0].total or 0
                return total
            except:
                pass

        return 0
Exemplo n.º 7
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))
Exemplo n.º 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

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