Esempio n. 1
0
def add(form, conn=None):
    """Add new standalone admin account."""
    mail = form_utils.get_single_value(form=form,
                                       input_name='mail',
                                       to_lowercase=True,
                                       to_string=True)

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

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

    # Make sure it's not hosted domain
    domain = mail.split('@', 1)[-1]
    if ldap_lib_general.is_domain_exists(domain=domain, conn=conn):
        return (False, 'CAN_NOT_BE_LOCAL_DOMAIN')

    name = form_utils.get_single_value(form=form, input_name='cn')
    account_status = form_utils.get_single_value(form=form,
                                                 input_name='accountStatus',
                                                 default_value='active',
                                                 to_string=True)
    lang = form_utils.get_single_value(form=form,
                                       input_name='preferredLanguage',
                                       to_string=True)

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

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

    ldif = iredldif.ldif_mailadmin(mail=mail,
                                   passwd=passwd,
                                   cn=name,
                                   account_status=account_status,
                                   preferred_language=lang)

    dn = ldaputils.rdn_value_to_admin_dn(mail)

    try:
        conn.add_s(dn, ldif)
        log_activity(msg="Create admin: %s." % (mail), event='create')
        return (True, )
    except ldap.ALREADY_EXISTS:
        return (False, 'ALREADY_EXISTS')
    except Exception as e:
        return (False, repr(e))
Esempio n. 2
0
    def POST(self):
        i = web.input(domainName=[], _unicode=False,)
        domainName = i.get('domainName', None)
        action = i.get('action')

        domainLib = domainlib.Domain()
        if action == 'delete':
            keep_mailbox_days = form_utils.get_single_value(form=i,
                                                            input_name='keep_mailbox_days',
                                                            default_value=0,
                                                            is_integer=True)

            result = domainLib.delete(domains=domainName, keep_mailbox_days=keep_mailbox_days)
            msg = 'DELETED'
        elif action == 'disable':
            result = domainLib.enableOrDisableAccount(accounts=domainName, active=False,)
            msg = 'DISABLED'
        elif action == 'enable':
            result = domainLib.enableOrDisableAccount(accounts=domainName, active=True,)
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')
            msg = i.get('msg', None)

        if result[0] is True:
            raise web.seeother('/domains?msg=%s' % msg)
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))
Esempio n. 3
0
    def POST(self, domain):
        domain = str(domain).lower()
        form = web.input()

        domain_in_form = form_utils.get_domain_name(form)
        current_admin_managed_domains = sql_lib_admin.get_managed_domains(
            session.get('username'), domain_name_only=True)[1]
        if ((domain != domain_in_form) or
            (domain not in current_admin_managed_domains) or
            (domain_in_form not in current_admin_managed_domains)
            ) and not session.get('is_global_admin'):
            raise web.seeother('/domains?msg=PERMISSION_DENIED')

        # Get username
        username = form_utils.get_single_value(form,
                                               input_name='username',
                                               to_string=True)

        qr = sql_lib_user.add_user_from_form(domain=domain, form=form)

        if qr[0]:
            raise web.seeother(
                '/profile/user/general/{}@{}?msg=CREATED'.format(
                    username, domain))
        else:
            raise web.seeother('/create/user/{}?msg={}'.format(
                domain, web.urlquote(qr[1])))
Esempio n. 4
0
    def POST(self):
        form = web.input(domainName=[], _unicode=False)

        domains = form.get('domainName', [])
        action = form.get('action', None)

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

        if action == 'delete':
            keep_mailbox_days = form_utils.get_single_value(
                form=form,
                input_name='keep_mailbox_days',
                default_value=0,
                is_integer=True)

            result = ldap_lib_domain.delete_domains(
                domains=domains, keep_mailbox_days=keep_mailbox_days)
            msg = 'DELETED'
        elif action == 'disable':
            result = ldap_lib_domain.enable_disable_domains(domains=domains,
                                                            action='disable')
            msg = 'DISABLED'
        elif action == 'enable':
            result = ldap_lib_domain.enable_disable_domains(domains=domains,
                                                            action='enable')
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')
            msg = form.get('msg', None)

        if result[0] is True:
            raise web.seeother('/domains?msg=%s' % msg)
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))
Esempio n. 5
0
    def POST(self, domain, page=1):
        form = web.input(_unicode=False, mail=[])
        page = int(page)
        if page < 1:
            page = 1

        domain = str(domain).lower()
        mails = form.get('mail', [])
        action = form.get('action', None)

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

        if action == 'delete':
            keep_mailbox_days = form_utils.get_single_value(
                form=form,
                input_name='keep_mailbox_days',
                default_value=0,
                is_integer=True)

            result = ldap_lib_user.delete(domain=domain,
                                          mails=mails,
                                          keep_mailbox_days=keep_mailbox_days,
                                          conn=None)
            msg = 'DELETED'
        elif action == 'disable':
            result = ldap_lib_general.enable_disable_users(mails=mails,
                                                           action='disable',
                                                           conn=None)
            msg = 'DISABLED'
        elif action == 'enable':
            result = ldap_lib_general.enable_disable_users(mails=mails,
                                                           action='enable',
                                                           conn=None)
            msg = 'ENABLED'
        elif action in [
                'markasadmin', 'unmarkasadmin', 'markasglobaladmin',
                'unmarkasglobaladmin'
        ]:
            result = ldap_lib_user.mark_unmark_as_admin(domain=domain,
                                                        mails=mails,
                                                        action=action,
                                                        conn=None)
            msg = action.upper()
        else:
            result = (False, 'INVALID_ACTION')
            msg = form.get('msg', None)

        if result[0] is True:
            raise web.seeother('/users/%s/page/%d?msg=%s' %
                               (domain, page, msg))
        else:
            raise web.seeother('/users/%s/page/%d?msg=%s' %
                               (domain, page, web.urlquote(result[1])))
