Ejemplo n.º 1
0
    def command(self):
        "run command"
        self.init()
        try:
            for option in ['username', 'password', 'email']:
                if getattr(self.options, option) is None:
                    if option == 'password' and \
                        'BARUWA_ADMIN_PASSWD' in os.environ and \
                        os.environ['BARUWA_ADMIN_PASSWD']:
                        VeryFascistCheck(os.environ['BARUWA_ADMIN_PASSWD'])
                        self.options.password = \
                                            os.environ['BARUWA_ADMIN_PASSWD']
                        continue
                    print "\nOption: %s is required\n" % option
                    print self.parser.print_help()
                    sys.exit(2)

            user = User(username=self.options.username,
                        email=self.options.email)
            user.active = True
            user.timezone = self.options.timezone
            user.account_type = 1
            user.local = True
            user.set_password(self.options.password)
            Session.add(user)
            Session.commit()
            print "Admin account %s created" % self.options.username
        except ValueError, message:
            print >> sys.stderr, "%s." % str(message)[3:]
            sys.exit(2)
Ejemplo n.º 2
0
    def command(self):
        "run command"
        self.init()
        try:
            for option in ['username', 'password', 'email']:
                if getattr(self.options, option) is None:
                    if option == 'password' and \
                        'BARUWA_ADMIN_PASSWD' in os.environ and \
                        os.environ['BARUWA_ADMIN_PASSWD']:
                        VeryFascistCheck(os.environ['BARUWA_ADMIN_PASSWD'])
                        self.options.password = \
                                            os.environ['BARUWA_ADMIN_PASSWD']
                        continue
                    print "\nOption: %s is required\n" % option
                    print self.parser.print_help()
                    sys.exit(2)

            user = User(username=self.options.username,
                        email=self.options.email)
            user.active = True
            user.timezone = self.options.timezone
            user.account_type = 1
            user.local = True
            user.set_password(self.options.password)
            Session.add(user)
            Session.commit()
            print "Admin account %s created" % self.options.username
        except ValueError, message:
            print >> sys.stderr, "%s." % str(message)[3:]
            sys.exit(2)
Ejemplo n.º 3
0
 def add(self):
     """/accounts/new"""
     c.form = AddUserForm(request.POST, csrf_context=session)
     if c.user.is_domain_admin:
         account_types = (('3', 'User'),)
         c.form.account_type.choices = account_types
         c.form.domains.query = Session.query(Domain).join(dom_owns,
                                 (oas, dom_owns.c.organization_id ==
                                 oas.c.organization_id))\
                                 .filter(oas.c.user_id == c.user.id)
     else:
         c.form.domains.query = Session.query(Domain)
     if request.POST and c.form.validate():
         try:
             user = User(username=c.form.username.data,
                     email=c.form.email.data)
             for attr in ['firstname', 'lastname', 'email', 'active',
                 'account_type', 'send_report', 'spam_checks',
                 'low_score', 'high_score', 'timezone']:
                 setattr(user, attr, getattr(c.form, attr).data)
             user.local = True
             user.set_password(c.form.password1.data)
             if int(user.account_type) == 3:
                 user.domains = c.form.domains.data
             Session.add(user)
             Session.commit()
             update_serial.delay()
             info = ADDACCOUNT_MSG % dict(u=user.username)
             audit_log(c.user.username,
                     3, unicode(info), request.host,
                     request.remote_addr, now())
             flash(_('The account: %(user)s was created successfully') %
                     {'user': c.form.username.data})
             redirect(url('account-detail', userid=user.id))
         except IntegrityError:
             Session.rollback()
             flash_alert(
             _('Either the username or email address already exist'))
     return render('/accounts/new.html')
Ejemplo n.º 4
0
 def command(self):
     "run command"
     self.init()
     for option in ['username', 'password', 'email']:
         if getattr(self.options, option) is None:
             print "\nOption: %s is required\n" % option
             print self.parser.print_help()
             sys.exit(2)
     try:
         user = User(username=self.options.username,
                     email=self.options.email)
         user.active = True
         user.timezone = self.options.timezone
         user.account_type = 1
         user.local = True
         user.set_password(self.options.password)
         Session.add(user)
         Session.commit()
         print "Admin account %s created" % self.options.username
     except IntegrityError:
         Session.rollback()
         print >> sys.stderr, ("The user %s already exists" %
                                 self.options.username)
