示例#1
0
    def GET(self):
        form = web.input(_unicode=False)
        is_api_login = False

        # check if trying API Login with GET Method
        try:
            if form.get('key', '').strip() != "" and form.get(
                    'key', '').strip() != None:
                is_api_login = True
                api_key = str(form.get('key', '').strip())
            else:
                is_api_login = False
        except AttributeError:
            raise web.seeother('/api?msg=Something_Went_Wrong_E:AuthAPIChk')
        # return if trying API Login with GET Method
        if is_api_login:
            raise web.seeother(
                '/api?msg=Login_with_API_KEY_must_be_via_POST_method')

        if not session.get('logged'):
            form = web.input(_unicode=False)

            if not iredutils.is_allowed_admin_login_ip(client_ip=web.ctx.ip):
                return web.render('error_without_login.html',
                                  error='NOT_ALLOWED_IP')

            # Show login page.
            return web.render('login.html',
                              languagemaps=iredutils.get_language_maps(),
                              msg=form.get('msg'))
        else:
            if settings.REDIRECT_TO_DOMAIN_LIST_AFTER_LOGIN:
                raise web.seeother('/domains')
            else:
                raise web.seeother('/dashboard')
示例#2
0
    def GET(self):
        form = web.input()

        return web.render('sql/domain/create.html',
                          preferred_language=settings.default_language,
                          languagemaps=iredutils.get_language_maps(),
                          timezones=TIMEZONES,
                          msg=form.get('msg'))
示例#3
0
 def GET(self):
     form = web.input()
     return web.render('sql/admin/create.html',
                       languagemaps=iredutils.get_language_maps(),
                       default_language=settings.default_language,
                       min_passwd_length=settings.min_passwd_length,
                       max_passwd_length=settings.max_passwd_length,
                       password_policies=iredutils.get_password_policies(),
                       msg=form.get('msg'))
示例#4
0
    def GET(self):
        form = web.input()
        domain = form_utils.get_domain_name(form=form)

        return web.render('ldap/domain/create.html',
                          preferred_language=settings.default_language,
                          languagemaps=iredutils.get_language_maps(),
                          timezones=TIMEZONES,
                          domainName=domain,
                          msg=form.get('msg'))
示例#5
0
    def GET(self, domain):
        domain = str(domain).lower()

        form = web.input()

        # Get all managed domains.
        _wrap = SQLWrap()
        conn = _wrap.conn

        if session.get('is_global_admin'):
            qr = sql_lib_domain.get_all_domains(conn=conn, name_only=True)
        else:
            qr = sql_lib_admin.get_managed_domains(
                conn=conn,
                admin=session.get('username'),
                domain_name_only=True)

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

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

        if qr_profile[0] is True:
            domain_profile = qr_profile[1]
            domain_settings = sqlutils.account_settings_string_to_dict(
                domain_profile['settings'])
        else:
            raise web.seeother('/domains?msg=%s' % web.urlquote(qr_profile[1]))

        # Cet total number and allocated quota size of existing users under domain.
        num_users_under_domain = sql_lib_general.num_users_under_domain(
            domain=domain, conn=conn)

        min_passwd_length = domain_settings.get('min_passwd_length',
                                                settings.min_passwd_length)
        max_passwd_length = domain_settings.get('max_passwd_length',
                                                settings.max_passwd_length)

        return web.render(
            'sql/user/create.html',
            cur_domain=domain,
            allDomains=all_domains,
            profile=domain_profile,
            domain_settings=domain_settings,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length,
            store_password_in_plain_text=settings.STORE_PASSWORD_IN_PLAIN_TEXT,
            num_existing_users=num_users_under_domain,
            languagemaps=iredutils.get_language_maps(),
            password_policies=iredutils.get_password_policies(),
            msg=form.get('msg'),
        )
