Example #1
0
        def proxyfunc(self, *args, **kw):
            if 'mail' in kw.keys() and iredutils.is_email(kw.get('mail')):
                self.domain = web.safestr(kw['mail']).split('@')[-1]
            elif 'domain' in kw.keys() and iredutils.is_domain(kw.get('domain')):
                self.domain = web.safestr(kw['domain'])
            else:
                return False

            self.admin = session.get('username')
            if not iredutils.is_email(self.admin):
                return False

            # Check domain global admin.
            if session.get('domainGlobalAdmin') is True:
                return func(self, *args, **kw)
            else:
                # Check whether is domain admin.
                try:
                    result = self.conn.select(
                        'domain_admins',
                        vars={'username': self.admin, 'domain': [self.domain, 'ALL']},
                        what='username',
                        where='username=$username AND domain IN $domain',
                    )
                except Exception:
                    result = {}

                if len(result) != 1:
                    return func(self, *args, **kw)
                else:
                    raise web.seeother('/users' + '?msg=PERMISSION_DENIED&domain=' + self.domain)
Example #2
0
        def proxyfunc(self, *args, **kw):
            if 'mail' in list(kw.keys()) and iredutils.is_email(kw.get('mail')):
                self.domain = web.safestr(kw['mail']).split('@')[-1]
            elif 'domain' in list(kw.keys()) and iredutils.is_domain(kw.get('domain')):
                self.domain = web.safestr(kw['domain'])
            else:
                return False

            self.admin = session.get('username')
            if not iredutils.is_email(self.admin):
                return False

            # Check domain global admin.
            if session.get('domainGlobalAdmin') is True:
                return func(self, *args, **kw)
            else:
                # Check whether is domain admin.
                try:
                    result = self.conn.select(
                        'domain_admins',
                        vars={'username': self.admin, 'domain': [self.domain, 'ALL']},
                        what='username',
                        where='username=$username AND domain IN $domain',
                    )
                except Exception:
                    result = {}

                if len(result) != 1:
                    return func(self, *args, **kw)
                else:
                    raise web.seeother('/users' + '?msg=PERMISSION_DENIED&domain=' + self.domain)
Example #3
0
    def proxyfunc(*args, **kw):
        # Check domain global admin.
        if session.get('domainGlobalAdmin') is True:
            return func(*args, **kw)
        else:
            if 'domain' in list(kw.keys()) and iredutils.is_domain(
                    kw.get('domain')):
                domain = web.safestr(kw['domain'])
            elif 'mail' in list(kw.keys()) and iredutils.is_email(
                    kw.get('mail')):
                domain = web.safestr(kw['mail']).split('@')[-1]
            elif 'admin' in list(kw.keys()) and iredutils.is_email(
                    kw.get('admin')):
                domain = web.safestr(kw['admin']).split('@')[-1]
            else:
                return (False, 'PERMISSION_DENIED')

            # Check whether is domain admin.
            validator = core.PGSQLWrap()
            if validator.is_domainAdmin(
                    domain=domain,
                    admin=session.get('username'),
            ):
                return func(*args, **kw)
            else:
                return (False, 'PERMISSION_DENIED')
Example #4
0
    def enableOrDisableAccount(self, domain, mails, action, attr="accountStatus"):
        if mails is None or len(mails) == 0:
            return (False, "NO_ACCOUNT_SELECTED")

        self.mails = [str(v) for v in mails if iredutils.is_email(v) and str(v).endswith("@" + str(domain))]

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

            self.domain = self.mail.split("@")[-1]
            self.dn = ldaputils.convert_keyword_to_dn(self.mail, accountType="user")
            if self.dn[0] is False:
                result[self.mail] = self.dn[1]
                continue

            try:
                connutils.enableOrDisableAccount(
                    domain=self.domain,
                    account=self.mail,
                    dn=self.dn,
                    action=web.safestr(action).strip().lower(),
                    accountTypeInLogger="user",
                )
            except ldap.LDAPError, e:
                result[self.mail] = str(e)
Example #5
0
    def setAccountStatus(self, accounts, accountType, active=True):
        # accounts must be a list/tuple.
        # accountType in ['domain', 'user', 'admin']
        # active: True -> active, False -> disabled
        if not len(accounts) > 0:
            return (True,)

        accountType = str(accountType)
        if active is True:
            active = 1
            action = 'Active'
        else:
            active = 0
            action = 'Disable'

        if accountType == 'domain':
            accounts = [str(v) for v in accounts if iredutils.is_domain(v)]
            try:
                self.conn.update(
                    'domain',
                    vars={'accounts': accounts},
                    where='domain IN $accounts',
                    active=active,
                )
            except Exception as e:
                return (False, str(e))
        elif accountType == 'user':
            accounts = [str(v) for v in accounts if iredutils.is_email(v)]
            try:
                self.conn.update(
                    'mailbox',
                    vars={'accounts': accounts},
                    where='username IN $accounts',
                    active=active,
                )
            except Exception as e:
                return (False, str(e))
        elif accountType == 'admin':
            accounts = [str(v) for v in accounts if iredutils.is_email(v)]
            try:
                self.conn.update(
                    'admin',
                    vars={'accounts': accounts},
                    where='username IN $accounts',
                    active=active,
                )
            except Exception as e:
                return (False, str(e))
        else:
            pass

        try:
            web.logger(
                msg="%s %s: %s." % (action, accountType, ', '.join(accounts)),
                event=action.lower(),
            )
        except:
            pass
        return (True,)
