コード例 #1
0
ファイル: utils.py プロジェクト: tellustheguru/iRedAdmin
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, )
コード例 #2
0
ファイル: domain.py プロジェクト: avinashkarhana/iRedAdmin
def enable_disable_domains(domains, action, conn=None):
    """Set account status.

    :param domains: a list/tuple/set of mail domain names
    :param action: enable, disable
    :param conn: sql connection cursor
    """
    action = action.lower()
    if action in ['enable', 'active']:
        active = 1

    else:
        active = 0

    try:
        conn.update('domain',
                    vars={'domains': domains},
                    where='domain IN $domains',
                    active=active)

        log_activity(event=action.lower(),
                     msg="{} domain(s): {}.".format(action.title(),
                                                    ', '.join(domains)))

        return (True, )
    except Exception as e:
        return (False, repr(e))
コード例 #3
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))
コード例 #4
0
ファイル: admin.py プロジェクト: tellustheguru/iRedAdmin
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))
コード例 #5
0
ファイル: admin.py プロジェクト: tellustheguru/iRedAdmin
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))
コード例 #6
0
ファイル: domain.py プロジェクト: avinashkarhana/iRedAdmin
def add(form, conn=None):
    domain = form_utils.get_domain_name(form)

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

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

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

    params = {
        'domain': domain,
        'transport': settings.default_mta_transport,
        'active': 1,
        'created': iredutils.get_gmttime(),
    }

    # Name
    kv = form_utils.get_form_dict(form=form,
                                  input_name='cn',
                                  key_name='description')
    params.update(kv)

    # Add domain in database.
    try:
        conn.insert('domain', **params)
        log_activity(msg="New domain: %s." % (domain),
                     domain=domain,
                     event='create')

        # If it's a normal domain admin with permission to create new domain,
        # assign current admin as admin of this newly created domain.
        if session.get('create_new_domains'):
            qr = assign_admins_to_domain(domain=domain,
                                         admins=[session.get('username')],
                                         conn=conn)
            if not qr[0]:
                return qr

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

    return (True, )
コード例 #7
0
    def POST(self):
        # Get username, password.
        form = web.input(_unicode=False)

        username = form.get('username', '').strip().lower()
        password = str(form.get('password', '').strip())

        # Auth as domain admin
        _wrap = SQLWrap()
        conn = _wrap.conn

        auth_result = auth.auth(conn=conn,
                                username=username,
                                password=password,
                                account_type='admin')

        if auth_result[0] is True:
            log_activity(msg="Admin login success", event='login')

            # Save selected language
            selected_language = str(form.get('lang', '')).strip()
            if selected_language != web.ctx.lang and \
               selected_language in iredutils.get_language_maps():
                session['lang'] = selected_language

            account_settings = auth_result[1].get('account_settings', {})
            if (not session.get('is_global_admin')
                ) and 'create_new_domains' in account_settings:
                session['create_new_domains'] = True

            for k in [
                    'disable_viewing_mail_log',
                    'disable_managing_quarantined_mails'
            ]:
                if account_settings.get(k) == 'yes':
                    session[k] = True

            if settings.REDIRECT_TO_DOMAIN_LIST_AFTER_LOGIN:
                raise web.seeother('/domains')
            else:
                raise web.seeother('/dashboard?checknew')
        else:
            raise web.seeother('/login?msg=INVALID_CREDENTIALS')
コード例 #8
0
    def POST(self):
        form = web.input(_unicode=False, id=[], ip=[])
        action = form.get('action', 'delete')

        delete_all = False
        if action == 'deleteAll':
            delete_all = True

        qr = fail2banlib.delete_logs(form=form, delete_all=delete_all)
        if qr[0]:
            if not delete_all:
                for i in form.ip:
                    log_activity(msg="Unbanned " + i, event='unban')
                raise web.seeother('/activities/fail2ban?msg=UNBANNED')
            else:
                log_activity(msg="Unbanned All", event='unban')
                raise web.seeother('/activities/fail2ban?msg=UNBANNED_ALL')
        else:
            raise web.seeother('/activities/fail2ban?msg=%s' %
                               web.urlquote(qr[1]))