Ejemplo n.º 5
0
 def add(self):
     """/accounts/new"""
     c.form = AddUserForm(request.POST, csrf_context=session)
     if c.user.is_domain_admin:
         account_types = (('3', 'User'), )
         c.form.account_type.choices = account_types
         c.form.domains.query = Session.query(Domain).join(dom_owns,
                                 (oas, dom_owns.c.organization_id ==
                                 oas.c.organization_id))\
                                 .filter(oas.c.user_id == c.user.id)
     else:
         c.form.domains.query = Session.query(Domain)
     if request.POST and c.form.validate():
         try:
             user = User(username=c.form.username.data,
                         email=c.form.email.data)
             for attr in [
                     'firstname', 'lastname', 'email', 'active',
                     'account_type', 'send_report', 'spam_checks',
                     'low_score', 'high_score', 'timezone'
             ]:
                 setattr(user, attr, getattr(c.form, attr).data)
             user.local = True
             user.set_password(c.form.password1.data)
             if int(user.account_type) == 3:
                 user.domains = c.form.domains.data
             Session.add(user)
             Session.commit()
             update_serial.delay()
             info = ADDACCOUNT_MSG % dict(u=user.username)
             audit_log(c.user.username, 3, info, request.host,
                       request.remote_addr, now())
             flash(
                 _('The account: %(user)s was created successfully') %
                 {'user': c.form.username.data})
             redirect(url('account-detail', userid=user.id))
         except IntegrityError:
             Session.rollback()
             flash_alert(
                 _('Either the username or email address already exist'))
     return render('/accounts/new.html')
Ejemplo n.º 6
0
    def loggedin(self):
        "Landing page"
        came_from = (unquote(str(request.params.get('came_from', ''))) or
                    url('/'))
        if not self.identity:
            login_counter = request.environ['repoze.who.logins'] + 1
            redirect(url('/accounts/login',
                    came_from=came_from,
                    __logins=login_counter))
        userid = self.identity['repoze.who.userid']
        user = self.identity['user']
        if user is None:
            try:
                user = User(username=userid, email=userid)
                user.active = True
                local_part, domain = userid.split('@')
                domains = Session.query(Domain)\
                        .filter(Domain.name == domain)\
                        .all()
                user.domains = domains
                user.timezone = domains[0].timezone
                Session.add(user)
                Session.commit()
                msg = _('First time Login from external auth,'
                        ' your local account was created')
                addresses = []
                if ('tokens' in self.identity and
                    'ldap' in self.identity['tokens']):
                    lsettings = Session.query(AuthServer.address,
                                    AuthServer.port, LDAPSettings.binddn,
                                    LDAPSettings.bindpw,
                                    LDAPSettings.usetls)\
                                    .join(LDAPSettings)\
                                    .join(Domain)\
                                    .filter(AuthServer.enabled == True)\
                                    .filter(Domain.name == domain)\
                                    .all()
                    lsettings = lsettings[0]
                    lurl = make_ldap_uri(lsettings.address, lsettings.port)
                    base_dn = get_user_dn(self.identity['tokens'][1])
                    attributes = ['sn', 'givenName', 'proxyAddresses', 'mail',
                                'memberOf']
                    ldapattributes = LDAPAttributes(
                                                lurl,
                                                base_dn,
                                                attributes=attributes,
                                                bind_dn=lsettings.binddn,
                                                bind_pass=lsettings.bindpw,
                                                start_tls=lsettings.usetls
                                                )
                    ldapattributes()
                    attrmap = {
                                'sn': 'lastname',
                                'givenName': 'firstname',
                                'mail': 'email',
                                }

                    update_attrs = False

                    doms = [domains[0].name]
                    doms.extend([alias.name for alias in domains[0].aliases])

                    for attr in attrmap:
                        if attr == 'mail':
                            for mailattr in ldapattributes[attr]:
                                mailattr = mailattr.lower()
                                if (mailattr != user.email and
                                    '@' in mailattr and
                                    mailattr.split('@')[1] in doms):
                                    address = Address(mailattr)
                                    address.user = user
                                    addresses.append(address)
                            continue
                        if attr in ldapattributes:
                            setattr(user,
                                    attrmap[attr],
                                    ldapattributes[attr][0])
                            update_attrs = True

                    if update_attrs:
                        Session.add(user)
                        Session.commit()

                    # accounts aliases
                    if 'proxyAddresses' in ldapattributes:
                        for mailaddr in ldapattributes['proxyAddresses']:
                            try:
                                if mailaddr.startswith('SMTP:'):
                                    continue
                                clean_addr = PROXY_ADDR_RE.sub('', mailaddr)
                                clean_addr = clean_addr.lower()
                                if (mailaddr.startswith('smtp:') and
                                    clean_addr.split('@')[1] in doms):
                                    # Only add domain if we host it
                                    address = Address(clean_addr)
                                    address.user = user
                                    addresses.append(address)
                            except IndexError:
                                pass
                    # accounts groups
                    if 'memberOf' in ldapattributes:
                        for group_dn in ldapattributes['memberOf']:
                            groupattributes = LDAPAttributes(
                                                lurl,
                                                group_dn,
                                                attributes=['proxyAddresses'],
                                                bind_dn=lsettings.binddn,
                                                bind_pass=lsettings.bindpw,
                                                start_tls=lsettings.usetls
                                                )
                            groupattributes()
                            if 'proxyAddresses' not in groupattributes:
                                continue
                            for mailaddr in groupattributes['proxyAddresses']:
                                try:
                                    mailaddr = mailaddr.lower()
                                    clean_addr = PROXY_ADDR_RE.sub('', mailaddr)
                                    if (mailaddr.startswith('smtp:') and
                                        clean_addr.split('@')[1] in doms):
                                        address = Address(clean_addr)
                                        address.user = user
                                        addresses.append(address)
                                except IndexError:
                                    pass
                else:
                    for alias in domains[0].aliases:
                        address = Address('%s@%s' % (local_part, alias.name))
                        address.user = user
                        addresses.append(address)
                for unsaved in addresses:
                    try:
                        Session.add(unsaved)
                        Session.commit()
                    except IntegrityError:
                        Session.rollback()
            except IntegrityError:
                Session.rollback()
                redirect(url('/logout'))
            except ldap.LDAPError:
                pass
        else:
            if not user.active:
                redirect(url('/logout'))
            msg = _('Login successful, Welcome back %(username)s !' %
                    dict(username=userid))
        user.last_login = now()
        Session.add(user)
        Session.commit()
        if user.is_peleb:
            for domain in user.domains:
                if check_language(domain.language):
                    session['lang'] = domain.language
                    session.save()
                    break
        session['taskids'] = []
        session.save()
        info = ACCOUNTLOGIN_MSG % dict(u=user.username)
        audit_log(user.username,
                6, unicode(info), request.host,
                request.remote_addr, now())
        flash(msg)
        redirect(url(came_from))