示例#6
0
def ldif_mailadmin(mail,
                   passwd,
                   cn,
                   account_status=None,
                   preferred_language=None,
                   account_setting=None,
                   disabled_services=None):
    """Generate LDIF used to create a standalone domain admin account.

    :param mail: full email address. The mail domain cannot be one of locally
                 hosted domain.
    :param passwd: hashed password string
    :param cn: the display name of this admin
    :param account_status: account status (active, disabled)
    :param preferred_language: short code of preferred language. e.g. en_US.
    :param is_global_admin: mark this admin as a global admin (yes, no)
    :param account_setting: a dict of per-account settings.
    :param disabled_services: a list/tupe/set of disabled services.
    """
    mail = web.safestr(mail).lower()

    if account_status not in ['active', 'disabled']:
        account_status = 'disabled'

    ldif = ldaputils.attrs_ldif({
        'objectClass':
        'mailAdmin',
        'mail':
        mail,
        'userPassword':
        passwd,
        'accountStatus':
        account_status,
        'domainGlobalAdmin':
        'yes',
        'shadowLastChange':
        ldaputils.get_days_of_shadow_last_change(),
        'cn':
        cn,
        'disabledService':
        disabled_services,
    })

    if preferred_language:
        if preferred_language in iredutils.get_language_maps():
            ldif += ldaputils.attr_ldif("preferredLanguage",
                                        preferred_language)

    if account_setting and isinstance(account_setting, dict):
        _as = ldaputils.account_setting_dict_to_list(account_setting)
        ldif += ldaputils.attr_ldif("accountSetting", _as)

    return ldif
示例#7
0
    def GET(self, profile_type, domain):
        form = web.input()
        domain = web.safestr(domain).lower()

        _wrap = LDAPWrap()
        conn = _wrap.conn

        qr = ldap_lib_domain.get_profile(domain=domain, conn=conn)

        if not qr[0]:
            raise web.seeother('/domains?msg=' + web.urlquote(qr[1]))

        domain_profile = qr[1]['ldif']

        r = ldap_lib_domain.list_accounts(attributes=['domainName'], conn=conn)
        if r[0] is True:
            all_domains = r[1]
        else:
            return r

        domain_account_settings = ldaputils.get_account_setting_from_profile(
            domain_profile)

        (min_passwd_length,
         max_passwd_length) = ldap_lib_general.get_domain_password_lengths(
             domain=domain,
             account_settings=domain_account_settings,
             fallback_to_global_settings=False)

        # Get settings from db.
        _settings = iredutils.get_settings_from_db(
            params=['min_passwd_length', 'max_passwd_length'])
        global_min_passwd_length = _settings['min_passwd_length']
        global_max_passwd_length = _settings['max_passwd_length']

        return web.render(
            'ldap/domain/profile.html',
            cur_domain=domain,
            allDomains=all_domains,
            domain_account_settings=domain_account_settings,
            profile=domain_profile,
            profile_type=profile_type,
            global_min_passwd_length=global_min_passwd_length,
            global_max_passwd_length=global_max_passwd_length,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length,
            timezones=TIMEZONES,
            default_mta_transport=settings.default_mta_transport,
            languagemaps=iredutils.get_language_maps(),
            msg=form.get('msg', None),
        )
示例#8
0
    def GET(self):
        if not session.get('logged'):
            form = web.input(_unicode=False)

            if not iredutils.is_allowed_admin_login_ip(client_ip=web.ctx.ip):
                return web.render('error_without_login.html',
                                  error='NOT_ALLOWED_IP')

            # Show login page.
            return web.render('login.html',
                              languagemaps=iredutils.get_language_maps(),
                              msg=form.get('msg'))
        else:
            if settings.REDIRECT_TO_DOMAIN_LIST_AFTER_LOGIN:
                raise web.seeother('/domains')
            else:
                raise web.seeother('/dashboard')
示例#9
0
    def GET(self):
        form = web.input()

        db_settings = iredutils.get_settings_from_db()
        min_passwd_length = db_settings['min_passwd_length']
        max_passwd_length = db_settings['max_passwd_length']

        password_policies = iredutils.get_password_policies(
            db_settings=db_settings)

        return web.render('ldap/admin/create.html',
                          languagemaps=iredutils.get_language_maps(),
                          default_language=settings.default_language,
                          min_passwd_length=min_passwd_length,
                          max_passwd_length=max_passwd_length,
                          password_policies=password_policies,
                          msg=form.get('msg'))