Esempio n. 6
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', None)
        msg = i.get('msg', None)

        userLib = userlib.User()

        if action == 'delete':
            keep_mailbox_days = form_utils.get_single_value(
                form=i,
                input_name='keep_mailbox_days',
                default_value=0,
                is_integer=True)
            result = userLib.delete(domain=self.domain,
                                    mails=self.mails,
                                    keep_mailbox_days=keep_mailbox_days)
            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]),
            ))
Esempio n. 7
0
    def POST(self, domain):
        i = web.input(_unicode=False, mail=[])
        self.domain = web.safestr(domain)
        self.mails = i.get('mail', [])
        action = i.get('action', None)

        userLib = user.User()

        if action == 'delete':
            keep_mailbox_days = form_utils.get_single_value(
                form=i,
                input_name='keep_mailbox_days',
                default_value=0,
                is_integer=True)
            result = userLib.delete(domain=self.domain,
                                    mails=self.mails,
                                    keep_mailbox_days=keep_mailbox_days)
            msg = 'DELETED'
        elif action == 'disable':
            result = userLib.enableOrDisableAccount(
                domain=self.domain,
                mails=self.mails,
                action='disable',
            )
            msg = 'DISABLED'
        elif action == 'enable':
            result = userLib.enableOrDisableAccount(
                domain=self.domain,
                mails=self.mails,
                action='enable',
            )
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')
            msg = i.get('msg', None)

        if result[0] is True:
            cur_page = i.get('cur_page', '1')
            raise web.seeother('/users/%s/page/%s?msg=%s' % (
                self.domain,
                str(cur_page),
                msg,
            ))
        else:
            raise web.seeother('/users/%s?msg=%s' %
                               (self.domain, web.urlquote(result[1])))
Esempio n. 8
0
    def POST(self, domain):
        domain = str(domain).lower()
        form = web.input()

        domain_in_form = form_utils.get_domain_name(form)
        if domain != domain_in_form:
            raise web.seeother('/api?msg=PERMISSION_DENIED')

        # Get domain name, username, cn.
        username = form_utils.get_single_value(form,
                                               input_name='username',
                                               to_string=True)

        qr = sql_lib_user.add_user_from_form(domain=domain, form=form)

        if qr[0]:
            raise web.seeother('/api?msg=CREATED')
        else:
            raise web.seeother('/api?msg={}'.format(web.urlquote(qr[1])))
Esempio n. 9
0
    def POST(self, domain):
        domain = str(domain).lower()
        form = web.input()

        domain_in_form = form_utils.get_domain_name(form)
        if domain != domain_in_form:
            raise web.seeother('/domains?msg=PERMISSION_DENIED')

        # Get username, cn.
        username = form_utils.get_single_value(form,
                                               input_name='username',
                                               to_string=True)

        result = ldap_lib_user.add(domain=domain, form=form, conn=None)
        if result[0] is True:
            raise web.seeother('/profile/user/general/%s?msg=CREATED' %
                               (username + '@' + domain))
        else:
            raise web.seeother('/create/user/{}?msg={}'.format(
                domain, web.urlquote(result[1])))