コード例 #9
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))
コード例 #10
0
def __delete_single_user(mail, keep_mailbox_days=0, conn=None):
    mail = web.safestr(mail)
    if not iredutils.is_email(mail):
        return (False, 'INVALID_MAIL')

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

    # Get dn of mail user and domain.
    dn_user = ldaputils.rdn_value_to_user_dn(mail)

    try:
        keep_mailbox_days = int(keep_mailbox_days)
    except:
        if session.get('is_global_admin'):
            keep_mailbox_days = 0
        else:
            _max_days = max(settings.DAYS_TO_KEEP_REMOVED_MAILBOX)
            if keep_mailbox_days > _max_days:
                # Get the max days
                keep_mailbox_days = _max_days

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

    # Log maildir path in SQL table.
    try:
        qr = get_profile(mail=mail, conn=conn)
        if not qr[0]:
            if qr[1] == 'NO_SUCH_ACCOUNT':
                # If destination user doesn't exist, don't waste time to check
                # other data.
                return (True, )

            return qr

        user_profile = qr[1]['ldif']

        if 'homeDirectory' in user_profile:
            maildir = user_profile.get('homeDirectory', [''])[0]
        else:
            storageBaseDirectory = user_profile.get('storageBaseDirectory',
                                                    [''])[0]
            mailMessageStore = user_profile.get('mailMessageStore', [''])[0]
            maildir = os.path.join(storageBaseDirectory, mailMessageStore)

        if keep_mailbox_days == 0:
            sql_keep_days = None
        else:
            # Convert keep days to string
            _now_in_seconds = time.time()
            _days_in_seconds = _now_in_seconds + (keep_mailbox_days * 24 * 60 *
                                                  60)
            sql_keep_days = time.strftime('%Y-%m-%d',
                                          time.localtime(_days_in_seconds))

        web.conn_iredadmin.insert(
            'deleted_mailboxes',
            maildir=maildir,
            username=mail,
            domain=domain,
            admin=session.get('username'),
            delete_date=sql_keep_days,
        )
    except:
        pass

    # Delete user object.
    try:
        # Delete object and its subtree.
        _qr = ldap_lib_general.delete_ldap_tree(dn=dn_user, conn=conn)
        if not _qr[0]:
            return _qr

        # Delete record from SQL database: real-time used quota.
        try:
            ldap_lib_general.delete_account_used_quota([mail])
        except:
            pass

        # Log delete action.
        log_activity(msg="Delete user: %s." % (mail),
                     domain=domain,
                     event='delete')

        return (True, )
    except ldap.LDAPError as e:
        return (False, repr(e))
コード例 #11
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))
コード例 #12
0
ファイル: domain.py プロジェクト: avinashkarhana/iRedAdmin
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))
コード例 #13
0
ファイル: domain.py プロジェクト: avinashkarhana/iRedAdmin
def delete_domains(domains, keep_mailbox_days=0, conn=None):
    domains = [str(d).lower() for d in domains if iredutils.is_domain(d)]
    if not domains:
        return (True, )

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

    try:
        keep_mailbox_days = abs(int(keep_mailbox_days))
    except:
        keep_mailbox_days = 0

    if not session.get('is_global_admin'):
        _max_days = max(settings.DAYS_TO_KEEP_REMOVED_MAILBOX)
        if keep_mailbox_days > _max_days:
            # Get the max days
            keep_mailbox_days = _max_days

    # Keep mailboxes 'forever', set to 100 years.
    if keep_mailbox_days == 0:
        sql_keep_days = web.sqlliteral('Null')
    else:
        if settings.backend == 'pgsql':
            sql_keep_days = web.sqlliteral(
                """CURRENT_TIMESTAMP + INTERVAL '%d DAYS'""" %
                keep_mailbox_days)
        else:
            # settings.backend == 'mysql'
            sql_keep_days = web.sqlliteral(
                'DATE_ADD(CURDATE(), INTERVAL %d DAY)' % keep_mailbox_days)

    sql_vars = {
        'domains': domains,
        'admin': session.get('username'),
        'sql_keep_days': sql_keep_days
    }

    # Log maildir paths of existing users
    try:
        if settings.backend == 'pgsql':
            sql_raw = '''
                INSERT INTO deleted_mailboxes (username, maildir, domain, admin, delete_date)
                SELECT username, \
                       storagebasedirectory || '/' || storagenode || '/' || maildir, \
                       domain, \
                       $admin, \
                       $sql_keep_days
                  FROM mailbox
                 WHERE domain IN $domains'''
        else:
            # settings.backend == 'mysql'
            sql_raw = '''
                INSERT INTO deleted_mailboxes (username, maildir, domain, admin, delete_date)
                SELECT username, \
                       CONCAT(storagebasedirectory, '/', storagenode, '/', maildir) AS maildir, \
                       domain, \
                       $admin, \
                       $sql_keep_days
                  FROM mailbox
                 WHERE domain IN $domains'''

        conn.query(sql_raw, vars=sql_vars)
    except Exception as e:
        logger.error(e)

    try:
        # Delete domain name
        for tbl in [
                'domain', 'alias', 'domain_admins', 'mailbox',
                'recipient_bcc_domain', 'recipient_bcc_user',
                'sender_bcc_domain', 'sender_bcc_user', 'forwardings',
                'moderators', settings.SQL_TBL_USED_QUOTA
        ]:
            conn.delete(tbl, vars=sql_vars, where='domain IN $domains')

        # Delete alias domain
        conn.delete(
            'alias_domain',
            vars=sql_vars,
            where='alias_domain IN $domains OR target_domain IN $domains')

        # Delete domain admins
        for d in domains:
            conn.delete('domain_admins',
                        vars={'domain': '%%@' + d},
                        where='username LIKE $domain')
    except Exception as e:
        return (False, repr(e))

    for d in domains:
        log_activity(event='delete', domain=d, msg="Delete domain: %s." % d)

    return (True, )