Ejemplo n.º 7
0
def setup_app(command, conf, variables):
    """Place any commands to setup baruwa here"""
    # Don't reload the app if it was loaded under the testing environment
    if not pylons.test.pylonsapp:
        load_environment(conf.global_conf, conf.local_conf)

    # Create the tables if they don't already exist
    print '-' * 100
    log.info("Creating tables")
    Base.metadata.create_all(bind=Session.bind)
    basepath = os.path.dirname(os.path.dirname(__file__))
    # Create the custom functions
    print '-' * 100
    log.info("Creating custom functions")
    sqlfile = os.path.join(basepath,
                        'baruwa',
                        'config',
                        'sql',
                        'functions.sql')
    if os.path.exists(sqlfile):
        with open(sqlfile, 'r') as handle:
            sql = handle.read()
            try:
                conn = Session.connection()
                conn.execute(text(sql))
                Session.commit()
            except ProgrammingError:
                Session.rollback()
    defaultserver = Session.query(Server)\
                    .filter(Server.hostname == 'default')\
                    .all()
    # Create the Mailscanner SQL config views
    print '-' * 100
    log.info("Populating initial sql")
    sqlfile = os.path.join(basepath,
                        'baruwa',
                        'config',
                        'sql',
                        'integration.sql')
    if os.path.exists(sqlfile):
        with open(sqlfile, 'r') as handle:
            sql = handle.read()
        for sqlcmd in sql.split(';'):
            if sqlcmd:
                try:
                    sqlcmd = "%s;" % sqlcmd
                    Session.execute(text(sqlcmd))
                    Session.commit()
                except ProgrammingError:
                    Session.rollback()
    if not defaultserver:
        log.info("Creating the default settings node")
        dfls = Server('default', True)
        Session.add(dfls)
        confserial = ConfigSettings('confserialnumber',
                                    'ConfSerialNumber',
                                    0)
        confserial.value = 1
        confserial.server_id = 1
        Session.add(confserial)
        Session.commit()
        log.info("Default settings node created !")
    admin = Session.query(User).filter(User.account_type==1).all()
    if not admin:
        def timeout_handler(signum, frame):
            raise TimeoutException()

        old_handler = signal.signal(signal.SIGALRM, timeout_handler) 
        signal.alarm(30)
        try:
            create_user = raw_input('Do you want to configure '
                                'an admin account? (Y/N): ')
        except (TimeoutException, EOFError):
            sys.exit(0)
        finally:
            signal.signal(signal.SIGALRM, old_handler)
        signal.alarm(0)
        if str(create_user).lower() == 'y':
            print '-' * 100
            log.info("Creating initial admin account")
            value_map = {'username': True, 'password1': True,
                        'password2': True, 'firstname': False,
                        'lastname': False, 'email': True}
            values = {}

            def get_input(field, required):
                "Get user input"
                prompt = "Please enter the %s:" % field
                while 1:
                    if field in ['password1', 'password2']:
                        value = getpass.getpass(prompt=prompt)
                    else:
                        value = raw_input(prompt)
                    if not required:
                        break
                    if required and value.strip() != "":
                        if not field in ['email', 'password1', 'password2']:
                            break
                        if field == 'email':
                            if not ADDRESS_RE.match(value):
                                print "Please provide a valid email address."
                            else:
                                break
                        if field == 'password1':
                            try:
                                cracklib.VeryFascistCheck(value)
                            except ValueError, message:
                                print str(message)
                            else:
                                break
                        if field == 'password2':
                            if values['password1'] == value:
                                break
                            else:
                                print 'password2 does not match password1'
                return value

            for attr in value_map:
                value = get_input(attr, value_map[attr])
                values[attr] = value
            user = User(values['username'], values['email'])
            for name in ['firstname', 'lastname']:
                if values[name]:
                    setattr(user, name, values[name])
            user.internal = True
            user.active = True
            user.local = True
            user.account_type = 1
            user.set_password(values['password1'])
            Session.add(user)
            Session.commit()