Esempio n. 10
0
    def POST(self):
        form = web.input(domainName=[], _unicode=False)
        domains = form.get('domainName', [])
        action = form.get('action')

        if action not in ['delete', 'enable', 'disable']:
            raise web.seeother('/domains?msg=INVALID_ACTION')

        _wrap = SQLWrap()
        conn = _wrap.conn

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

        if action == 'delete':
            keep_mailbox_days = form_utils.get_single_value(
                form=form,
                input_name='keep_mailbox_days',
                default_value=0,
                is_integer=True)

            qr = sql_lib_domain.delete_domains(
                domains=domains,
                keep_mailbox_days=keep_mailbox_days,
                conn=conn)
            msg = 'DELETED'

        elif action in ['enable', 'disable']:
            qr = sql_lib_domain.enable_disable_domains(domains=domains,
                                                       action=action,
                                                       conn=conn)

            # msg: ENABLED, DISABLED
            msg = action.upper() + 'D'
        else:
            raise web.seeother('/domains?msg=INVALID_ACTION')

        if qr[0]:
            raise web.seeother('/domains?msg=%s' % msg)
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(qr[1]))
Esempio n. 11
0
def add_admin_from_form(form, conn=None):
    mail = web.safestr(form.get('mail')).strip().lower()

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

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

    qr = iredpwd.verify_new_password(newpw=newpw, confirmpw=confirmpw)
    if qr[0] is True:
        passwd = qr[1]
    else:
        return qr

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

    # Check local domain
    domain = mail.split('@', 1)[-1]
    if not iredutils.is_domain(domain):
        return (False, 'INVALID_DOMAIN')

    if sql_lib_general.is_domain_exists(domain=domain, conn=conn):
        return (False, 'CAN_NOT_BE_LOCAL_DOMAIN')

    # Check admin exist.
    if is_admin_exists(conn=conn, admin=mail):
        return (False, 'ALREADY_EXISTS')

    # Name, language
    cn = form.get('cn', '')
    managed_domains = form.get('managed_domains', [])
    lang = form_utils.get_language(form)
    _status = form_utils.get_single_value(form=form,
                                          input_name='accountStatus',
                                          default_value='active')
    if _status == 'active':
        _status = 1
    else:
        _status = 0

    # GET ALL valid DOMAINS
    all_domains = sql_lib_domain.get_all_domains(conn=conn, name_only=True)
    if all_domains[0]:
        all_domains = all_domains[1]
    else:
        all_domains = []

    #Check form submitted DOMAINS for validity
    for i in managed_domains:
        if i not in all_domains:
            if i != "ALL":
                managed_domains = list(filter((i).__ne__, managed_domains))
    managed_domains = list(set(managed_domains))

    try:
        if len(managed_domains) > 0:
            conn.insert('admin',
                        username=mail,
                        name=cn,
                        password=iredpwd.generate_password_hash(passwd),
                        language=lang,
                        created=iredutils.get_gmttime(),
                        active=_status)

            for i in managed_domains:
                conn.insert('domain_admins',
                            username=mail,
                            domain=i,
                            created=iredutils.get_gmttime(),
                            active='1')

            log_activity(msg="Create admin: %s." % (mail), event='create')
            return (True, )
        else:
            return (False, "No Valid Domain Selected!")
    except Exception as e:
        log_traceback()
        return (False, repr(e))
Esempio n. 12
0
def add_admin_from_form(form, conn=None):
    mail = web.safestr(form.get('mail')).strip().lower()

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

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

    qr = iredpwd.verify_new_password(newpw=newpw, confirmpw=confirmpw)
    if qr[0] is True:
        passwd = qr[1]
    else:
        return qr

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

    # Check local domain
    domain = mail.split('@', 1)[-1]
    if not iredutils.is_domain(domain):
        return (False, 'INVALID_DOMAIN')

    if sql_lib_general.is_domain_exists(domain=domain, conn=conn):
        return (False, 'CAN_NOT_BE_LOCAL_DOMAIN')

    # Check admin exist.
    if is_admin_exists(conn=conn, admin=mail):
        return (False, 'ALREADY_EXISTS')

    # Name, language
    cn = form.get('cn', '')
    lang = form_utils.get_language(form)
    _status = form_utils.get_single_value(form=form,
                                          input_name='accountStatus',
                                          default_value='active')
    if _status == 'active':
        _status = 1
    else:
        _status = 0

    try:
        conn.insert('admin',
                    username=mail,
                    name=cn,
                    password=iredpwd.generate_password_hash(passwd),
                    language=lang,
                    created=iredutils.get_gmttime(),
                    active=_status)

        conn.insert('domain_admins',
                    username=mail,
                    domain='ALL',
                    created=iredutils.get_gmttime(),
                    active='1')

        log_activity(msg="Create admin: %s." % (mail), event='create')
        return (True, )
    except Exception as e:
        log_traceback()
        return (False, repr(e))