Example #6
0
    def deleteSingleUser(self, mail, deleteFromGroups=True):
        self.mail = web.safestr(mail)
        if not iredutils.is_email(self.mail):
            return (False, "INVALID_MAIL")

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

        # Get dn of mail user and domain.
        self.dnUser = ldaputils.convert_keyword_to_dn(self.mail, accountType="user")
        if self.dnUser[0] is False:
            return self.dnUser

        # Delete user object.
        try:
            # Delete single object.
            # self.conn.delete_s(self.dnUser)

            # Delete object and its subtree.
            deltree.DelTree(self.conn, self.dnUser, ldap.SCOPE_SUBTREE)

            if deleteFromGroups:
                self.deleteSingleUserFromGroups(self.mail)

            # Delete record from SQL database: real-time used quota.
            try:
                connUtils.deleteAccountFromUsedQuota([self.mail])
            except Exception, e:
                pass

            # Log delete action.
            web.logger(msg="Delete user: %s." % (self.mail), domain=self.domain, event="delete")
            return (True,)
Example #7
0
    def is_domainAdmin(
            self,
            domain,
            admin=session.get('username'),
    ):
        if not iredutils.is_domain(domain) or not iredutils.is_email(admin):
            return False

        if admin == session.get('username') \
           and session.get('domainGlobalAdmin') is True:
            return True

        try:
            result = self.conn.select(
                'domain_admins',
                vars={
                    'domain': domain,
                    'username': admin,
                },
                what='username',
                where='domain=$domain AND username=$username AND active=1',
                limit=1,
            )
            if len(result) == 1:
                return True
            else:
                return False
        except Exception:
            return False
Example #8
0
def assign_admins_to_domain(domain, admins, conn=None):
    """Assign list of NEW admins to specified mail domain.

    It doesn't remove existing admins."""
    if not iredutils.is_domain(domain):
        return (False, 'INVALID_DOMAIN_NAME')

    if not isinstance(admins, (list, tuple, set)):
        return (False, 'NO_ADMINS')
    else:
        admins = [str(i).lower() for i in admins if iredutils.is_email(i)]
        if not admins:
            return (False, 'NO_ADMINS')

    if not conn:
        _wrap = SQLWrap()
        conn = _wrap.conn

    for adm in admins:
        try:
            conn.insert('domain_admins', domain=domain, username=adm)
        except Exception as e:
            if e.__class__.__name__ == 'IntegrityError':
                pass
            else:
                return (False, repr(e))

    return (True, )
Example #9
0
    def delete(self, domain, mails=None, keep_mailbox_days=0):
        if not mails:
            return (False, 'NO_ACCOUNT_SELECTED')

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

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

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

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

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

        if result == {}:
            return (True, )
        else:
            return (False, str(result))
Example #10
0
    def getManagedDomains(self, admin, domainNameOnly=False, listedOnly=False,):
        admin = web.safestr(admin)

        if not iredutils.is_email(admin):
            return (False, 'INCORRECT_USERNAME')

        sql_left_join = ''
        if listedOnly is False:
            sql_left_join = """OR domain_admins.domain='ALL'"""

        try:
            result = self.conn.query(
                """
                SELECT domain.domain
                FROM domain
                LEFT JOIN domain_admins ON (domain.domain=domain_admins.domain %s)
                WHERE domain_admins.username=$admin
                ORDER BY domain_admins.domain
                """ % (sql_left_join),
                vars={'admin': admin, },
            )

            if domainNameOnly is True:
                domains = []
                for i in result:
                    if iredutils.is_domain(i.domain):
                        domains += [str(i.domain).lower()]

                return (True, domains)
            else:
                return (True, list(result))
        except Exception, e:
            return (False, str(e))
Example #11
0
    def is_email_exists(self, mail):
        # Return True if account is invalid or exist.
        mail = web.safestr(mail)

        if not iredutils.is_email(mail):
            return True

        sql_vars = {'email': mail, }

        try:
            resultOfMailbox = self.conn.select(
                'mailbox',
                vars=sql_vars,
                what='username',
                where='username=$email',
                limit=1,
            )

            resultOfAlias = self.conn.select(
                'alias',
                vars=sql_vars,
                what='address',
                where='address=$email',
                limit=1,
            )

            if resultOfMailbox or resultOfAlias:
                return True
            else:
                return False

        except Exception:
            return True
Example #12
0
    def delete(self, domain, mails=None, keep_mailbox_days=0):
        domain = str(domain).lower()

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

        if not mails:
            return (False, 'INVALID_MAIL')

        mails = [
            str(v).lower() for v in mails
            if iredutils.is_email(v) and str(v).endswith('@' + domain)
        ]

        if not mails:
            return (False, 'INVALID_MAIL')

        # Delete user and related records.
        try:
            qr = self.deleteAccounts(accounts=mails,
                                     accountType='user',
                                     keep_mailbox_days=keep_mailbox_days)
            if qr[0] is True:
                web.logger(
                    msg="Delete user: %s." % ', '.join(mails),
                    domain=domain,
                    event='delete',
                )
            else:
                return qr

            return (True, )
        except Exception as e:
            return (False, str(e))
Example #13
0
    def getManagedDomains(self, admin, domainNameOnly=False, listedOnly=False,):
        admin = web.safestr(admin)

        if not iredutils.is_email(admin):
            return (False, 'INCORRECT_USERNAME')

        sql_left_join = ''
        if listedOnly is False:
            sql_left_join = """OR domain_admins.domain='ALL'"""

        try:
            result = self.conn.query(
                """
                SELECT domain.domain
                FROM domain
                LEFT JOIN domain_admins ON (domain.domain=domain_admins.domain %s)
                WHERE domain_admins.username=$admin
                ORDER BY domain_admins.domain
                """ % (sql_left_join),
                vars={'admin': admin, },
            )

            if domainNameOnly is True:
                domains = []
                for i in result:
                    if iredutils.is_domain(i.domain):
                        domains += [str(i.domain).lower()]

                return (True, domains)
            else:
                return (True, list(result))
        except Exception, e:
            return (False, str(e))