コード例 #14
0
ファイル: user.py プロジェクト: tellustheguru/iRedAdmin
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))
コード例 #15
0
ファイル: basic.py プロジェクト: avinashkarhana/iRedAdmin
    def POST(self):
        form = web.input(_unicode=False)
        is_api_login = False
        api_key = False
        username = False
        password = False
        login_type = 'admin'

        # check if API login
        try:
            if form.get('key', '').strip() != "" and form.get(
                    'key', '').strip() != None:
                is_api_login = True
                api_key = str(form.get('key', '').strip()).lower()
                api_key = ''.join(e for e in api_key if e.isalnum())
            else:
                is_api_login = False
        except AttributeError:
            raise web.seeother('/api?msg=Something_Went_Wrong_E:AuthAPIChk')

        # check type of user login
        try:
            if form.get('login_type', '').strip() != "" and form.get(
                    'login_type', '').strip() != None:
                login_type = str(form.get('login_type', '').strip()).lower()
                login_type = ''.join(e for e in login_type if e.isalnum())
        except AttributeError:
            raise web.seeother('/login?msg=Try Again!')

        # Get username, password. if not API login
        if not is_api_login:
            username = form.get('username', '').strip().lower()
            password = str(form.get('password', '').strip())

        _wrap = SQLWrap()
        conn = _wrap.conn
        # Authenticate
        auth_result = auth.auth(conn=conn,
                                username=username,
                                password=password,
                                is_api_login=is_api_login,
                                api_key=api_key,
                                account_type=login_type)

        # if Authenticated
        if auth_result[0] is True:
            # Log Activity with correct user type
            if login_type == "admin":
                # Admin loggedin
                log_activity(msg="Admin login success", event='login')
            else:
                # user loggedin
                log_activity(msg="User login success", event='user_login')

            # Save user's selected language and set into session
            selected_language = str(form.get('lang', '')).strip()
            if selected_language != web.ctx.lang and \
               selected_language in iredutils.get_language_maps():
                session['lang'] = selected_language

            # set create_new_domain in session if allowed in users settings
            account_settings = auth_result[1].get('account_settings', {})
            if (not session.get('is_global_admin')
                ) and 'create_new_domains' in account_settings:
                session['create_new_domains'] = True

            # set sessions for disable_viewing_mail_log and disable_managing_quarantined_mails if defined in user settings
            for k in [
                    'disable_viewing_mail_log',
                    'disable_managing_quarantined_mails'
            ]:
                if account_settings.get(k) == 'yes':
                    session[k] = True

            # redirect user to /domains if defined in user settings and not API Login, else redirect to dashboard on normal login and push LOGIN_SUCCESSFUL message on API login
            if settings.REDIRECT_TO_DOMAIN_LIST_AFTER_LOGIN and (
                    not is_api_login):
                raise web.seeother('/domains')
            else:
                if not is_api_login:
                    raise web.seeother('/dashboard?checknew')
                else:
                    raise web.seeother('/api?msg=LOGIN_SUCCESSFUL')

        # if not Authenticated Push Invalid Credentials message
        else:
            if not is_api_login:
                raise web.seeother('/login?msg=INVALID_CREDENTIALS')
            else:
                raise web.seeother('/api?msg=INVALID_CREDENTIALS')