Esempio n. 13
0
def update(profile_type, mail, form, conn=None):
    profile_type = web.safestr(profile_type)
    mail = str(mail).lower()
    (username, domain) = mail.split('@', 1)

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

    # Get account dn.
    dn_user = ldaputils.rdn_value_to_user_dn(mail)

    mod_attrs = []

    qr = ldap_lib_general.get_domain_account_setting(domain=domain, conn=conn)
    if qr[0]:
        domainAccountSetting = qr[1]
    else:
        return qr

    qr = get_profile(mail=mail, conn=conn)
    if qr[0]:
        user_profile = qr[1]['ldif']
        user_account_setting = ldaputils.get_account_setting_from_profile(
            user_profile)
    else:
        return qr

    if profile_type == 'general':
        # Update domainGlobalAdmin=yes
        if session.get('is_global_admin'):
            # Update domainGlobalAdmin=yes
            if 'domainGlobalAdmin' in form:
                mod_attrs = ldaputils.mod_replace('domainGlobalAdmin', 'yes')

                if user_profile.get('domainGlobalAdmin') != ['yes']:
                    log_activity(msg="User %s is marked as global admin." %
                                 mail,
                                 username=mail,
                                 domain=domain,
                                 event='grant')
            else:
                mod_attrs = ldaputils.mod_replace('domainGlobalAdmin', None)

                if user_profile.get('domainGlobalAdmin') == ['yes']:
                    log_activity(msg="User %s is not a global admin anymore." %
                                 mail,
                                 username=mail,
                                 domain=domain,
                                 event='revoke')

        # Get full name, first name, last name.
        # Note: cn, givenName, sn are required by objectClass `inetOrgPerson`.
        cn = form_utils.get_name(form=form, input_name="cn")
        first_name = form_utils.get_single_value(form=form,
                                                 input_name="first_name")
        last_name = form_utils.get_single_value(form=form,
                                                input_name="last_name")

        mod_attrs += ldaputils.mod_replace(attr="cn",
                                           value=cn,
                                           default=username)

        mod_attrs += ldaputils.mod_replace(attr='givenName',
                                           value=first_name,
                                           default=username)

        mod_attrs += ldaputils.mod_replace(attr='sn',
                                           value=last_name,
                                           default=username)

        # Get preferred language: short lang code. e.g. en_US, de_DE.
        preferred_language = form_utils.get_language(form)
        # Must be equal to or less than 5 characters.
        if not (preferred_language in iredutils.get_language_maps()):
            preferred_language = None

        mod_attrs += ldaputils.mod_replace('preferredLanguage',
                                           preferred_language)

        # Update language immediately.
        if session.get('username') == mail and \
           session.get('lang', 'en_US') != preferred_language:
            session['lang'] = preferred_language

        # Update timezone
        tz_name = form_utils.get_timezone(form)

        if qr[0]:
            user_account_setting['timezone'] = tz_name

            if session['username'] == mail and tz_name:
                session['timezone'] = TIMEZONES[tz_name]

        # Update employeeNumber, mobile, title.
        mod_attrs += ldaputils.mod_replace('employeeNumber',
                                           form.get('employeeNumber'))

        ############
        # Reset quota
        #
        # Get new mail quota from web form.
        quota = form_utils.get_single_value(form=form,
                                            input_name='mailQuota',
                                            default_value=0,
                                            is_integer=True)

        # quota must be stored in bytes.
        mod_attrs += ldaputils.mod_replace('mailQuota', quota * 1024 * 1024)

        # Get telephoneNumber, mobile.
        # - multi values are allowed.
        # - non-ascii characters are not allowed.
        for k in ['mobile', 'telephoneNumber']:
            mod_attrs += ldaputils.form_mod_attrs_from_api(form=form,
                                                           input_name=k,
                                                           attr=k,
                                                           to_string=True)

        # Get title, with multiple values.
        for _attr in ['title']:
            _values = [v for v in form.get(_attr, []) if v]

            # Remove duplicate entries
            _values = list(set(_values))

            mod_attrs += ldaputils.mod_replace(attr=_attr, value=_values)

        # check account status.
        accountStatus = 'disabled'
        if 'accountStatus' in form:
            accountStatus = 'active'
        mod_attrs += ldaputils.mod_replace('accountStatus', accountStatus)

    elif profile_type == 'password':
        # Get password length from @domainAccountSetting.
        (min_pw_len,
         max_pw_len) = ldap_lib_general.get_domain_password_lengths(
             domain=domain,
             account_settings=domainAccountSetting,
             fallback_to_global_settings=False,
             conn=conn)

        # Get new passwords from user input.
        newpw = web.safestr(form.get('newpw', ''))
        confirmpw = web.safestr(form.get('confirmpw', ''))

        result = iredpwd.verify_new_password(newpw=newpw,
                                             confirmpw=confirmpw,
                                             min_passwd_length=min_pw_len,
                                             max_passwd_length=max_pw_len)

        if result[0] is True:
            if 'store_password_in_plain_text' in form and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                passwd = iredpwd.generate_password_hash(result[1],
                                                        pwscheme='PLAIN')
            else:
                passwd = iredpwd.generate_password_hash(result[1])

            mod_attrs += ldaputils.mod_replace('userPassword', passwd)
            mod_attrs += ldaputils.mod_replace(
                'shadowLastChange', ldaputils.get_days_of_shadow_last_change())

            # Always store plain password in another attribute.
            if settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR:
                mod_attrs += ldaputils.mod_replace(
                    settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR, newpw)
        else:
            return result

    # accountSetting
    list_of_account_setting = ldaputils.account_setting_dict_to_list(
        user_account_setting)
    mod_attrs += ldaputils.mod_replace('accountSetting',
                                       list_of_account_setting)

    try:
        conn.modify_s(dn_user, mod_attrs)

        log_activity(msg="Update user profile ({}): {}.".format(
            profile_type, mail),
                     admin=session.get('username'),
                     username=mail,
                     domain=domain,
                     event='update')

        return (True, {})
    except Exception as e:
        return (False, repr(e))