Ejemplo n.º 8
0
def importaccounts(domid, filename, skipfirst, userid):
    "import accounts"
    logger = importaccounts.get_logger()
    results = dict(rows=[], global_error=[])
    keys = tuple(ACCOUNTFIELDS + ADDRESSFIELDS)

    try:
        with open(filename, 'rU') as handle:
            dialect = csv.Sniffer().sniff(handle.read(1024))
            handle.seek(0)
            rows = csv.DictReader(handle, fieldnames=keys, dialect=dialect)
            query = Session.query(Domain).filter(Domain.id == domid)
            domain = query.one()
            requester = Session.query(User).get(userid)
            logger.info("Importing accounts from file: %s for: %s" %
                        (filename, domain.name))
            try:
                count = 1
                for row in rows:
                    if skipfirst and (count == 1):
                        count += 1
                        continue
                    result = dict(id=None,
                                username=row['username'],
                                imported=False,
                                error=None)
                    try:
                        session_dict = {}
                        dummy = AddUserForm(dict2mdict({}),
                                csrf_context=session_dict)
                        fields = getkeys(row)
                        post_data = dict2mdict(fields)
                        post_data.add('password2', row['password1'])
                        post_data.add('domains', domid)
                        post_data.add('csrf_token',
                                    dummy.csrf_token.current_token)
                        form = AddUserForm(post_data,
                                csrf_context=session_dict)
                        form.domains.query = query
                        if form.validate():
                            #db insert
                            if domain.name != form.email.data.split('@')[1]:
                                raise TypeError(
                                    'Cannot import: %s into domain: %s' %
                                    (form.email.data, domain.name)
                                    )
                            user = User(form.username.data, form.email.data)
                            for attr in ['firstname', 'lastname', 'email',
                                'active', 'account_type', 'send_report',
                                'spam_checks', 'low_score', 'high_score']:
                                setattr(user, attr, getattr(form, attr).data)
                            user.local = True
                            user.set_password(form.password1.data)
                            if user.is_peleb:
                                user.domains = [domain]
                            Session.add(user)
                            Session.commit()
                            result['id'] = user.id
                            result['imported'] = True
                            logger.info("Imported account: %s" %
                                        row['username'])
                            #address add
                            add_address(row, user, requester)
                        else:
                            logger.info("Import failed account: %s" %
                                        row['username'])
                            if isinstance(form.errors, dict):
                                errors = []
                                for field in form.errors:
                                    errors.append('%s: %s' % (field,
                                                form.errors[field][0]))
                                result['error'] = ', '.join(errors)
                            else:
                                result['error'] = form.errors
                    except TypeError, err:
                        logger.info("Import failed account: %s" %
                                    row['username'])
                        result['error'] = str(err)
                    except IntegrityError, err:
                        Session.rollback()
                        logger.info("Import failed account: %s" %
                                    row['username'])
                        result['error'] = 'Account already exists'
                    finally:
                        count += 1
                        results['rows'].append(result)