示例#10
0
    def GET(self, domain):
        domain = str(domain).lower()
        form = web.input()

        _wrap = LDAPWrap()
        conn = _wrap.conn

        _attrs = ['domainName', 'accountSetting', 'domainCurrentQuotaSize']
        result = ldap_lib_domain.list_accounts(attributes=_attrs, conn=conn)
        if result[0] is True:
            allDomains = result[1]

            # Get accountSetting of current domain.
            allAccountSettings = ldaputils.get_account_settings_from_qr(
                allDomains)
            domainAccountSetting = allAccountSettings.get(domain, {})

            defaultUserQuota = ldap_lib_domain.get_default_user_quota(
                domain=domain, domain_account_setting=domainAccountSetting)
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))

        # Get number of account limit.
        numberOfCurrentAccounts = ldap_lib_general.num_users_under_domain(
            domain=domain, conn=conn)

        (min_passwd_length,
         max_passwd_length) = ldap_lib_general.get_domain_password_lengths(
             domain=domain,
             account_settings=domainAccountSetting,
             fallback_to_global_settings=True,
         )

        return web.render(
            'ldap/user/create.html',
            cur_domain=domain,
            allDomains=allDomains,
            defaultUserQuota=defaultUserQuota,
            domainAccountSetting=domainAccountSetting,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length,
            store_password_in_plain_text=settings.STORE_PASSWORD_IN_PLAIN_TEXT,
            password_policies=iredutils.get_password_policies(),
            numberOfCurrentAccounts=numberOfCurrentAccounts,
            languagemaps=iredutils.get_language_maps(),
            msg=form.get('msg'))
示例#11
0
    def GET(self, profile_type, domain):
        form = web.input()
        domain = web.safestr(domain.split('/', 1)[0])
        profile_type = web.safestr(profile_type)

        #check if admin asking for details of correct domain
        admins_of_domain = sql_lib_domain.get_domain_admin_addresses(
            domain=domain)[1]
        if session.get('username') not in admins_of_domain and not session.get(
                'is_global_admin'):
            raise web.seeother(
                '/domains?msg=PERMISSION_DENIED_TRYING_TO_ACCESS_OUT_OF_BOUND_DOMAIN'
            )

        _wrap = SQLWrap()
        conn = _wrap.conn

        result = sql_lib_domain.profile(conn=conn, domain=domain)

        if result[0] is not True:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))

        domain_profile = result[1]

        # Get settings from db.
        _settings = iredutils.get_settings_from_db(
            params=['min_passwd_length', 'max_passwd_length'])
        global_min_passwd_length = _settings['min_passwd_length']
        global_max_passwd_length = _settings['max_passwd_length']

        return web.render(
            'sql/domain/profile.html',
            cur_domain=domain,
            profile_type=profile_type,
            profile=domain_profile,
            default_mta_transport=settings.default_mta_transport,
            domain_settings=sqlutils.account_settings_string_to_dict(
                domain_profile['settings']),
            global_min_passwd_length=global_min_passwd_length,
            global_max_passwd_length=global_max_passwd_length,
            timezones=TIMEZONES,
            # Language
            languagemaps=iredutils.get_language_maps(),
            msg=form.get('msg'),
        )
示例#12
0
    def GET(self):
        form = web.input()
        _wrap = SQLWrap()
        conn = _wrap.conn

        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 = []
        return web.render('sql/admin/create.html',
                          languagemaps=iredutils.get_language_maps(),
                          domains=all_domains,
                          default_language=settings.default_language,
                          min_passwd_length=settings.min_passwd_length,
                          max_passwd_length=settings.max_passwd_length,
                          password_policies=iredutils.get_password_policies(),
                          msg=form.get('msg'))
示例#13
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')
示例#14
0
    def GET(self, profile_type, domain):
        form = web.input()
        domain = web.safestr(domain.split('/', 1)[0])
        profile_type = web.safestr(profile_type)

        _wrap = SQLWrap()
        conn = _wrap.conn

        result = sql_lib_domain.profile(conn=conn, domain=domain)

        if result[0] is not True:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))

        domain_profile = result[1]

        # Get settings from db.
        _settings = iredutils.get_settings_from_db(
            params=['min_passwd_length', 'max_passwd_length'])
        global_min_passwd_length = _settings['min_passwd_length']
        global_max_passwd_length = _settings['max_passwd_length']

        return web.render(
            'sql/domain/profile.html',
            cur_domain=domain,
            profile_type=profile_type,
            profile=domain_profile,
            default_mta_transport=settings.default_mta_transport,
            domain_settings=sqlutils.account_settings_string_to_dict(
                domain_profile['settings']),
            global_min_passwd_length=global_min_passwd_length,
            global_max_passwd_length=global_max_passwd_length,
            timezones=TIMEZONES,
            # Language
            languagemaps=iredutils.get_language_maps(),
            msg=form.get('msg'),
        )