Esempio n. 14
0
def add(domain, form, conn=None):
    # Get domain name, username, cn.
    form_domain = form_utils.get_domain_name(form)
    if not (domain == form_domain):
        return (False, 'INVALID_DOMAIN_NAME')

    username = web.safestr(form.get('username')).strip().lower()
    mail = username + '@' + domain
    mail = iredutils.strip_mail_ext_address(mail)

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

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

    _qr = ldap_lib_general.check_account_existence(mail=mail,
                                                   account_type='mail',
                                                   conn=conn)
    if _qr[0] is not False:
        return (False, 'ALREADY_EXISTS')

    # Get @domainAccountSetting.
    qr = ldap_lib_domain.get_profile(domain=domain, conn=conn)

    if not qr[0]:
        return qr

    domain_profile = qr[1]['ldif']
    domain_status = domain_profile.get('accountStatus', ['disabled'])[0]
    domainAccountSetting = ldaputils.get_account_setting_from_profile(
        domain_profile)

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

    _pw_hash = form.get('password_hash', '')
    if _pw_hash:
        if not iredpwd.is_supported_password_scheme(_pw_hash):
            return (False, 'INVALID_PASSWORD_SCHEME')

        passwd_plain = ''
        passwd_hash = _pw_hash
    else:
        (min_pw_len,
         max_pw_len) = ldap_lib_general.get_domain_password_lengths(
             domain=domain,
             account_settings=domainAccountSetting,
             fallback_to_global_settings=False,
             conn=conn,
         )

        qr = form_utils.get_password(form=form,
                                     input_name='newpw',
                                     confirm_pw_input_name='confirmpw',
                                     min_passwd_length=min_pw_len,
                                     max_passwd_length=max_pw_len)

        if qr[0]:
            passwd_plain = qr[1]['pw_plain']
            passwd_hash = qr[1]['pw_hash']
        else:
            return qr

    cn = form_utils.get_name(form=form, input_name="cn")

    # Get preferred language.
    preferred_language = form_utils.get_language(form=form)
    if preferred_language not in iredutils.get_language_maps():
        preferred_language = None

    # Get user quota. Unit is MB.
    quota = form_utils.get_single_value(form=form,
                                        input_name='mailQuota',
                                        default_value=0,
                                        is_integer=True)

    quota = abs(quota)

    if quota == 0:
        # Get per-domain default user quota
        default_user_quota = ldap_lib_domain.get_default_user_quota(
            domain=domain, domain_account_setting=domainAccountSetting)

        quota = default_user_quota

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

    db_settings = iredutils.get_settings_from_db()
    # Get mailbox format and folder.
    _mailbox_format = form.get('mailboxFormat', '').lower()
    _mailbox_folder = form.get('mailboxFolder', '')
    if not iredutils.is_valid_mailbox_format(_mailbox_format):
        _mailbox_format = db_settings['mailbox_format']

    if not iredutils.is_valid_mailbox_folder(_mailbox_folder):
        _mailbox_folder = db_settings['mailbox_folder']

    # Get full maildir path
    _mailbox_maildir = form.get('maildir')

    # Get default mailing lists which set in domain accountSetting.
    ldif = iredldif.ldif_mailuser(
        domain=domain,
        username=username,
        cn=cn,
        passwd=passwd_hash,
        quota=quota,
        storage_base_directory=defaultStorageBaseDirectory,
        mailbox_format=_mailbox_format,
        mailbox_folder=_mailbox_folder,
        mailbox_maildir=_mailbox_maildir,
        language=preferred_language,
        domain_status=domain_status,
    )

    dn_user = ldaputils.rdn_value_to_user_dn(mail)

    # Store plain password in additional attribute
    if passwd_plain and settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR:
        ldif += [(settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR,
                  [passwd_plain])]

    try:
        conn.add_s(dn_user, ldif)

        # Update count of accounts
        ldap_lib_general.update_num_domain_current_users(domain=domain,
                                                         increase=True,
                                                         conn=conn)

        log_activity(msg="Create user: %s." % (mail),
                     domain=domain,
                     event='create')

        return (True, )
    except ldap.ALREADY_EXISTS:
        return (False, 'ALREADY_EXISTS')
    except Exception as e:
        return (False, repr(e))