Ejemplo n.º 9
0
def setup_app(command, conf, variables):
    """Place any commands to setup baruwa here"""
    # Don't reload the app if it was loaded under the testing environment
    if not pylons.test.pylonsapp:
        load_environment(conf.global_conf, conf.local_conf)

    # Create the tables if they don't already exist
    print '-' * 100
    log.info("Creating tables")
    Base.metadata.create_all(bind=Session.bind)
    basepath = os.path.dirname(os.path.dirname(__file__))
    # Create the custom functions
    print '-' * 100
    log.info("Creating custom functions")
    sqlfile = os.path.join(basepath, 'baruwa', 'config', 'sql',
                           'functions.sql')
    if os.path.exists(sqlfile):
        with open(sqlfile, 'r') as handle:
            sql = handle.read()
            try:
                conn = Session.connection()
                conn.execute(text(sql))
                Session.commit()
            except ProgrammingError:
                Session.rollback()
    defaultserver = Session.query(Server)\
                    .filter(Server.hostname == 'default')\
                    .all()
    # Create the Mailscanner SQL config views
    print '-' * 100
    log.info("Populating initial sql")
    sqlfile = os.path.join(basepath, 'baruwa', 'config', 'sql',
                           'integration.sql')
    if os.path.exists(sqlfile):
        with open(sqlfile, 'r') as handle:
            sql = handle.read()
        for sqlcmd in sql.split(';'):
            if sqlcmd:
                try:
                    sqlcmd = "%s;" % sqlcmd
                    Session.execute(text(sqlcmd))
                    Session.commit()
                except ProgrammingError:
                    Session.rollback()
    if not defaultserver:
        log.info("Creating the default settings node")
        dfls = Server('default', True)
        Session.add(dfls)
        confserial = ConfigSettings('confserialnumber', 'ConfSerialNumber', 0)
        confserial.value = 1
        confserial.server_id = 1
        Session.add(confserial)
        Session.commit()
        log.info("Default settings node created !")
    admin = Session.query(User).filter(User.account_type == 1).all()
    if not admin:

        def timeout_handler(signum, frame):
            raise TimeoutException()

        old_handler = signal.signal(signal.SIGALRM, timeout_handler)
        signal.alarm(30)
        try:
            create_user = raw_input('Do you want to configure '
                                    'an admin account? (Y/N): ')
        except (TimeoutException, EOFError):
            sys.exit(0)
        finally:
            signal.signal(signal.SIGALRM, old_handler)
        signal.alarm(0)
        if str(create_user).lower() == 'y':
            print '-' * 100
            log.info("Creating initial admin account")
            value_map = {
                'username': True,
                'password1': True,
                'password2': True,
                'firstname': False,
                'lastname': False,
                'email': True
            }
            values = {}

            def get_input(field, required):
                "Get user input"
                prompt = "Please enter the %s:" % field
                while 1:
                    if field in ['password1', 'password2']:
                        value = getpass.getpass(prompt=prompt)
                    else:
                        value = raw_input(prompt)
                    if not required:
                        break
                    if required and value.strip() != "":
                        if not field in ['email', 'password1', 'password2']:
                            break
                        if field == 'email':
                            if not ADDRESS_RE.match(value):
                                print "Please provide a valid email address."
                            else:
                                break
                        if field == 'password1':
                            try:
                                cracklib.VeryFascistCheck(value)
                            except ValueError, message:
                                print str(message)
                            else:
                                break
                        if field == 'password2':
                            if values['password1'] == value:
                                break
                            else:
                                print 'password2 does not match password1'
                return value

            for attr in value_map:
                value = get_input(attr, value_map[attr])
                values[attr] = value
            user = User(values['username'], values['email'])
            for name in ['firstname', 'lastname']:
                if values[name]:
                    setattr(user, name, values[name])
            user.internal = True
            user.active = True
            user.local = True
            user.account_type = 1
            user.set_password(values['password1'])
            Session.add(user)
            Session.commit()