示例#15
0
    def GET(self, profile_type, mail):
        mail = str(mail).lower()
        form = web.input()

        if not (session.get('is_global_admin')
                or session.get('username') == mail):
            # Don't allow to view/update others' profile.
            raise web.seeother(
                '/profile/admin/general/%s?msg=PERMISSION_DENIED' %
                session.get('username'))

        _wrap = SQLWrap()
        conn = _wrap.conn

        is_global_admin = sql_lib_general.is_global_admin(admin=mail,
                                                          conn=conn)
        result = sql_lib_admin.get_profile(mail=mail, conn=conn)

        if result[0] is True:
            profile = result[1]
            qr = sql_lib_general.get_admin_settings(admin=mail, conn=conn)
            if qr[0]:
                admin_settings = qr[1]
            else:
                return qr

            # Get all domains.
            all_domains = []

            qr_all_domains = sql_lib_domain.get_all_domains(conn=conn)
            if qr_all_domains[0] is True:
                all_domains = qr_all_domains[1]

            # Get managed domains.
            managed_domains = []

            qr = sql_lib_admin.get_managed_domains(conn=conn,
                                                   admin=mail,
                                                   domain_name_only=True,
                                                   listed_only=True)
            if qr[0] is True:
                managed_domains += qr[1]

            return web.render(
                'sql/admin/profile.html',
                mail=mail,
                profile_type=profile_type,
                is_global_admin=is_global_admin,
                profile=profile,
                admin_settings=admin_settings,
                languagemaps=iredutils.get_language_maps(),
                allDomains=all_domains,
                managedDomains=managed_domains,
                min_passwd_length=settings.min_passwd_length,
                max_passwd_length=settings.max_passwd_length,
                store_password_in_plain_text=settings.
                STORE_PASSWORD_IN_PLAIN_TEXT,
                password_policies=iredutils.get_password_policies(),
                msg=form.get('msg'),
            )
        else:
            # Return to user profile page if admin is a mail user.
            qr = sql_lib_user.simple_profile(conn=conn,
                                             mail=mail,
                                             columns=['username'])

            if qr[0]:
                raise web.seeother('/profile/user/general/' + mail)
            else:
                raise web.seeother('/admins?msg=' + web.urlquote(result[1]))
示例#16
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))
示例#17
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))
示例#18
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))
示例#19
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))
示例#20
0
    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')
示例#21
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))
示例#22
0
    def GET(self, mail):
        mail = str(mail).lower()
        domain = mail.split('@', 1)[-1]

        _wrap = SQLWrap()
        conn = _wrap.conn

        form = web.input()
        msg = form.get('msg', '')
        used_quota = {}

        qr = sql_lib_user.profile(mail=mail, conn=conn)
        if qr[0]:
            user_profile = qr[1]
        else:
            raise web.seeother('/api?msg={}'.format(web.urlquote(qr[1])))
        del qr

        # Get per-user settings
        user_settings = {}
        qr = sql_lib_general.get_user_settings(
            conn=conn, mail=mail, existing_settings=user_profile['settings'])
        if qr[0]:
            user_settings = qr[1]
        del qr

        # Get used quota.
        if settings.SHOW_USED_QUOTA:
            used_quota = sql_lib_general.get_account_used_quota(
                accounts=[mail], conn=conn)

        # Get per-domain disabled user profiles.
        qr = sql_lib_domain.simple_profile(conn=conn,
                                           domain=domain,
                                           columns=['settings'])

        if qr[0]:
            domain_profile = qr[1]
            domain_settings = sqlutils.account_settings_string_to_dict(
                domain_profile['settings'])

            min_passwd_length = domain_settings.get('min_passwd_length',
                                                    settings.min_passwd_length)
            max_passwd_length = domain_settings.get('max_passwd_length',
                                                    settings.max_passwd_length)

        return web.render('api/msg/msg.html',
                          content_type="application/json",
                          msg={
                              "cur_domain":
                              domain,
                              "mail":
                              mail,
                              "profile":
                              user_profile,
                              "timezones":
                              TIMEZONES,
                              "min_passwd_length":
                              min_passwd_length,
                              "max_passwd_length":
                              max_passwd_length,
                              "store_password_in_plain_text":
                              settings.STORE_PASSWORD_IN_PLAIN_TEXT,
                              "password_policies":
                              iredutils.get_password_policies(),
                              "user_settings":
                              user_settings,
                              "used_quota":
                              used_quota,
                              "languagemaps":
                              iredutils.get_language_maps(),
                              "msg":
                              msg,
                          })