Esempio n. 15
0
def update(domain, profile_type, form, conn=None):
    profile_type = str(profile_type)
    domain = str(domain).lower()
    sql_vars = {'domain': domain}

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

    db_settings = iredutils.get_settings_from_db()

    # Get current domain profile
    qr = simple_profile(conn=conn, domain=domain)
    if qr[0]:
        domain_profile = qr[1]
        domain_settings = sqlutils.account_settings_string_to_dict(
            domain_profile.get('settings', ''))
        del qr
    else:
        return qr

    # Check disabled domain profiles
    disabled_domain_profiles = []
    if not session.get('is_global_admin'):
        disabled_domain_profiles = domain_settings.get(
            'disabled_domain_profiles', [])
        if profile_type in disabled_domain_profiles:
            return (False, 'PERMISSION_DENIED')

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

    if profile_type == 'general':
        # Get name
        cn = form.get('cn', '')
        updates['description'] = cn

        # Get default quota for new user.
        default_user_quota = form_utils.get_single_value(
            form=form,
            input_name='defaultQuota',
            default_value=0,
            is_integer=True)
        if default_user_quota > 0:
            domain_settings['default_user_quota'] = default_user_quota
        else:
            if 'default_user_quota' in domain_settings:
                domain_settings.pop('default_user_quota')

    elif profile_type == 'advanced':
        # Update min/max password length in domain setting
        if session.get('is_global_admin') or ('password_policies'
                                              not in disabled_domain_profiles):
            for (_input_name,
                 _key_name) in [('minPasswordLength', 'min_passwd_length'),
                                ('maxPasswordLength', 'max_passwd_length')]:
                try:
                    _length = int(form.get(_input_name, 0))
                except:
                    _length = 0

                if _length > 0:
                    if not session.get('is_global_admin'):
                        # Make sure domain setting doesn't exceed global setting.
                        if _input_name == 'minPasswordLength':
                            # Cannot be shorter than global setting.
                            if _length < db_settings['min_passwd_length']:
                                _length = db_settings['min_passwd_length']
                        elif _input_name == 'maxPasswordLength':
                            # Cannot be longer than global setting.
                            if (db_settings['max_passwd_length'] > 0) and \
                               (_length > db_settings['max_passwd_length'] or _length <= db_settings['min_passwd_length']):
                                _length = db_settings['max_passwd_length']

                    domain_settings[_key_name] = _length
                else:
                    if _key_name in domain_settings:
                        domain_settings.pop(_key_name)

        # Update default language for new user
        default_language = form_utils.get_language(form)
        if default_language in iredutils.get_language_maps():
            domain_settings['default_language'] = default_language

        domain_settings['timezone'] = form_utils.get_timezone(form)

    updates['settings'] = sqlutils.account_settings_dict_to_string(
        domain_settings)
    try:
        conn.update('domain', vars=sql_vars, where='domain=$domain', **updates)

        log_activity(msg="Update domain profile: {} ({}).".format(
            domain, profile_type),
                     domain=domain,
                     event='update')

        return (True, )
    except Exception as e:
        return (False, repr(e))
Esempio n. 16
0
    def POST(self, domain, page=1):
        form = web.input(_unicode=False, mail=[])
        page = int(page)
        if page < 1:
            page = 1

        domain = str(domain).lower()

        # Filter users not under the same domain.
        mails = [
            str(v) for v in form.get('mail', [])
            if iredutils.is_email(v) and str(v).endswith('@' + domain)
        ]

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

        redirect_to_admin_list = False
        if 'redirect_to_admin_list' in form:
            redirect_to_admin_list = True

        _wrap = SQLWrap()
        conn = _wrap.conn

        if not session.get('is_global_admin'):
            for mail in mails:
                if (mail == session.get('username')
                    ) or sql_lib_user.user_is_global_admin(
                        conn=conn,
                        mail=mail) or sql_lib_user.user_is_normal_admin(
                            conn=conn, mail=mail):
                    mails = list(filter((mail).__ne__, mails))

        if session.get('username') in mails:
            mails = list(filter((session.get('username')).__ne__, mails))

        if len(mails) == 0:
            msg = "NO ELIGIBLE ACCOUNTS SELECTED FOR GIVEN ACTION"
            raise web.seeother('/users/%s/page/%d?msg=%s' %
                               (domain, page, msg))

        if action == 'delete':
            keep_mailbox_days = form_utils.get_single_value(
                form=form,
                input_name='keep_mailbox_days',
                default_value=0,
                is_integer=True)
            result = sql_lib_user.delete_users(
                conn=conn, accounts=mails, keep_mailbox_days=keep_mailbox_days)
            msg = 'DELETED'
        elif action == 'disable':
            result = sql_lib_utils.set_account_status(conn=conn,
                                                      accounts=mails,
                                                      account_type='user',
                                                      enable_account=False)
            msg = 'DISABLED'
        elif action == 'enable':
            result = sql_lib_utils.set_account_status(conn=conn,
                                                      accounts=mails,
                                                      account_type='user',
                                                      enable_account=True)
            msg = 'ENABLED'
        elif action == 'markasadmin' and session.get('is_global_admin'):
            result = sql_lib_user.mark_user_as_admin(conn=conn,
                                                     domain=domain,
                                                     users=mails,
                                                     as_normal_admin=True)
            msg = 'MARKASADMIN'
        elif action == 'unmarkasadmin' and session.get('is_global_admin'):
            result = sql_lib_user.mark_user_as_admin(conn=conn,
                                                     domain=domain,
                                                     users=mails,
                                                     as_normal_admin=False)
            msg = 'UNMARKASADMIN'
        elif action == 'markasglobaladmin' and session.get('is_global_admin'):
            result = sql_lib_user.mark_user_as_admin(conn=conn,
                                                     domain=domain,
                                                     users=mails,
                                                     as_global_admin=True)
            msg = 'MARKASGLOBALADMIN'
        elif action == 'unmarkasglobaladmin' and session.get(
                'is_global_admin'):
            result = sql_lib_user.mark_user_as_admin(conn=conn,
                                                     domain=domain,
                                                     users=mails,
                                                     as_global_admin=False)
            msg = 'UNMARKASGLOBALADMIN'
        else:
            result = (False, 'INVALID_ACTION')

        if result[0] is True:
            if redirect_to_admin_list:
                raise web.seeother('/admins/%s/page/%d?msg=%s' %
                                   (domain, page, msg))
            else:
                raise web.seeother('/users/%s/page/%d?msg=%s' %
                                   (domain, page, msg))
        else:
            if redirect_to_admin_list:
                raise web.seeother('/admins/%s/page/%d?msg=%s' %
                                   (domain, page, web.urlquote(result[1])))
            else:
                raise web.seeother('/users/%s/page/%d?msg=%s' %
                                   (domain, page, web.urlquote(result[1])))