Example #14
0
def get_profile(mail, columns=None, conn=None):
    if not iredutils.is_email(mail):
        return (False, 'INVALID_MAIL')

    if isinstance(columns, (list, tuple, set)):
        columns = ','.join(columns)
    else:
        columns = '*'

    if not conn:
        _wrap = SQLWrap()
        conn = _wrap.conn

    try:
        qr = conn.select('admin',
                         vars={'username': mail},
                         what=columns,
                         where='username=$username',
                         limit=1)

        if qr:
            return (True, list(qr)[0])
        else:
            return (False, 'NO_SUCH_ACCOUNT')
    except Exception as e:
        log_traceback()
        return (False, repr(e))
Example #15
0
def delete_admins(mails, revoke_admin_privilege_from_user=True, conn=None):
    mails = [str(v) for v in mails if iredutils.is_email(v)]

    if not mails:
        return (True, )

    sql_vars = {'mails': mails}

    try:
        if not conn:
            _wrap = SQLWrap()
            conn = _wrap.conn

        # Standalone mail admins
        conn.delete('admin', vars=sql_vars, where='username IN $mails')

        conn.delete('domain_admins', vars=sql_vars, where='username IN $mails')

        # Unmark globa/domain admin which is mail user
        if revoke_admin_privilege_from_user:
            conn.update(
                'mailbox',
                vars=sql_vars,
                where='username IN $mails AND (isadmin=1 OR isglobaladmin=1)',
                isadmin=0,
                isglobaladmin=0)

        log_activity(event='delete',
                     msg="Delete admin(s): %s." % ', '.join(mails))

        return (True, )
    except Exception as e:
        log_traceback()
        return (False, repr(e))
Example #16
0
def set_account_status(conn,
                       accounts,
                       account_type,
                       enable_account=False):
    """Set account status.

    accounts -- an iterable object (list/tuple) filled with accounts.
    account_type -- possible value: domain, admin, user, alias
    enable_account -- possible value: True, False
    """
    if account_type in ['admin', 'user']:
        # email
        accounts = [str(v).lower() for v in accounts if iredutils.is_email(v)]
    else:
        # domain name
        accounts = [str(v).lower() for v in accounts if iredutils.is_domain(v)]

    if not accounts:
        return (True, )

    # 0: disable, 1: enable
    account_status = 0
    action = 'disable'
    if enable_account:
        account_status = 1
        action = 'active'

    if account_type == 'domain':
        # handle with function which handles admin privilege
        qr = sql_lib_domain.enable_disable_domains(domains=accounts,
                                                   action=action)
        return qr
    elif account_type == 'admin':
        # [(<table>, <column-used-for-query>), ...]
        table_column_maps = [("admin", "username")]
    elif account_type == 'alias':
        table_column_maps = [
            ("alias", "address"),
            ("forwardings", "address"),
        ]
    else:
        # account_type == 'user'
        table_column_maps = [
            ("mailbox", "username"),
            ("forwardings", "address"),
        ]

    for (_table, _column) in table_column_maps:
        sql_where = '{} IN {}'.format(_column, web.sqlquote(accounts))
        try:
            conn.update(_table,
                        where=sql_where,
                        active=account_status)

        except Exception as e:
            return (False, repr(e))

    log_activity(event=action,
                 msg="{} {}: {}.".format(action.title(), account_type, ', '.join(accounts)))
    return (True, )
Example #17
0
def is_domain_admin(domain, admin=None, conn=None) -> bool:
    if (not iredutils.is_domain(domain)) or (not iredutils.is_email(admin)):
        return False

    if not admin:
        admin = session.get('username')

    if admin == session.get('username') and session.get('is_global_admin'):
        return True

    try:
        if not conn:
            _wrap = SQLWrap()
            conn = _wrap.conn

        qr = conn.select(
            'domain_admins',
            vars={
                'domain': domain,
                'username': admin
            },
            what='username',
            where='domain=$domain AND username=$username AND active=1',
            limit=1,
        )

        if qr:
            return True
        else:
            return False
    except:
        return False
Example #18
0
def is_email_exists(mail, conn=None) -> bool:
    # Return True if account is invalid or exist.
    if not iredutils.is_email(mail):
        return True

    mail = iredutils.strip_mail_ext_address(mail)

    if not conn:
        _wrap = SQLWrap()
        conn = _wrap.conn

    try:
        # `forwardings` table has email addr of mail user account and alias account.
        qr = conn.select('forwardings',
                         vars={'mail': mail},
                         what='address',
                         where='address=$mail',
                         limit=1)

        if qr:
            return True

        # Check `alias` for alias account which doesn't have any member.
        qr = conn.select('alias',
                         vars={'mail': mail},
                         what='address',
                         where='address=$mail',
                         limit=1)
        if qr:
            return True

        return False
    except Exception:
        return True
Example #19
0
    def delete(self, domain, mails=[]):
        domain = str(domain)
        if not iredutils.is_domain(domain):
            return (False, 'INVALID_DOMAIN_NAME')

        if not isinstance(mails, list):
            return (False, 'INVALID_MAIL')

        mails = [str(v).lower() for v in mails if iredutils.is_email(v) and str(v).endswith('@' + domain)]
        if not mails:
            return (False, 'INVALID_MAIL')

        # Delete user and related records.
        try:
            qr = self.deleteAccounts(accounts=mails, accountType='user')
            if qr[0] is True:
                web.logger(
                    msg="Delete user: %s." % ', '.join(mails),
                    domain=domain,
                    event='delete',
                )
            else:
                return qr

            return (True,)
        except Exception, e:
            return (False, str(e))