示例#23
0
    def GET(self, profile_type, mail):
        mail = str(mail).lower()
        domain = mail.split('@', 1)[-1]

        if not session.get('is_global_admin') and not session.get('is_admin'):
            mail = session.get("username")

        if session.get('is_admin'):
            #check if admin asking for details of correct domain
            admins_of_domain = sql_lib_domain.get_domain_admin_addresses(
                domain=domain)[1]
            if session.get(
                    'username'
            ) not in admins_of_domain and not session.get('is_global_admin'):
                raise web.seeother('/domains?msg=PERMISSION_DENIED')

        _wrap = SQLWrap()
        conn = _wrap.conn

        form = web.input()
        msg = form.get('msg', '')

        # profile_type == 'general'
        used_quota = {}

        qr = sql_lib_user.profile(mail=mail, conn=conn)

        if qr[0]:
            user_profile = qr[1]
        else:
            if not session.get('is_global_admin') and not session.get(
                    'is_admin'):
                raise web.seeother('/users/{}?msg={}'.format(
                    domain, web.urlquote(qr[1])))
            else:
                raise web.seeother("/dashboard?msg=SOMETHING_WENT_WRONG")
        del qr

        # Get per-user settings
        user_settings = {}
        qr = sql_lib_general.get_user_settings(
            conn=conn, mail=mail, existing_settings=user_profile['settings'])

        if qr[0]:
            user_settings = qr[1]
        del qr

        # Get used quota.
        if settings.SHOW_USED_QUOTA:
            used_quota = sql_lib_general.get_account_used_quota(
                accounts=[mail], conn=conn)

        # Get per-domain disabled user profiles.
        qr = sql_lib_general.get_domain_settings(conn=conn, domain=domain)

        if qr[0]:
            domain_settings = qr[1]
            min_passwd_length = domain_settings.get('min_passwd_length',
                                                    settings.min_passwd_length)
            max_passwd_length = domain_settings.get('max_passwd_length',
                                                    settings.max_passwd_length)

        return web.render(
            'sql/user/profile.html',
            cur_domain=domain,
            mail=mail,
            profile_type=profile_type,
            profile=user_profile,
            timezones=TIMEZONES,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length,
            store_password_in_plain_text=settings.STORE_PASSWORD_IN_PLAIN_TEXT,
            password_policies=iredutils.get_password_policies(),
            user_settings=user_settings,
            used_quota=used_quota,
            languagemaps=iredutils.get_language_maps(),
            msg=msg,
        )
