Exemplo n.º 1
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))
Exemplo n.º 2
0
def update_profile(form, mail, profile_type, conn=None):
    mail = web.safestr(mail).lower()
    username = mail.split('@', 1)[0]

    if (not session.get('is_global_admin')) and (session.get('username') !=
                                                 mail):
        # Don't allow to view/update other admins' profile.
        return (False, 'PERMISSION_DENIED')

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

    dn = ldaputils.rdn_value_to_admin_dn(mail)

    mod_attrs = []
    if profile_type == 'general':
        # Get preferredLanguage.
        lang = form_utils.get_language(form)
        mod_attrs += ldaputils.mod_replace('preferredLanguage', lang)

        # Get cn.
        cn = form.get('cn', None)
        mod_attrs += ldaputils.mod_replace(attr='cn',
                                           value=cn,
                                           default=username)

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

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

        # Get account setting
        _qr = ldap_lib_general.get_admin_account_setting(mail=mail,
                                                         profile=None,
                                                         conn=conn)
        if not _qr[0]:
            return _qr

        _as = _qr[1]

        # Update timezone
        tz_name = form_utils.get_timezone(form)

        if tz_name:
            _as['timezone'] = tz_name

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

        if session.get('is_global_admin'):
            # check account status.
            account_status = 'disabled'
            if 'accountStatus' in form:
                account_status = 'active'

            mod_attrs += ldaputils.mod_replace('accountStatus', account_status)

            # Get domainGlobalAdmin.
            if 'domainGlobalAdmin' in form:
                mod_attrs += ldaputils.mod_replace('domainGlobalAdmin', 'yes')
            else:
                mod_attrs += ldaputils.mod_replace('domainGlobalAdmin', None)

        try:
            # Modify profiles.
            conn.modify_s(dn, mod_attrs)

            if session.get('username') == mail and session.get('lang') != lang:
                session['lang'] = lang
        except Exception as e:
            return (False, repr(e))

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

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

        # Change password.
        if session.get('is_global_admin'):
            # Reset password without verify old password.
            cur_passwd = None

        _qr = ldap_lib_general.change_password(dn=dn,
                                               old_password=cur_passwd,
                                               new_password=passwd,
                                               conn=conn)

        if _qr[0]:
            return (True, )
        else:
            return _qr
Exemplo n.º 3
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))
Exemplo n.º 4
0
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))