Example #20
0
    def delete(self, mails=[]):
        if not isinstance(mails, list):
            return (False, 'INVALID_MAIL')

        self.mails = [str(v).lower() for v in mails if iredutils.is_email(v)]
        sql_vars = {
            'username': self.mails,
        }

        # Delete domain and related records.
        try:
            self.conn.delete(
                'admin',
                vars=sql_vars,
                where='username IN $username',
            )
            self.conn.delete(
                'domain_admins',
                vars=sql_vars,
                where='username IN $username',
            )

            web.logger(
                msg="Delete admin: %s." % ', '.join(self.mails),
                event='delete',
            )
            return (True, )
        except Exception as e:
            return (False, str(e))
Example #21
0
    def profile(self, mail):
        self.mail = web.safestr(mail)
        self.domainGlobalAdmin = False

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

        try:
            result = self.conn.select(
                'admin',
                vars={
                    'username': self.mail,
                },
                where='username=$username',
                limit=1,
            )
            if len(result) == 1:
                if self.is_global_admin(admin=self.mail):
                    self.domainGlobalAdmin = True

                return (True, self.domainGlobalAdmin, list(result)[0])
            else:
                return (False, 'INVALID_MAIL')
        except Exception as e:
            return (False, str(e))
Example #22
0
    def isAdminExists(self, mail):
        # Return True if account is invalid or exist.
        mail = str(mail)
        if not iredutils.is_email(mail):
            return True

        try:
            result = self.conn.select(
                'admin',
                vars={
                    'username': mail,
                },
                what='username',
                where='username=$username',
                limit=1,
            )

            if len(result) > 0:
                # Exists.
                return True
            else:
                return False
        except:
            # Return True as exist to not allow to create new domain/account.
            return True
Example #23
0
    def is_email_exists(self, mail):
        # Return True if account is invalid or exist.
        mail = web.safestr(mail)

        if not iredutils.is_email(mail):
            return True

        sql_vars = {
            'email': mail,
        }

        try:
            result = self.conn.select('forwardings',
                                      vars=sql_vars,
                                      what='address',
                                      where='address=$email',
                                      limit=1)

            if result:
                return True
            else:
                return False

        except Exception:
            return True
Example #24
0
    def is_email_exists(self, mail):
        # Return True if account is invalid or exist.
        mail = web.safestr(mail)

        if not iredutils.is_email(mail):
            return True

        sql_vars = {
            'email': mail,
        }

        try:
            resultOfMailbox = self.conn.select(
                'mailbox',
                vars=sql_vars,
                what='username',
                where='username=$email',
                limit=1,
            )

            resultOfAlias = self.conn.select(
                'alias',
                vars=sql_vars,
                what='address',
                where='address=$email',
                limit=1,
            )

            if resultOfMailbox or resultOfAlias:
                return True
            else:
                return False

        except Exception:
            return True
Example #25
0
    def GET(self, profile_type, mail):
        i = web.input()
        self.mail = str(mail).lower()
        self.cur_domain = self.mail.split('@', 1)[-1]
        self.profile_type = str(profile_type)

        if self.mail.startswith('@') and iredutils.is_domain(self.cur_domain):
            # Catchall account.
            raise web.seeother('/profile/domain/catchall/%s' % self.cur_domain)

        if not iredutils.is_email(self.mail):
            raise web.seeother('/domains?msg=INVALID_USER')

        if not iredutils.is_domain(self.cur_domain):
            raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME')

        userLib = userlib.User()
        qr = userLib.profile(domain=self.cur_domain, mail=self.mail)
        if qr[0] is True:
            self.profile = qr[1]
        else:
            raise web.seeother('/users/%s?msg=%s' % (self.cur_domain, web.urlquote(qr[1])))

        return web.render(
            'pgsql/user/profile.html',
            cur_domain=self.cur_domain,
            mail=self.mail,
            profile_type=self.profile_type,
            profile=self.profile,
            languagemaps=get_language_maps(),
            msg=i.get('msg'),
        )
Example #26
0
def get_multi_values(form,
                     input_name,
                     default_value=None,
                     input_is_textarea=False,
                     is_domain=False,
                     is_email=False,
                     to_lowercase=False,
                     to_uppercase=False):
    v = form.get(input_name)
    if v:
        if input_is_textarea:
            v = v.splitlines()
    else:
        v = default_value

    # Remove duplicate items.
    v = list(set(v))

    if is_domain:
        v = [str(i).lower() for i in v if iredutils.is_domain(i)]

    if is_email:
        v = [str(i).lower() for i in v if iredutils.is_email(i)]

    if to_lowercase:
        if not (is_domain or is_email):
            v = [i.lower() for i in v]

    if to_uppercase:
        if not (is_domain or is_email):
            v = [i.upper() for i in v]

    return v
Example #27
0
    def POST(self, domain):
        i = web.input(_unicode=False, mail=[])

        self.domain = str(domain)

        if not iredutils.is_domain(self.domain):
            raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME')

        self.mails = [str(v)
                      for v in i.get('mail', [])
                      if iredutils.is_email(v)
                      and str(v).endswith('@' + self.domain)
                     ]

        action = i.get('action', '')
        msg = i.get('msg', None)

        userLib = userlib.User()

        if action == 'delete':
            result = userLib.delete(domain=self.domain, mails=self.mails,)
            msg = 'DELETED'
        elif action == 'disable':
            result = userLib.enableOrDisableAccount(domain=self.domain, accounts=self.mails, active=False)
            msg = 'DISABLED'
        elif action == 'enable':
            result = userLib.enableOrDisableAccount(domain=self.domain, accounts=self.mails, active=True)
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')

        if result[0] is True:
            raise web.seeother('/users/%s?msg=%s' % (self.domain, msg,))
        else:
            raise web.seeother('/users/%s?msg=%s' % (self.domain, web.urlquote(result[1]),))