Esempio n. 17
0
def add_user_from_form(domain, form, conn=None):
    # Get domain name, username, cn.
    mail_domain = form_utils.get_domain_name(form)
    mail_username = form.get('username')
    if mail_username:
        mail_username = web.safestr(mail_username).strip().lower()
    else:
        return (False, 'INVALID_ACCOUNT')

    mail = mail_username + '@' + mail_domain

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

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

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

    # Check account existing.
    if sql_lib_general.is_email_exists(mail=mail, conn=conn):
        return (False, 'ALREADY_EXISTS')

    # Get domain profile.
    qr_profile = sql_lib_domain.profile(conn=conn, domain=domain)

    if qr_profile[0] is True:
        domain_profile = qr_profile[1]
        domain_settings = sqlutils.account_settings_string_to_dict(
            domain_profile['settings'])
    else:
        return qr_profile

    # Check account limit.
    num_exist_accounts = sql_lib_admin.num_managed_users(conn=conn,
                                                         domains=[domain])

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

    # Get quota from <form>
    quota = str(form.get('mailQuota', 0)).strip()
    try:
        quota = int(quota)
    except:
        quota = 0

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

    if pw_hash:
        if not iredpwd.is_supported_password_scheme(pw_hash):
            return (False, 'INVALID_PASSWORD_SCHEME')

        passwd = pw_hash
    else:
        # Get password length limit from domain profile or global setting.
        min_passwd_length = domain_settings.get('min_passwd_length', 0)
        max_passwd_length = domain_settings.get('max_passwd_length', 0)

        qr_pw = iredpwd.verify_new_password(
            newpw,
            confirmpw,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length)

        if qr_pw[0] is True:
            pwscheme = None
            if 'store_password_in_plain_text' in form and settings.STORE_PASSWORD_IN_PLAIN_TEXT:
                pwscheme = 'PLAIN'
            passwd = iredpwd.generate_password_hash(qr_pw[1],
                                                    pwscheme=pwscheme)
        else:
            return qr_pw

    # Get display name from <form>
    cn = form_utils.get_single_value(form, input_name='cn', default_value='')

    # Get preferred language.
    preferred_language = form_utils.get_language(form)
    if preferred_language not in iredutils.get_language_maps():
        preferred_language = ''

    # Get storage base directory.
    _storage_base_directory = settings.storage_base_directory
    splited_sbd = _storage_base_directory.rstrip('/').split('/')
    storage_node = splited_sbd.pop()
    storage_base_directory = '/'.join(splited_sbd)
    maildir = iredutils.generate_maildir_path(mail)

    # Read full maildir path from web form - from RESTful API.
    mailbox_maildir = form.get('maildir', '').lower().rstrip('/')
    if mailbox_maildir and os.path.isabs(mailbox_maildir):
        # Split storageBaseDirectory and storageNode
        _splited = mailbox_maildir.rstrip('/').split('/')
        storage_base_directory = '/' + _splited[0]
        storage_node = _splited[1]
        maildir = '/'.join(_splited[2:])

    record = {
        'domain': domain,
        'username': mail,
        'password': passwd,
        'name': cn,
        'quota': quota,
        'storagebasedirectory': storage_base_directory,
        'storagenode': storage_node,
        'maildir': maildir,
        'language': preferred_language,
        'passwordlastchange': iredutils.get_gmttime(),
        'created': iredutils.get_gmttime(),
        'active': 1
    }

    # Get settings from SQL db.
    db_settings = iredutils.get_settings_from_db()

    # Get mailbox format and folder.
    _mailbox_format = form.get('mailboxFormat',
                               db_settings['mailbox_format']).lower()
    _mailbox_folder = form.get('mailboxFolder', db_settings['mailbox_folder'])
    if iredutils.is_valid_mailbox_format(_mailbox_format):
        record['mailboxformat'] = _mailbox_format

    if iredutils.is_valid_mailbox_folder(_mailbox_folder):
        record['mailboxfolder'] = _mailbox_folder

    # Always store plain password in another attribute.
    if settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR:
        record[settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR] = newpw

    # Set disabled mail services.
    disabled_mail_services = domain_settings.get('disabled_mail_services', [])
    for srv in disabled_mail_services:
        record['enable' + srv] = 0

    # globally disabled mail services
    for srv in settings.ADDITIONAL_DISABLED_USER_SERVICES:
        record['enable' + srv] = 0

    # globally enabled mail services
    for srv in settings.ADDITIONAL_ENABLED_USER_SERVICES:
        record['enable' + srv] = 1

    try:
        # Store new user in SQL db.
        conn.insert('mailbox', **record)

        # Create an entry in `vmail.forwardings` with `address=forwarding`
        conn.insert('forwardings',
                    address=mail,
                    forwarding=mail,
                    domain=domain,
                    dest_domain=domain,
                    is_forwarding=1,
                    active=1)

        log_activity(msg="Create user: %s." % (mail),
                     domain=domain,
                     event='create')
        return (True, )
    except Exception as e:
        return (False, repr(e))