コード例 #16
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))
コード例 #17
0
ファイル: basic.py プロジェクト: tellustheguru/iRedAdmin
    def POST(self):
        # Get username, password.
        form = web.input(_unicode=False)

        username = web.safestr(form.get('username', '').strip()).lower()
        password = form.get('password', '').strip()

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

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

        domain = username.split('@', 1)[-1]

        _wrap = LDAPWrap()
        conn = _wrap.conn

        # Check whether it's a mail user with admin privilege.
        qr_user_auth = auth.login_auth(username=username,
                                       password=password,
                                       account_type='user',
                                       conn=conn)

        qr_admin_auth = (False, 'INVALID_CREDENTIALS')
        if not qr_user_auth[0]:
            # Verify admin account under 'o=domainAdmins'.
            qr_admin_auth = auth.login_auth(username=username,
                                            password=password,
                                            account_type='admin',
                                            conn=conn)

            if not qr_admin_auth[0]:
                session['failed_times'] += 1
                logger.warning(
                    "Web login failed: client_address={}, username={}".format(
                        web.ctx.ip, username))
                log_activity(msg="Login failed.",
                             admin=username,
                             event='login',
                             loglevel='error')
                raise web.seeother('/login?msg=INVALID_CREDENTIALS')

        session['username'] = username

        web.config.session_parameters['cookie_name'] = 'iRedAdmin'
        web.config.session_parameters['ignore_expiry'] = False
        web.config.session_parameters[
            'ignore_change_ip'] = settings.SESSION_IGNORE_CHANGE_IP

        _attrs = ['preferredLanguage', 'accountSetting', 'disabledService']
        # Read preferred language from LDAP
        if qr_admin_auth[0]:
            logger.info(
                "Admin login success: username={}, client_address={}".format(
                    username, web.ctx.ip))
            log_activity(msg="Admin login success", event='login')

            if not session.get('timezone'):
                # no per-admin time zone set in `login_auth()`
                timezone = settings.LOCAL_TIMEZONE
                session['timezone'] = timezone

        if qr_user_auth[0]:
            logger.info(
                "Admin login success: username={}, client_address={}".format(
                    username, web.ctx.ip))
            log_activity(msg="Admin login success",
                         admin=username,
                         event='login')

            qr_user_profile = ldap_lib_user.get_profile(mail=username,
                                                        attributes=_attrs,
                                                        conn=conn)
            if qr_user_profile[0]:
                # Time zone
                if not session.get('timezone'):
                    # no per-user time zone set in `login_auth()`
                    timezone = settings.LOCAL_TIMEZONE

                    # Get per-domain time zone
                    qr = ldap_lib_general.get_domain_account_setting(
                        domain=domain, conn=conn)
                    if qr[0]:
                        _das = qr[1]
                        tz_name = _das.get('timezone')
                        if tz_name in TIMEZONES:
                            timezone = TIMEZONES[tz_name]

                    session['timezone'] = timezone

        # Save selected language
        selected_language = str(form.get('lang', '')).strip()
        if selected_language != web.ctx.lang and \
           selected_language in iredutils.get_language_maps():
            session['lang'] = selected_language

        # Save 'logged' at the end, if above settings are failed, it won't
        # redirect to other page and loop forever.
        session["logged"] = True

        if settings.REDIRECT_TO_DOMAIN_LIST_AFTER_LOGIN:
            raise web.seeother('/domains')
        else:
            raise web.seeother('/dashboard?checknew')