Example #28
0
    def getManagedDomains(self, mail, attrs=attrs.ADMIN_ATTRS_ALL, listedOnly=False):
        self.mail = web.safestr(mail)
        if not iredutils.is_email(self.mail):
            return (False, 'INCORRECT_USERNAME')

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

        try:
            self.managedDomains = self.conn.search_s(
                self.basedn,
                ldap.SCOPE_ONELEVEL,
                filter,
                attrs,
            )
            if listedOnly:
                domains = []
                for qr in self.managedDomains:
                    domains += qr[1]['domainName']
                self.managedDomains = domains
            return (True, self.managedDomains)
        except Exception as e:
            return (False, ldaputils.getExceptionDesc(e))
Example #29
0
    def enableOrDisableAccount(self, mails, action, attr='accountStatus',):
        if mails is None or len(mails) == 0:
            return (False, 'NO_ACCOUNT_SELECTED')

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

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

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

        if result == {}:
            return (True,)
        else:
            return (False, ldaputils.getExceptionDesc(result))
Example #30
0
def enable_disable_mail_accounts(mails, account_type, action, conn=None):
    """Enable (action='enable') or disable (action='disable') given mail users.

    :param mails: a list/tuple/set of user mail addresses
    :param account_type: user, maillist, alias.
    :param action: enable, disable.
    :param conn: ldap connection cursor
    """
    mails = [str(v).lower() for v in mails if iredutils.is_email(v)]

    action = action.lower()
    if action not in ['enable', 'disable']:
        return (False, 'INVALID_ACTION')

    if not conn:
        _wrap = LDAPWrap()
        conn = _wrap.conn

    mapping = {'user': ldaputils.rdn_value_to_user_dn}

    for mail in mails:
        _func = mapping[account_type]
        dn = _func(mail)

        qr = enable_disable_account_by_dn(dn=dn,
                                          action=action,
                                          conn=conn)
        if not qr[0]:
            return qr

    return (True, )
Example #31
0
    def getDnWithKeyword(self, value, accountType='user'):
        self.keyword = web.safestr(value)

        if accountType == 'user':
            if attrs.RDN_USER == 'mail':
                if not iredutils.is_email(self.keyword):
                    return False
                return ldaputils.convert_keyword_to_dn(self.keyword, accountType='user')
            else:
                self.domain = self.keyword.split('@', 1)[-1]
                self.dnOfDomain = ldaputils.convert_keyword_to_dn(self.domain, accountType='domain',)
                try:
                    result = self.conn.search_s(
                        attrs.DN_BETWEEN_USER_AND_DOMAIN + self.dnOfDomain,
                        ldap.SCOPE_SUBTREE,
                        '(&(objectClass=mailUser)(mail=%s))' % (self.keyword),
                    )
                    if len(result) == 1:
                        self.dn = result[0][0]
                        return self.dn
                    else:
                        return False
                except:
                    return False
        else:
            # Unsupported accountType.
            return False
Example #32
0
    def getNumberOfManagedAccounts(self, admin=None, accountType='domain', domains=[],):
        if admin is None:
            admin = session.get('username')
        else:
            admin = str(admin)

        if not iredutils.is_email(admin):
            return 0

        domains = []
        if len(domains) > 0:
            domains = [str(d).lower() for d in domains if iredutils.is_domain(d)]
        else:
            connutils = connUtils.Utils()
            qr = connutils.getManagedDomains(mail=admin, attrs=['domainName'], listedOnly=True)
            if qr[0] is True:
                domains = qr[1]

        if accountType == 'domain':
            try:
                return len(domains)
            except Exception:
                pass

        return 0
Example #33
0
    def getManagedDomains(
        self,
        admin,
        domainNameOnly=False,
        listedOnly=False,
    ):
        admin = web.safestr(admin)

        if not iredutils.is_email(admin):
            return (False, 'INCORRECT_USERNAME')

        try:
            result = self.conn.select('domain')

            if domainNameOnly is True:
                domains = []
                for i in result:
                    if iredutils.is_domain(i.domain):
                        domains += [str(i.domain).lower()]

                return (True, domains)
            else:
                return (True, list(result))
        except Exception as e:
            return (False, str(e))
Example #34
0
    def getNumberOfManagedAccounts(self, admin=None, accountType='domain', domains=[],):
        if admin is None:
            admin = session.get('username')
        else:
            admin = str(admin)

        if not iredutils.is_email(admin):
            return 0

        domains = []
        if len(domains) > 0:
            domains = [str(d).lower() for d in domains if iredutils.is_domain(d)]
        else:
            connutils = connUtils.Utils()
            qr = connutils.getManagedDomains(mail=admin, attrs=['domainName'], listedOnly=True)
            if qr[0] is True:
                domains = qr[1]

        if accountType == 'domain':
            try:
                return len(domains)
            except Exception:
                pass

        return 0
Example #35
0
    def enableOrDisableAccount(self, mails, action, attr='accountStatus',):
        if mails is None or len(mails) == 0:
            return (False, 'NO_ACCOUNT_SELECTED')

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

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

            try:
                connutils.enableOrDisableAccount(
                    domain=self.domain,
                    account=self.mail,
                    dn=self.dn,
                    action=web.safestr(action).strip().lower(),
                    accountTypeInLogger='admin',
                )
            except ldap.LDAPError, e:
                result[self.mail] = str(e)