Ejemplo n.º 10
0
    def loggedin(self):
        "Landing page"
        came_from = (unquote(str(request.params.get('came_from', '')))
                     or url('/'))
        if not self.identity:
            login_counter = request.environ['repoze.who.logins'] + 1
            redirect(
                url('/accounts/login',
                    came_from=came_from,
                    __logins=login_counter))
        userid = self.identity['repoze.who.userid']
        user = self.identity['user']
        if user is None:
            try:
                user = User(username=userid, email=userid)
                user.active = True
                local_part, domain = userid.split('@')
                domains = Session.query(Domain)\
                        .filter(Domain.name == domain)\
                        .all()
                user.domains = domains
                user.timezone = domains[0].timezone
                Session.add(user)
                Session.commit()
                msg = _('First time Login from external auth,'
                        ' your local account was created')
                addresses = []
                if ('tokens' in self.identity
                        and 'ldap' in self.identity['tokens']):
                    lsettings = Session.query(AuthServer.address,
                                    AuthServer.port, LDAPSettings.binddn,
                                    LDAPSettings.bindpw,
                                    LDAPSettings.usetls)\
                                    .join(Domain)\
                                    .filter(AuthServer.enabled == True)\
                                    .filter(Domain.name == domain)\
                                    .all()
                    lsettings = lsettings[0]
                    lurl = make_ldap_uri(lsettings.address, lsettings.port)
                    base_dn = get_user_dn(self.identity['tokens'][1])
                    attributes = [
                        'sn', 'givenName', 'proxyAddresses', 'mail', 'memberOf'
                    ]
                    ldapattributes = LDAPAttributes(lurl,
                                                    base_dn,
                                                    attributes=attributes,
                                                    bind_dn=lsettings.binddn,
                                                    bind_pass=lsettings.bindpw,
                                                    start_tls=lsettings.usetls)
                    ldapattributes()
                    attrmap = {
                        'sn': 'lastname',
                        'givenName': 'firstname',
                        'mail': 'email',
                    }

                    update_attrs = False

                    doms = [domains[0].name]
                    doms.extend([alias.name for alias in domains[0].aliases])

                    for attr in attrmap:
                        if (attr == 'mail' and attr in ldapattributes
                                and ldapattributes[attr][0] == user.email):
                            # Dont update if user.email = directory.email
                            continue
                        if (attr == 'mail' and attr in ldapattributes
                                and '@' in ldapattributes[attr][0]):
                            # Update if email is hosted by us
                            if ldapattributes[attr][0].split('@')[1] in doms:
                                setattr(user, attrmap[attr],
                                        ldapattributes[attr][0])
                                update_attrs = True
                            continue
                        if attr in ldapattributes:
                            setattr(user, attrmap[attr],
                                    ldapattributes[attr][0])
                            update_attrs = True

                    if update_attrs:
                        Session.add(user)
                        Session.commit()

                    # accounts aliases
                    if 'proxyAddresses' in ldapattributes:
                        for mailaddr in ldapattributes['proxyAddresses']:
                            try:
                                if mailaddr.startswith('SMTP:'):
                                    continue
                                if (mailaddr.startswith('smtp:') and
                                        mailaddr.strip('smtp:').lsplit('@')[1]
                                        in doms):
                                    # Only add domain if we host it
                                    address = Address(
                                        PROXY_ADDR_RE.sub('', mailaddr))
                                    address.user = user
                                    addresses.append(address)
                            except IndexError:
                                pass
                    # accounts groups
                    if 'memberOf' in ldapattributes:
                        for group_dn in ldapattributes['memberOf']:
                            groupattributes = LDAPAttributes(
                                lurl,
                                group_dn,
                                attributes=['proxyAddresses'],
                                bind_dn=lsettings.binddn,
                                bind_pass=lsettings.bindpw,
                                start_tls=lsettings.usetls)
                            groupattributes()
                            for mailaddr in groupattributes['proxyAddresses']:
                                try:
                                    mailaddr = mailaddr.lower()
                                    if (mailaddr.startswith('smtp:')
                                            and mailaddr.lstrip('smtp:').split(
                                                '@')[1] in doms):
                                        address = Address(
                                            PROXY_ADDR_RE.sub('', mailaddr))
                                        address.user = user
                                        addresses.append(address)
                                except IndexError:
                                    pass
                else:
                    for alias in domains[0].aliases:
                        address = Address('%s@%s' % (local_part, alias.name))
                        address.user = user
                        addresses.append(address)
                for unsaved in addresses:
                    try:
                        Session.add(unsaved)
                        Session.commit()
                    except IntegrityError:
                        Session.rollback()
            except IntegrityError:
                Session.rollback()
                redirect(url('/logout'))
        else:
            msg = _('Login successful, Welcome back %(username)s !' %
                    dict(username=userid))
        user.last_login = now()
        Session.add(user)
        Session.commit()
        if user.is_peleb:
            for domain in user.domains:
                if check_language(domain.language):
                    session['lang'] = domain.language
                    session.save()
                    break
        session['taskids'] = []
        session.save()
        info = ACCOUNTLOGIN_MSG % dict(u=user.username)
        audit_log(user.username, 6, info, request.host, request.remote_addr,
                  now())
        flash(msg)
        redirect(url(came_from))