示例#24
0
    def GET(self, profile_type, mail):
        mail = web.safestr(mail).lower()
        profile_type = web.safestr(profile_type)

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

        _wrap = LDAPWrap()
        conn = _wrap.conn

        # Get admin profile.
        qr = ldap_lib_admin.get_profile(mail=mail, conn=conn)
        if qr[0]:
            admin_profile = qr[1]['ldif']
            account_settings = ldaputils.get_account_setting_from_profile(
                admin_profile)
            _qr = ldap_lib_general.get_admin_account_setting(
                mail=mail, profile=admin_profile, conn=conn)
            if _qr[0]:
                account_settings = _qr[1]
        else:
            raise web.seeother('/admins?msg=' + qr[1])

        form = web.input()

        if profile_type in ['general', 'password']:
            # Get all domains.
            qr_all_domains = ldap_lib_domain.list_accounts(
                attributes=['domainName', 'cn'], conn=conn)
            if qr_all_domains[0] is True:
                all_domains = qr_all_domains[1]
            else:
                return qr_all_domains

            # Get domains under control.
            qr_managed_domains = ldap_lib_admin.get_managed_domains(
                admin=mail,
                attributes=['domainName'],
                domain_name_only=True,
                conn=conn)

            if qr_managed_domains[0] is True:
                managed_domains = qr_managed_domains[1]
            else:
                return qr_managed_domains

            return web.render(
                'ldap/admin/profile.html',
                mail=mail,
                profile_type=profile_type,
                admin_profile=admin_profile,
                account_settings=account_settings,
                languagemaps=iredutils.get_language_maps(),
                allDomains=all_domains,
                managedDomains=managed_domains,
                min_passwd_length=settings.min_passwd_length,
                max_passwd_length=settings.max_passwd_length,
                store_password_in_plain_text=settings.
                STORE_PASSWORD_IN_PLAIN_TEXT,
                password_policies=iredutils.get_password_policies(),
                timezones=TIMEZONES,
                msg=form.get('msg', None),
            )
示例#25
0
    def GET(self, profile_type, mail):
        mail = str(mail).lower()
        domain = mail.split('@', 1)[-1]

        _wrap = SQLWrap()
        conn = _wrap.conn

        form = web.input()
        msg = form.get('msg', '')

        # profile_type == 'general'
        used_quota = {}

        qr = sql_lib_user.profile(mail=mail, conn=conn)
        if qr[0]:
            user_profile = qr[1]
        else:
            raise web.seeother('/users/{}?msg={}'.format(
                domain, web.urlquote(qr[1])))
        del qr

        # Get per-user settings
        user_settings = {}
        qr = sql_lib_general.get_user_settings(
            conn=conn, mail=mail, existing_settings=user_profile['settings'])
        if qr[0]:
            user_settings = qr[1]
        del qr

        # Get used quota.
        if settings.SHOW_USED_QUOTA:
            used_quota = sql_lib_general.get_account_used_quota(
                accounts=[mail], conn=conn)

        # Get per-domain disabled user profiles.
        qr = sql_lib_domain.simple_profile(conn=conn,
                                           domain=domain,
                                           columns=['settings'])

        if qr[0]:
            domain_profile = qr[1]
            domain_settings = sqlutils.account_settings_string_to_dict(
                domain_profile['settings'])

            min_passwd_length = domain_settings.get('min_passwd_length',
                                                    settings.min_passwd_length)
            max_passwd_length = domain_settings.get('max_passwd_length',
                                                    settings.max_passwd_length)

        return web.render(
            'sql/user/profile.html',
            cur_domain=domain,
            mail=mail,
            profile_type=profile_type,
            profile=user_profile,
            timezones=TIMEZONES,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length,
            store_password_in_plain_text=settings.STORE_PASSWORD_IN_PLAIN_TEXT,
            password_policies=iredutils.get_password_policies(),
            user_settings=user_settings,
            used_quota=used_quota,
            languagemaps=iredutils.get_language_maps(),
            msg=msg,
        )
示例#26
0
    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')