Example #36
0
def delete(mails, revoke_admin_privilege_from_user=True, conn=None):
    """
    Delete standalone domain admin accounts, or revoke admin privilege from
    mail user which is domain admin.

    :param mails: list of domain admin email addresses
    :param revoke_admin_privilege_from_user: if @mails contains mail user which
              has domain admin privilege, we should revoke the privilege.
    :param conn: ldap connection cursor
    """
    mails = [str(i).lower() for i in mails if iredutils.is_email(i)]
    if not mails:
        return (True, )

    if not conn:
        _wrap = LDAPWrap()
        conn = _wrap.conn

    result = {}

    for mail in mails:
        # Get dn of admin account under o=domainAdmins
        dn = ldaputils.rdn_value_to_admin_dn(mail)

        try:
            conn.delete_s(dn)
            log_activity(msg="Delete admin: %s." % (mail), event='delete')
        except ldap.NO_SUCH_OBJECT:
            if revoke_admin_privilege_from_user:
                # This is a mail user admin
                dn = ldaputils.rdn_value_to_user_dn(mail)
                try:
                    # Delete enabledService=domainadmin
                    ldap_lib_general.remove_attr_values(dn=dn,
                                                        attr='enabledService',
                                                        values=['domainadmin'],
                                                        conn=conn)

                    # Delete domainGlobalAdmin=yes
                    ldap_lib_general.remove_attr_values(
                        dn=dn,
                        attr='domainGlobalAdmin',
                        values=['yes'],
                        conn=conn)

                    log_activity(msg="Revoke domain admin privilege: %s." %
                                 (mail),
                                 event='delete')
                except Exception as e:
                    result[mail] = str(e)
        except ldap.LDAPError as e:
            result[mail] = str(e)

    if result == {}:
        return (True, )
    else:
        return (False, repr(result))
Example #37
0
    def deleteSingleUserFromGroups(self, mail):
        self.mail = web.safestr(mail)
        if not iredutils.is_email(self.mail):
            return (False, 'INVALID_MAIL')

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

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

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

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

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

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

            return (True, )
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Example #38
0
def filter_existing_emails(mails, base_dn=None, conn=None):
    """
    Remove non-existing addresses from given list of mail addresses, return a
    list of existing ones.

    :param mails: list of email addresses
    :param base_dn: if not present, search from `settings.ldap_basedn`
    :param conn: ldap connection cursor
    """
    mails = [str(v).lower()
             for v in mails
             if iredutils.is_email(v)]
    mails = list(set(mails))

    result = {'exist': [], 'nonexist': []}

    if not mails:
        return result

    if not conn:
        _wrap = LDAPWrap()
        conn = _wrap.conn

    _filter = '(&'
    _filter += '(|(objectClass=mailUser)(objectClass=mailList)(objectClass=mailAlias))'
    _filter += '(|'
    for addr in mails:
        _filter += '(mail={})(shadowAddress={})'.format(addr, addr)

    _filter += '))'

    if not base_dn:
        base_dn = settings.ldap_basedn

    try:
        qr = conn.search_s(base_dn,
                           ldap.SCOPE_SUBTREE,
                           _filter,
                           ['mail', 'shadowAddress'])

        if not qr:
            # None of them exists.
            result['nonexist'] = mails
        else:
            for (_dn, _ldif) in qr:
                _ldif = iredutils.bytes2str(_ldif)
                result['exist'] += _ldif.get('mail', []) + _ldif.get('shadowAddress', [])

            result['nonexist'] = [v for v in mails if v not in result['exist']]

        # Remove duplicates and sort.
        result['exist'] = list(set(result['exist']))
        result['nonexist'] = list(set(result['nonexist']))
    except:
        log_traceback()

    return result
Example #39
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 #40
0
    def proxyfunc(*args, **kw):
        # Check domain global admin.
        if session.get('domainGlobalAdmin') is True:
            return func(*args, **kw)
        else:
            if 'domain' in kw.keys() and iredutils.is_domain(kw.get('domain')):
                domain = web.safestr(kw['domain'])
            elif 'mail' in kw.keys() and iredutils.is_email(kw.get('mail')):
                domain = web.safestr(kw['mail']).split('@')[-1]
            elif 'admin' in kw.keys() and iredutils.is_email(kw.get('admin')):
                domain = web.safestr(kw['admin']).split('@')[-1]
            else:
                return (False, 'PERMISSION_DENIED')

            # Check whether is domain admin.
            validator = core.MySQLWrap()
            if validator.is_domainAdmin(domain=domain, admin=session.get('username'),):
                return func(*args, **kw)
            else:
                return (False, 'PERMISSION_DENIED')
Example #41
0
def ldif_mailExternalUser(mail,):
    mail = web.safestr(mail).lower()
    if not iredutils.is_email(mail):
        return None

    listname, domain = mail.split('@')
    ldif = [
            ('objectClass', ['mailExternalUser']),
            ('accountStatus', ['active']),
            ('memberOfGroup', [mail]),
            ('enabledService', ['mail', 'deliver']),
            ]
    return ldif
Example #42
0
    def listLogs(self, event='all', domain='all', admin='all', cur_page=1):
        self.event = web.safestr(event)
        self.domain = web.safestr(domain)
        self.admin = web.safestr(admin)
        self.cur_page = int(cur_page)

        # Generate a dictionary, converted to an SQL WHERE clause.
        queryDict = {}
        if self.event in LOG_EVENTS and self.event != 'all':
            queryDict['event'] = self.event

        if iredutils.is_domain(self.domain):
            queryDict['domain'] = self.domain

        if session.get('domainGlobalAdmin') is not True:
            queryDict['admin'] = session.get('username')
        else:
            if iredutils.is_email(self.admin):
                queryDict['admin'] = self.admin

        # Get number of total records.
        if len(queryDict) == 0:
            qr = db.select('log', what='COUNT(timestamp) AS total',)
        else:
            qr = db.select('log', what='COUNT(timestamp) AS total', where=web.db.sqlwhere(queryDict),)

        self.total = qr[0].total or 0

        # Get records.
        if len(queryDict) == 0:
            # No addition filter.
            self.entries = db.select(
                'log',
                offset=(self.cur_page - 1) * settings.PAGE_SIZE_LIMIT,
                limit=settings.PAGE_SIZE_LIMIT,
                order='timestamp DESC',
            )
        else:
            # With filter.
            self.entries = db.select('log',
                    where=web.db.sqlwhere(queryDict),
                    offset=(self.cur_page - 1) * settings.PAGE_SIZE_LIMIT,
                    limit=settings.PAGE_SIZE_LIMIT,
                    order='timestamp DESC',
                    )

        return (self.total, list(self.entries))