Ejemplo n.º 11
0
def importaccounts(domid, filename, skipfirst, userid):
    "import accounts"
    logger = importaccounts.get_logger()
    results = dict(rows=[], global_error=[])
    keys = tuple(ACCOUNTFIELDS + ADDRESSFIELDS)

    try:
        with open(filename, 'rU') as handle:
            dialect = csv.Sniffer().sniff(handle.read(1024))
            handle.seek(0)
            rows = csv.DictReader(handle, fieldnames=keys, dialect=dialect)
            query = Session.query(Domain).filter(Domain.id == domid)
            domain = query.one()
            requester = Session.query(User).get(userid)
            logger.info("Importing accounts from file: %s for: %s" %
                        (filename, domain.name))
            try:
                count = 1
                for row in rows:
                    if skipfirst and (count == 1):
                        count += 1
                        continue
                    result = dict(id=None,
                                  username=row['username'],
                                  imported=False,
                                  error=None)
                    try:
                        session_dict = {}
                        dummy = AddUserForm(dict2mdict({}),
                                            csrf_context=session_dict)
                        fields = getkeys(row)
                        post_data = dict2mdict(fields)
                        post_data.add('password2', row['password1'])
                        post_data.add('domains', domid)
                        post_data.add('csrf_token',
                                      dummy.csrf_token.current_token)
                        form = AddUserForm(post_data,
                                           csrf_context=session_dict)
                        form.domains.query = query
                        if form.validate():
                            #db insert
                            if domain.name != form.email.data.split('@')[1]:
                                raise TypeError(
                                    'Cannot import: %s into domain: %s' %
                                    (form.email.data, domain.name))
                            user = User(form.username.data, form.email.data)
                            for attr in [
                                    'firstname', 'lastname', 'email', 'active',
                                    'account_type', 'send_report',
                                    'spam_checks', 'low_score', 'high_score'
                            ]:
                                setattr(user, attr, getattr(form, attr).data)
                            user.local = True
                            user.set_password(form.password1.data)
                            if user.is_peleb:
                                user.domains = [domain]
                            Session.add(user)
                            Session.commit()
                            result['id'] = user.id
                            result['imported'] = True
                            logger.info("Imported account: %s" %
                                        row['username'])
                            #address add
                            add_address(row, user, requester)
                        else:
                            logger.info("Import failed account: %s" %
                                        row['username'])
                            if isinstance(form.errors, dict):
                                errors = []
                                for field in form.errors:
                                    errors.append(
                                        '%s: %s' %
                                        (field, form.errors[field][0]))
                                result['error'] = ', '.join(errors)
                            else:
                                result['error'] = form.errors
                    except TypeError, err:
                        logger.info("Import failed account: %s" %
                                    row['username'])
                        result['error'] = str(err)
                    except IntegrityError, err:
                        Session.rollback()
                        logger.info("Import failed account: %s" %
                                    row['username'])
                        result['error'] = 'Account already exists'
                    finally:
                        count += 1
                        results['rows'].append(result)