示例#27
0
def ldif_mailuser(domain,
                  username,
                  cn,
                  passwd,
                  quota=0,
                  storage_base_directory=None,
                  mailbox_format=None,
                  mailbox_folder=None,
                  mailbox_maildir=None,
                  language=None,
                  disabled_services=None,
                  domain_status=None):
    domain = str(domain).lower()
    username = str(username).strip().replace(' ', '').lower()
    mail = username + '@' + domain
    if not cn:
        cn = username

    if not (storage_base_directory and os.path.isabs(storage_base_directory)):
        storage_base_directory = settings.storage_base_directory

    if mailbox_maildir and os.path.isabs(mailbox_maildir):
        home_directory = str(mailbox_maildir).lower()
    else:
        home_directory = os.path.join(storage_base_directory,
                                      iredutils.generate_maildir_path(mail))

    enabled_services = list(attrs.USER_SERVICES_OF_NORMAL_USER
                            ) + settings.ADDITIONAL_ENABLED_USER_SERVICES

    if disabled_services:
        enabled_services = set(enabled_services) - set(disabled_services)
        enabled_services = list(enabled_services)

    lang = language or settings.default_language
    if lang not in iredutils.get_language_maps():
        lang = None

    # Generate basic LDIF.
    ldif = ldaputils.attrs_ldif({
        'objectClass':
        ['inetOrgPerson', 'mailUser', 'shadowAccount', 'amavisAccount'],
        'mail':
        mail,
        'userPassword':
        passwd,
        'cn':
        cn,
        'sn':
        username,
        'uid':
        username,
        'homeDirectory':
        home_directory,
        'accountStatus':
        'active',
        'enabledService':
        enabled_services,
        'preferredLanguage':
        lang,
        # shadowAccount integration.
        'shadowLastChange':
        ldaputils.get_days_of_shadow_last_change(),
        # Amavisd integration.
        'amavisLocal':
        'TRUE',
    })

    # Append quota. No 'mailQuota' attribute means unlimited.
    quota = str(quota).strip()
    if quota.isdigit():
        quota = int(int(quota) * 1024 * 1024)
        ldif += ldaputils.attr_ldif('mailQuota', quota)

    # Append mailbox format.
    if mailbox_format:
        ldif += ldaputils.attr_ldif('mailboxFormat',
                                    str(mailbox_format).lower())

    # mailbox folder
    if mailbox_folder:
        ldif += ldaputils.attr_ldif('mailboxFolder', mailbox_folder)

    if domain_status not in ['active', None]:
        ldif += ldaputils.attr_ldif('domainStatus', 'disabled')

    return ldif
示例#28
0
def get_language(form, input_name='preferredLanguage'):
    lang = get_single_value(form, input_name=input_name, to_string=True)
    if lang not in iredutils.get_language_maps():
        lang = ''

    return lang
示例#29
0
    def GET(self, profile_type, mail):
        mail = str(mail).lower()
        cur_domain = mail.split('@', 1)[-1]

        form = web.input(enabledService=[], telephoneNumber=[], domainName=[])
        msg = form.get('msg')

        profile_type = web.safestr(profile_type)

        _wrap = LDAPWrap()
        conn = _wrap.conn

        qr = ldap_lib_user.get_profile(mail=mail, conn=conn)
        if not qr[0]:
            raise web.seeother('/users/{}?msg={}'.format(
                cur_domain, web.urlquote(qr[1])))

        user_profile = qr[1]['ldif']
        user_account_setting = ldaputils.account_setting_list_to_dict(
            user_profile.get('accountSetting', []))

        # profile_type == 'general'
        accountUsedQuota = {}

        # Per-domain account settings
        domainAccountSetting = {}

        # Get accountSetting of current domain.
        qr = ldap_lib_general.get_domain_account_setting(domain=cur_domain,
                                                         conn=conn)
        if qr[0] is True:
            domainAccountSetting = qr[1]

        if profile_type == 'general':
            # Get account used quota.
            if settings.SHOW_USED_QUOTA:
                accountUsedQuota = ldap_lib_general.get_account_used_quota(
                    [mail])

        (min_passwd_length,
         max_passwd_length) = ldap_lib_general.get_domain_password_lengths(
             domain=cur_domain,
             account_settings=domainAccountSetting,
             fallback_to_global_settings=False)

        password_policies = iredutils.get_password_policies()
        if min_passwd_length > 0:
            password_policies['min_passwd_length'] = min_passwd_length

        if max_passwd_length > 0:
            password_policies['max_passwd_length'] = max_passwd_length

        return web.render(
            'ldap/user/profile.html',
            profile_type=profile_type,
            mail=mail,
            user_profile=user_profile,
            user_account_setting=user_account_setting,
            defaultStorageBaseDirectory=settings.storage_base_directory,
            timezones=TIMEZONES,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length,
            store_password_in_plain_text=settings.STORE_PASSWORD_IN_PLAIN_TEXT,
            password_policies=iredutils.get_password_policies(),
            accountUsedQuota=accountUsedQuota,
            domainAccountSetting=domainAccountSetting,
            languagemaps=iredutils.get_language_maps(),
            msg=msg,
        )