Esempio n. 18
0
    def POST(self, domain, page=1):
        form = web.input(_unicode=False, mail=[])
        page = int(page)
        if page < 1:
            page = 1

        domain = str(domain).lower()

        # Filter users not under the same domain.
        mails = [
            str(v) for v in form.get('mail', [])
            if iredutils.is_email(v) and str(v).endswith('@' + domain)
        ]

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

        redirect_to_admin_list = False
        if 'redirect_to_admin_list' in form:
            redirect_to_admin_list = True

        _wrap = SQLWrap()
        conn = _wrap.conn

        if action == 'delete':
            keep_mailbox_days = form_utils.get_single_value(
                form=form,
                input_name='keep_mailbox_days',
                default_value=0,
                is_integer=True)
            result = sql_lib_user.delete_users(
                conn=conn, accounts=mails, keep_mailbox_days=keep_mailbox_days)
            msg = 'DELETED'
        elif action == 'disable':
            result = sql_lib_utils.set_account_status(conn=conn,
                                                      accounts=mails,
                                                      account_type='user',
                                                      enable_account=False)
            msg = 'DISABLED'
        elif action == 'enable':
            result = sql_lib_utils.set_account_status(conn=conn,
                                                      accounts=mails,
                                                      account_type='user',
                                                      enable_account=True)
            msg = 'ENABLED'
        elif action == 'markasadmin':
            result = sql_lib_user.mark_user_as_admin(conn=conn,
                                                     domain=domain,
                                                     users=mails,
                                                     as_normal_admin=True)
            msg = 'MARKASADMIN'
        elif action == 'unmarkasadmin':
            result = sql_lib_user.mark_user_as_admin(conn=conn,
                                                     domain=domain,
                                                     users=mails,
                                                     as_normal_admin=False)
            msg = 'UNMARKASADMIN'
        #elif action == 'markasglobaladmin':
        #    result = sql_lib_user.mark_user_as_admin(conn=conn,
        #                                             domain=domain,
        #                                             users=mails,
        #                                             as_global_admin=True)
        #    msg = 'MARKASGLOBALADMIN'
        #elif action == 'unmarkasglobaladmin':
        #    result = sql_lib_user.mark_user_as_admin(conn=conn,
        #                                             domain=domain,
        #                                             users=mails,
        #                                             as_global_admin=False)
        #    msg = 'UNMARKASGLOBALADMIN'
        else:
            result = (False, 'INVALID_ACTION')

        if result[0] is True:
            if redirect_to_admin_list:
                raise web.seeother('/api?msg=%s' % (msg))
            else:
                raise web.seeother('/api?msg=%s' % (msg))
        else:
            if redirect_to_admin_list:
                raise web.seeother('/api?msg=%s' % (web.urlquote(result[1])))
            else:
                raise web.seeother('/api?msg=%s' % (web.urlquote(result[1])))