コード例 #18
0
ファイル: user.py プロジェクト: tellustheguru/iRedAdmin
def delete_users(accounts, keep_mailbox_days=0, conn=None):
    accounts = [str(v) for v in accounts if iredutils.is_email(v)]

    if not accounts:
        return (True, )

    # Keep mailboxes 'forever', set to 100 years.
    try:
        keep_mailbox_days = abs(int(keep_mailbox_days))
    except:
        if session.get('is_global_admin'):
            keep_mailbox_days = 0
        else:
            _max_days = max(settings.DAYS_TO_KEEP_REMOVED_MAILBOX)
            if keep_mailbox_days > _max_days:
                # Get the max days
                keep_mailbox_days = _max_days

    if keep_mailbox_days == 0:
        sql_keep_days = web.sqlliteral('Null')
    else:
        if settings.backend == 'mysql':
            sql_keep_days = web.sqlliteral(
                'DATE_ADD(CURDATE(), INTERVAL %d DAY)' % keep_mailbox_days)
        elif settings.backend == 'pgsql':
            sql_keep_days = web.sqlliteral(
                """CURRENT_TIMESTAMP + INTERVAL '%d DAYS'""" %
                keep_mailbox_days)

    sql_vars = {
        'accounts': accounts,
        'admin': session.get('username'),
        'sql_keep_days': sql_keep_days
    }

    # Log maildir path of deleted users.
    if settings.backend == 'mysql':
        sql_raw = '''
            INSERT INTO deleted_mailboxes (username, maildir, domain, admin, delete_date)
            SELECT username, \
                   CONCAT(storagebasedirectory, '/', storagenode, '/', maildir) AS maildir, \
                   SUBSTRING_INDEX(username, '@', -1), \
                   $admin, \
                   $sql_keep_days
              FROM mailbox
             WHERE username IN $accounts'''
    elif settings.backend == 'pgsql':
        sql_raw = '''
            INSERT INTO deleted_mailboxes (username, maildir, domain, admin, delete_date)
            SELECT username, \
                   storagebasedirectory || '/' || storagenode || '/' || maildir, \
                   SPLIT_PART(username, '@', 2), \
                   $admin, \
                   $sql_keep_days
              FROM mailbox
             WHERE username IN $accounts'''

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

        conn.query(sql_raw, vars=sql_vars)
    except:
        pass

    try:
        for tbl in [
                'mailbox', 'domain_admins', 'recipient_bcc_user',
                'sender_bcc_user', settings.SQL_TBL_USED_QUOTA
        ]:
            conn.delete(tbl, vars=sql_vars, where='username IN $accounts')

        # remove destination bcc addresses.
        for tbl in [
                'recipient_bcc_user', 'sender_bcc_user',
                'recipient_bcc_domain', 'sender_bcc_domain'
        ]:
            conn.delete(tbl, vars=sql_vars, where='bcc_address IN $accounts')

        # Remove user from `forwardings`, including:
        #   - per-user mail forwardings
        #   - per-domain catch-all account
        #   - alias membership
        #   - alias moderators
        conn.delete('forwardings',
                    vars=sql_vars,
                    where='address IN $accounts OR forwarding IN $accounts')

        # remove destination moderators.
        conn.delete('moderators',
                    vars=sql_vars,
                    where='moderator IN $accounts')
    except Exception as e:
        return (False, repr(e))

    log_activity(event='delete',
                 domain=accounts[0].split('@', 1)[-1],
                 msg="Delete user: %s." % ', '.join(accounts))

    return (True, )