Example #43
0
    def deleteSingleUserFromGroups(self, mail):
        self.mail = web.safestr(mail)
        if not iredutils.is_email(self.mail):
            return (False, "INVALID_MAIL")

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

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

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

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

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

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

            return (True,)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Example #44
0
    def POST(self):
        # Get username, password.
        i = web.input(_unicode=False)

        username = web.safestr(i.get('username', '').strip()).lower()
        password = i.get('password', '').strip()
        save_pass = web.safestr(i.get('save_pass', 'no').strip())

        if not iredutils.is_email(username):
            raise web.seeother('/login?msg=INVALID_USERNAME')

        if not password:
            raise web.seeother('/login?msg=EMPTY_PASSWORD')

        # Get LDAP URI.
        uri = settings.ldap_uri

        # Verify bind_dn & bind_pw.
        try:
            # Detect STARTTLS support.
            if uri.startswith('ldaps://'):
                starttls = True
            else:
                starttls = False

            # Set necessary option for STARTTLS.
            if starttls:
                ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

            # Initialize connection.
            conn = ldap.initialize(uri)

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

            if starttls:
                conn.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)

            # synchronous bind.
            conn.bind_s(settings.ldap_bind_dn, settings.ldap_bind_password)
            conn.unbind_s()
        except (ldap.INVALID_CREDENTIALS):
            raise web.seeother('/login?msg=vmailadmin_INVALID_CREDENTIALS')
        except Exception, e:
            raise web.seeother('/login?msg=%s' % web.safestr(e))
Example #45
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 #46
0
    def add(self, data):
        self.cn = data.get('cn')
        self.mail = web.safestr(data.get('mail')).strip().lower()

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

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

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

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

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

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

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

        try:
            self.conn.add_s(self.dn, ldif)
            web.logger(msg="Create admin: %s." % (self.mail), event='create',)
            return (True,)
        except ldap.ALREADY_EXISTS:
            return (False, 'ALREADY_EXISTS')
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Example #47
0
    def GET(self, profile_type, mail):
        i = web.input()
        self.mail = web.safestr(mail)
        self.profile_type = web.safestr(profile_type)

        if not iredutils.is_email(self.mail):
            raise web.seeother('/admins?msg=INVALID_MAIL')

        if session.get('domainGlobalAdmin') is not True and session.get('username') != self.mail:
            # Don't allow to view/update other admins' profile.
            raise web.seeother('/profile/admin/general/%s?msg=PERMISSION_DENIED' % session.get('username'))

        adminLib = adminlib.Admin()
        result = adminLib.profile(mail=self.mail)

        if result[0] is True:
            domainGlobalAdmin, profile = result[1], result[2]

            # Get all domains.
            self.allDomains = []

            domainLib = domainlib.Domain()
            resultOfAllDomains = domainLib.getAllDomains()
            if resultOfAllDomains[0] is True:
                self.allDomains = resultOfAllDomains[1]

            # Get managed domains.
            self.managedDomains = []

            return web.render(
                'pgsql/admin/profile.html',
                mail=self.mail,
                profile_type=self.profile_type,
                domainGlobalAdmin=domainGlobalAdmin,
                profile=profile,
                languagemaps=languages.get_language_maps(),
                allDomains=self.allDomains,
                min_passwd_length=settings.min_passwd_length,
                max_passwd_length=settings.max_passwd_length,
                msg=i.get('msg'),
            )
        else:
            raise web.seeother('/admins?msg=' + web.urlquote(result[1]))
Example #48
0
    def GET(self, profile_type, mail):
        i = web.input(enabledService=[], telephoneNumber=[], )
        self.mail = web.safestr(mail)
        self.cur_domain = self.mail.split('@', 1)[-1]
        self.profile_type = web.safestr(profile_type)

        if self.mail.startswith('@') and iredutils.is_domain(self.cur_domain):
            # Catchall account.
            raise web.seeother('/profile/domain/catchall/%s' % self.cur_domain)

        if not iredutils.is_email(self.mail):
            raise web.seeother('/domains?msg=INVALID_USER')

        domainAccountSetting = {}

        userLib = user.User()
        result = userLib.profile(domain=self.cur_domain, mail=self.mail)
        if result[0] is False:
            raise web.seeother('/users/%s?msg=%s' % (self.cur_domain, web.urlquote(result[1])))

        if self.profile_type == 'password':
            # Get accountSetting of current domain.
            domainLib = domainlib.Domain()
            result_setting = domainLib.getDomainAccountSetting(domain=self.cur_domain)
            if result_setting[0] is True:
                domainAccountSetting = result_setting[1]

        minPasswordLength = domainAccountSetting.get('minPasswordLength', '0')
        maxPasswordLength = domainAccountSetting.get('maxPasswordLength', '0')

        return web.render(
            'ldap/user/profile.html',
            profile_type=self.profile_type,
            mail=self.mail,
            user_profile=result[1],
            defaultStorageBaseDirectory=settings.storage_base_directory,
            minPasswordLength=minPasswordLength,
            maxPasswordLength=maxPasswordLength,
            domainAccountSetting=domainAccountSetting,
            languagemaps=get_language_maps(),
            msg=i.get('msg', None),
        )