コード例 #19
0
ファイル: user.py プロジェクト: tellustheguru/iRedAdmin
def update(conn, mail, profile_type, form):
    profile_type = web.safestr(profile_type)
    mail = str(mail).lower()
    domain = mail.split('@', 1)[-1]

    qr = sql_lib_domain.simple_profile(conn=conn,
                                       domain=domain,
                                       columns=['maxquota', 'settings'])
    if not qr[0]:
        return qr

    domain_profile = qr[1]
    del qr

    domain_settings = sqlutils.account_settings_string_to_dict(
        domain_profile.get('settings', ''))

    disabled_user_profiles = domain_settings.get('disabled_user_profiles', [])
    if not session.get('is_global_admin'):
        if profile_type in disabled_user_profiles:
            return (False, 'PERMISSION_DENIED')

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

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

        # Get preferred language: short lang code. e.g. en_US, de_DE.
        preferred_language = form_utils.get_language(form)
        if preferred_language in iredutils.get_language_maps():
            updates['language'] = preferred_language
        else:
            updates['language'] = ''

        tz_name = form_utils.get_timezone(form)
        if tz_name:
            sql_lib_general.update_user_settings(
                conn=conn, mail=mail, new_settings={'timezone': tz_name})

            if session['username'] == mail:
                session['timezone'] = TIMEZONES[tz_name]
        else:
            sql_lib_general.update_user_settings(conn=conn,
                                                 mail=mail,
                                                 removed_settings=['timezone'])

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

        # check account status
        updates['active'] = 0
        if 'accountStatus' in form:
            updates['active'] = 1

        # Update account status in table `alias` immediately
        try:
            conn.update('forwardings',
                        vars={'address': mail},
                        where='address=$address OR forwarding=$address',
                        active=updates['active'])
        except:
            pass

        # Get mail quota size.
        mailQuota = str(form.get('mailQuota'))
        if mailQuota.isdigit():
            mailQuota = int(mailQuota)
        else:
            mailQuota = 0

        updates['quota'] = mailQuota
        updates['employeeid'] = form.get('employeeNumber', '')

    elif profile_type == 'password':
        newpw = web.safestr(form.get('newpw', ''))
        confirmpw = web.safestr(form.get('confirmpw', ''))

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

        # Verify new passwords.
        qr = iredpwd.verify_new_password(newpw=newpw,
                                         confirmpw=confirmpw,
                                         min_passwd_length=min_passwd_length,
                                         max_passwd_length=max_passwd_length)
        if qr[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[1], pwscheme=pwscheme)
        else:
            return qr

        # Hash/encrypt new password.
        updates['password'] = passwd
        updates['passwordlastchange'] = iredutils.get_gmttime()

        # Store plain password in another attribute.
        if settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR:
            updates[settings.STORE_PLAIN_PASSWORD_IN_ADDITIONAL_ATTR] = newpw
    else:
        return (True, )

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

        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))