Example #49
0
    def getManagedDomains(self, mail, attrs=attrs.ADMIN_ATTRS_ALL, listedOnly=False):
        self.mail = web.safestr(mail)
        if not iredutils.is_email(self.mail):
            return (False, "INCORRECT_USERNAME")

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

        try:
            self.managedDomains = self.conn.search_s(self.basedn, ldap.SCOPE_ONELEVEL, filter, attrs)
            if listedOnly:
                domains = []
                for qr in self.managedDomains:
                    domains += qr[1]["domainName"]
                self.managedDomains = domains
            return (True, self.managedDomains)
        except Exception, e:
            return (False, ldaputils.getExceptionDesc(e))
Example #50
0
    def getFilterOfDeleteUserFromGroups(self, mail):
        # Get valid emails as list.
        if isinstance(mail, list):
            self.mails = [web.safestr(v).lower() for v in mail if iredutils.is_email(str(v))]
        else:
            # Single email.
            self.mails = [web.safestr(mail).lower()]

        filterUserAndAlias = "(&(|(objectClass=mailAlias)(objectClass=mailUser))(|"
        filterExternalUser = "******"

        for mail in self.mails:
            filterUserAndAlias += "(mailForwardingAddress=%s)" % mail
            filterExternalUser += "(mail=%s)" % mail

        # Close filter string.
        filterUserAndAlias += "))"
        filterExternalUser += "))"

        filter = "(|" + filterUserAndAlias + filterExternalUser + ")"
        return filter
Example #51
0
    def is_domainAdmin(self, domain, admin=session.get('username'),):
        if not iredutils.is_domain(domain) or not iredutils.is_email(admin):
            return False

        if admin == session.get('username') \
           and session.get('domainGlobalAdmin') is True:
            return True

        try:
            result = self.conn.select(
                'domain_admins',
                vars={'domain': domain, 'username': admin, },
                what='username',
                where='domain=$domain AND username=$username AND active=1',
                limit=1,
            )
            if len(result) == 1:
                return True
            else:
                return False
        except Exception:
            return False
Example #52
0
    def delete(self, domain, mails=[]):
        if mails is None or len(mails) == 0:
            return (False, "NO_ACCOUNT_SELECTED")

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

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

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

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

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

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

                # Log delete action.
                web.logger(
                    msg="Delete user: %s." % (self.mail),
                    domain=self.mail.split('@')[1],
                    event='delete',
                )
                """
            except ldap.LDAPError, e:
                result[self.mail] = ldaputils.getExceptionDesc(e)
Example #53
0
    def profile(self, mail):
        self.mail = web.safestr(mail)
        self.domainGlobalAdmin = False

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

        try:
            result = self.conn.select(
                'admin',
                vars={'username': self.mail, },
                where='username=$username',
                limit=1,
            )
            if len(result) == 1:
                if self.is_global_admin(admin=self.mail):
                    self.domainGlobalAdmin = True

                return (True, self.domainGlobalAdmin, list(result)[0])
            else:
                return (False, 'INVALID_MAIL')
        except Exception, e:
            return (False, str(e))
Example #54
0
    def isAdminExists(self, mail):
        # Return True if account is invalid or exist.
        mail = str(mail)
        if not iredutils.is_email(mail):
            return True

        try:
            result = self.conn.select(
                'admin',
                vars={'username': mail, },
                what='username',
                where='username=$username',
                limit=1,
            )

            if len(result) > 0:
                # Exists.
                return True
            else:
                return False
        except:
            # Return True as exist to not allow to create new domain/account.
            return True
Example #55
0
    def isAccountExists(self, domain, mail):
        # Return True if account is invalid or exist.
        self.domain = str(domain)
        self.mail = str(mail)

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

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

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

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

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

            if self.number[0] is True and self.number[1] == 0:
                # Account not exist.
                return False
            else:
                return True
        except Exception, e:
            # Account 'EXISTS' (fake) if ldap lookup failed.
            return True
Example #56
0
    def getDnWithKeyword(self, value, accountType="user"):
        self.keyword = web.safestr(value)

        if accountType == "user":
            if attrs.RDN_USER == "mail":
                if not iredutils.is_email(self.keyword):
                    return False
                return ldaputils.convert_keyword_to_dn(self.keyword, accountType="user")
            else:
                self.domain = self.keyword.split("@", 1)[-1]
                self.dnOfDomain = ldaputils.convert_keyword_to_dn(self.domain, accountType="domain")
                try:
                    result = self.conn.search_s(
                        attrs.DN_BETWEEN_USER_AND_DOMAIN + self.dnOfDomain,
                        ldap.SCOPE_SUBTREE,
                        "(&(objectClass=mailUser)(mail=%s))" % (self.keyword),
                    )
                    if len(result) == 1:
                        self.dn = result[0][0]
                        return self.dn
                    else:
                        return False
                except Exception, e:
                    return False
Example #57
0
    def delete(self, mails=[]):
        if not isinstance(mails, list):
            return (False, 'INVALID_MAIL')

        self.mails = [str(v).lower() for v in mails if iredutils.is_email(v)]
        sql_vars = {'username': self.mails, }

        # Delete domain and related records.
        try:
            self.conn.delete(
                'admin',
                vars=sql_vars,
                where='username IN $username',
            )
            self.conn.delete(
                'domain_admins',
                vars=sql_vars,
                where='username IN $username',
            )

            web.logger(msg="Delete admin: %s." % ', '.join(self.mails), event='delete',)
            return (True,)
        except Exception, e:
            return (False, str(e))
Example #58
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_for_sql_mail_account(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))