コード例 #20
0
    def POST(self, generate=False):
        form = web.input(_unicode=False, id=[], key=[])
        action = form.get('action', 'delete')
        delete_all = False
        _wrap = SQLWrap()
        conn = _wrap.conn
        # initailize query result variable
        qr = ()
        api_key = ""

        if action in ['deleteAll', 'delete'] and not generate:
            if action == "deleteAll":
                delete_all = True

            if delete_all:
                try:
                    last_update_timestamp = str(
                        str(datetime.datetime.now()).split(".")[0])
                    conn.update('api',
                                where="",
                                is_enabled=0,
                                last_update_timestamp=last_update_timestamp)
                    qr = (True, )
                except Exception as e:
                    qr = (False, repr(e))
            else:
                ids = form.get('id', [])

                if ids:
                    last_update_timestamp = str(
                        str(datetime.datetime.now()).split(".")[0])
                    try:
                        conn.update(
                            'api',
                            where="kid IN %s" % web.db.sqlquote(ids),
                            is_enabled=0,
                            last_updated_by=session.get('username'),
                            last_update_timestamp=last_update_timestamp)
                        qr = (True, )
                    except Exception as e:
                        qr = (False, repr(e))
                else:
                    qr = (False, "No API Keys Selected!")

        elif action == "generate" and generate:
            alphabet = string.ascii_letters + string.digits
            api_key = ''.join(secrets.choice(alphabet) for i in range(256))
            exp_date = str(form.get("expiry", "")).strip()
            is_enabled = form.get("is_enabled", "")
            isglobaladminapi = form.get("isglobaladminapi", "")
            generated_by = session.get("username")

            # input validation checks
            if len(api_key) != 256: api_key = ""
            if str(is_enabled).strip() not in ["0", "1"]: is_enabled = ""
            if str(isglobaladminapi).strip() not in ["0", "1"]:
                isglobaladminapi = ""
            api_description = ""
            try:
                api_description = form.get("api_description", "")
                api_description = api_description.replace(chr(10), " ").strip()
                api_description = api_description.replace(chr(13), " ").strip()
                api_description = re.sub(' +', ' ', api_description).strip()
                api_description = urllib.parse.quote(api_description, safe='')
            except:
                api_description = ""
            last_update_timestamp = str(
                str(datetime.datetime.now()).split(".")[0])
            if len(api_description) > 256:
                api_description = api_description[:256]

            if generated_by is None: generated_by = ""
            try:
                datetime.datetime.strptime(exp_date, '%Y-%m-%d %H:%M:%S')
            except:
                exp_date = ""

            if api_key != "" and exp_date != "" and is_enabled != "" and isglobaladminapi != "" and generated_by != "":
                try:
                    conn.insert(
                        'api',
                        api_description=api_description,
                        api_key=api_key,
                        expiry_date_time=exp_date,
                        is_enabled=is_enabled,
                        isglobaladminapi=isglobaladminapi,
                        generated_by=generated_by,
                        last_update_timestamp=last_update_timestamp,
                    )
                    qr = (True, )
                except Exception as e:
                    qr = (False, repr(e))
            else:
                qr = (False, "Missing or incorrect parameters")

        elif action == "update":
            updation = {}
            form_ids = form.get('id', [])
            for i in form_ids:
                updation[i] = {}
                api_description = ""
                try:
                    api_description = form.get(i + "_api_description", "")
                    api_description = api_description.replace(chr(10),
                                                              " ").strip()
                    api_description = api_description.replace(chr(13),
                                                              " ").strip()
                    api_description = re.sub(' +', ' ',
                                             api_description).strip()
                    api_description = urllib.parse.quote(api_description,
                                                         safe='')
                    if len(api_description) > 256:
                        api_description = api_description[:256]
                except:
                    api_description = ""
                try:
                    enb = form.get(i + '_is_enabled', None)
                    isglbl = form.get(i + '_isglobaladminapi', None)
                    updation[i] = {
                        "is_enabled": enb,
                        "isglobaladminapi": isglbl
                    }
                except:
                    pass

                if updation[i].get('is_enabled') != None and updation[i].get(
                        'is_enabled') != "" and updation[i].get(
                            'isglobaladminapi') != None and updation[i].get(
                                'isglobaladminapi') != "":
                    try:
                        enbld = int(updation[i].get('is_enabled'))
                        glbladmnapi = int(updation[i].get('isglobaladminapi'))
                    except:
                        pass
                    if (enbld in [0, 1]) and (glbladmnapi in [0, 1]):
                        last_update_timestamp = str(
                            str(datetime.datetime.now()).split(".")[0])
                        try:
                            if api_description == "":
                                conn.update(
                                    'api',
                                    where="kid = %s" % web.db.sqlquote(i),
                                    is_enabled=enbld,
                                    isglobaladminapi=glbladmnapi,
                                    last_updated_by=session.get('username'),
                                    last_update_timestamp=last_update_timestamp
                                )
                            else:
                                conn.update(
                                    'api',
                                    where="kid = %s" % web.db.sqlquote(i),
                                    is_enabled=enbld,
                                    isglobaladminapi=glbladmnapi,
                                    last_updated_by=session.get('username'),
                                    last_update_timestamp=last_update_timestamp,
                                    api_description=api_description)
                        except Exception as e:
                            qr = (False, repr(e))

            updation = {}
            del updation
            qr = (True, )

        else:
            raise web.seeother('/apis?msg=INVALID_ACTION')

        if qr[0]:
            if action in ['deleteAll', 'delete']:
                if not delete_all:
                    for i in form.key:
                        log_activity(msg="Disabled API Key " + i,
                                     event='disable_api_key')
                    raise web.seeother('/apis?msg=DISABLED_API_KEY')
                else:
                    log_activity(msg="Disabled all API Keys",
                                 event='disable_api_key')
                    raise web.seeother('/apis?msg=DISABLED_API_KEY_ALL')
            elif action == "generate":
                log_activity(msg="GENERATED API Key " + api_key,
                             event='generated_api_key')
                raise web.seeother('/apis?msg=GENERATED_API_KEY_' + api_key)
            elif action == "update":
                idsl = list(form.get('id', []))
                idsl = ", ".join(map(str, idsl))
                log_activity(msg="Updated API Keys with ids: " + idsl,
                             event='updated_api_key')
                raise web.seeother('/apis?msg=UPDATED_API_KEY')
            else:
                raise web.seeother('/apis?msg=INVALID_ACTION')
        else:
            raise web.seeother('/apis?msg=%s' % web.urlquote(qr[1]))
コード例 #21
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))