Example #1
0
def create_sign_clean():
    "Generate the sign clean ruleset"
    usersql = """SELECT users.email, '' as address  FROM users,
                user_signatures WHERE users.active = 't'
                AND users.id=user_signatures.user_id
                AND user_signatures.enabled='t' AND
                user_signatures.signature_type = 1
                UNION
                SELECT users.email, addresses.address
                FROM users,addresses, user_signatures
                WHERE users.id=addresses.user_id
                AND users.id=user_signatures.user_id AND
                addresses.enabled='t' AND
                user_signatures.enabled='t' AND
                user_signatures.signature_type = 1
                """
    domainsql = """SELECT name FROM alldomains,
                domain_signatures WHERE alldomains.id =
                domain_signatures.domain_id AND
                alldomains.status='t' AND
                domain_signatures.enabled='t' AND
                domain_signatures.signature_type = 1
                """
    users = Session.execute(usersql)
    domains = Session.execute(domainsql)
    kwargs = dict(users=users, domains=domains)
    write_ruleset('sign.clean.msgs.rules', kwargs)
    Session.close()
Example #2
0
    def addaddress(self, userid):
        "Add address"
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = AddressForm(request.POST, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            try:
                addr = create_address(c.form, user, c.user, request.host,
                                      request.remote_addr)
                flash(
                    _('The alias address %(address)s was successfully created.'
                      % dict(address=addr.address)))
            except IntegrityError:
                Session.rollback()
                msg = _('The address %(addr)s already exists') % \
                        dict(addr=c.form.address.data)
                flash_alert(msg)
                log.info(msg)
            except NoResultFound:
                domain = c.form.address.data.split('@')[1]
                msg = _('Domain: %(d)s does not belong to you') % \
                        dict(d=domain)
                flash(msg)
                log.info(msg)
            redirect(url(controller='accounts', action='detail',
                         userid=userid))
        c.id = userid
        return self.render('/accounts/addaddress.html')
Example #3
0
    def editalias(self, aliasid):
        "Edit alias domain"
        alias = self._get_alias(aliasid)
        if not alias:
            abort(404)

        c.form = EditDomainAlias(request.POST, alias, csrf_context=session)
        c.form.domain.query = Session.query(Domain)\
                            .filter(Domain.id == alias.domain_id)
        if request.method == 'POST' and c.form.validate():
            if update_if_changed(c.form, alias):
                try:
                    edit_alias(alias, c.user, request.host,
                                request.remote_addr)
                    flash(_('The domain alias: %s has been updated') %
                            alias.name)
                    redirect(url('domain-detail', domainid=alias.domain_id))
                except IntegrityError:
                    Session.rollback()
                    msg = _('The update failed')
                    flash_alert(msg)
                    log.info(msg)
            else:
                msg = _('No changes were made to the domain alias')
                flash_info(msg)
                log.info(msg)
                redirect(url('domain-detail', domainid=alias.domain_id))

        c.aliasid = aliasid
        c.domainid = alias.domain_id
        c.domainname = alias.domain.name
        return self.render('/domains/editalias.html')
Example #4
0
 def evaluate(self, environ, credentials):
     "Evaluate"
     identity = environ.get('repoze.who.identity')
     user = identity['user']
     if not user.is_superadmin or not user.active:
         try:
             varbs = self.parse_variables(environ)
             if 'domainid' in varbs['named_args']:
                 domainid = varbs['named_args'].get('domainid')
             if 'destinationid' in varbs['named_args']:
                 destinationid = varbs['named_args'].get('destinationid')
                 dest = Session.query(DeliveryServer.domain_id)\
                             .filter(DeliveryServer.id == destinationid)\
                             .one()
                 domainid = dest.domain_id
             if 'authid' in varbs['named_args']:
                 authid = varbs['named_args'].get('authid')
                 authsvr = Session.query(AuthServer.domain_id)\
                             .filter(AuthServer.id == authid).one()
                 domainid = authsvr.domain_id
             if 'sigid' in varbs['named_args']:
                 sigid = varbs['named_args'].get('sigid')
                 sig = Session.query(DomSignature.domain_id)\
                         .filter(DomSignature.id == sigid).one()
                 domainid = sig.domain_id
             if not check_domain_ownership(user.id, domainid):
                 self.unmet()
         except NoResultFound:
             self.unmet()
Example #5
0
 def pwchange(self, userid):
     """Reset a user password"""
     user = self._get_user(userid)
     if not user:
         abort(404)
     c.form = ChangePasswordForm(request.POST, csrf_context=session)
     if request.POST and c.form.validate():
         if user.local and not user.is_superadmin:
             user.set_password(c.form.password1.data)
             Session.add(user)
             Session.commit()
             flash(_('The account password for %(name)s has been reset')
                 % dict(name=user.username))
             info = PASSWORDCHANGE_MSG % dict(u=user.username)
             audit_log(c.user.username,
                     2, unicode(info), request.host,
                     request.remote_addr, now())
         else:
             if user.is_superadmin:
                 flash(_('Admin accounts can not be modified via the web'))
             else:
                 flash(_('This is an external account, use'
                     ' external system to reset the password'))
         redirect(url('account-detail', userid=user.id))
     c.id = userid
     c.username = user.username
     c.posturl = 'accounts-pw-change'
     return render('/accounts/pwchange.html')
Example #6
0
    def command(self):
        "command"
        self.init()

        if acquire_lock('dbclean', self.conf):
            try:
                if self.options.days > 0:
                    days = self.options.days
                else:
                    days = int(self.conf.get('baruwa.messages.keep.days', 30))
                if self.options.adays > 0:
                    adays = self.options.adays
                else:
                    adays = int(self.conf.get('baruwa.archive.keep.days', 90))

                interval = datetime.timedelta(days=days)
                archive_interval = datetime.timedelta(days=adays)
                current_date = arrow.utcnow().datetime
                msgs_date = current_date - interval
                last_achive_date = current_date - archive_interval
                releases_date = current_date - datetime.timedelta(days=2)
                # process messages table
                process_messages(msgs_date)
                # process archive table
                prune_archive(last_achive_date)
                # process message status table
                prune_table('messagestatus', last_achive_date)
                # process releases table
                prune_table('releases', releases_date)
                # process awl table
                prune_table('awl', msgs_date)
            finally:
                Session.close()
                release_lock('dbclean', self.conf)
Example #7
0
def update_audit_log(username,
                    category,
                    info,
                    hostname,
                    remoteip,
                    timestamp=None):
    "Update the audit log"
    logger = update_audit_log.get_logger()
    try:
        entry = AuditLog(username,
                        category,
                        info,
                        hostname,
                        remoteip)
        if timestamp:
            entry.timestamp = timestamp
        Session.add(entry)
        Session.commit()
        logger.info("Audit Log update for: %s from: %s" %
                    (username, remoteip))
    except DatabaseError, err:
        logger.error("Audit Log FAILURE: %s %s %s %s %s %s Error: %s" %
                    (username,
                    category,
                    info,
                    hostname,
                    remoteip,
                    timestamp,
                    err))
Example #8
0
def check_domain(form, field):
    "check domain"
    domain = field.data.split("@")[1]
    try:
        Session.query(Domain).filter(Domain.name == domain).one()
    except NoResultFound:
        raise validators.ValidationError(_("The domain: %(dom)s is not local") % dict(dom=domain))
Example #9
0
 def delete_auth(self, authid):
     "Delete auth server"
     server = self._get_authserver(authid)
     if not server:
         abort(404)
     c.form = AddAuthForm(request.POST, server, csrf_context=session)
     if request.POST and c.form.validate():
         name = server.domains.name
         server_addr = server.address
         domainid = server.domains.id
         Session.delete(server)
         Session.commit()
         flash(_("The authentication settings have been deleted"))
         info = DELETEAUTHSVR_MSG % dict(d=name, ds=server_addr)
         audit_log(c.user.username, 4, info, request.host, request.remote_addr, datetime.now())
         redirect(url("domain-detail", domainid=domainid))
     else:
         flash(
             _("The authentication server: %(s)s will be deleted," " This action is not reversible")
             % dict(s=server.address)
         )
     c.domainid = server.domains.id
     c.domainname = server.domains.name
     c.authid = authid
     return render("/domains/deleteauth.html")
Example #10
0
 def deletedestination(self, destinationid):
     "Delete destination server"
     server = self._get_server(destinationid)
     if not server:
         abort(404)
     c.form = AddDeliveryServerForm(request.POST,
                                     server,
                                     csrf_context=session)
     if request.POST and c.form.validate():
         name = server.domains.name
         server_addr = server.address
         domainid = server.domain_id
         Session.delete(server)
         Session.commit()
         flash(_('The destination server has been deleted'))
         info = DELETEDELSVR_MSG % dict(d=name, ds=server_addr)
         audit_log(c.user.username,
                 4, unicode(info), request.host,
                 request.remote_addr, now())
         redirect(url('domain-detail', domainid=domainid))
     else:
         flash(_('The destination server: %(s)s will be deleted,'
             ' This action is not reversible') % dict(s=server.address))
     c.id = destinationid
     c.domainid = server.domain_id
     return render('/domains/deletedestination.html')
Example #11
0
    def deletealias(self, aliasid):
        "Delete alias domain"
        alias = self._get_alias(aliasid)
        if not alias:
            abort(404)

        c.form = DelDomainAlias(request.POST, alias, csrf_context=session)
        c.form.domain.query = Session.query(Domain)\
                            .filter(Domain.id==alias.domain_id)
        if request.POST and c.form.validate():
            domainid = alias.domain_id
            aliasname = alias.name
            Session.delete(alias)
            Session.commit()
            update_serial.delay()
            info = DELETEDOMALIAS_MSG % dict(d=aliasname)
            audit_log(c.user.username,
                    4, unicode(info), request.host,
                    request.remote_addr, now())
            flash(_('The domain alias: %s has been deleted') % aliasname)
            redirect(url('domain-detail', domainid=domainid))

        c.aliasid = aliasid
        c.domainid = alias.domain_id
        c.domainname = alias.domain.name
        return render('/domains/deletealias.html')
Example #12
0
    def editaddress(self, addressid):
        "Edit address"
        address = get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            try:
                if (address.address != c.form.address.data or
                    address.enabled != c.form.enabled.data):
                    update_address(c.form, address, c.user,
                                request.host, request.remote_addr)
                    flash(_('The alias address has been updated'))
                else:
                    flash_info(_('No changes were made to the address'))
            except IntegrityError:
                Session.rollback()
                msg = _('The address %(addr)s already exists') % \
                        dict(addr=c.form.address.data)
                flash_alert(msg)
                log.info(msg)
            except NoResultFound:
                domain = c.form.address.data.split('@')[1]
                msg = _('Domain: %(d)s does not belong to you') % \
                        dict(d=domain)
                flash(msg)
                log.info(msg)
            redirect(url(controller='accounts', action='detail',
            userid=address.user_id))
        c.id = addressid
        c.userid = address.user_id
        return self.render('/accounts/editaddress.html')
Example #13
0
    def addaddress(self, userid):
        "Add address"
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = AddressForm(request.POST, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            try:
                addr = create_address(c.form, user, c.user,
                                    request.host, request.remote_addr)
                flash(
                    _('The alias address %(address)s was successfully created.'
                    % dict(address=addr.address)))
            except IntegrityError:
                Session.rollback()
                msg = _('The address %(addr)s already exists') % \
                        dict(addr=c.form.address.data)
                flash_alert(msg)
                log.info(msg)
            except NoResultFound:
                domain = c.form.address.data.split('@')[1]
                msg = _('Domain: %(d)s does not belong to you') % \
                        dict(d=domain)
                flash(msg)
                log.info(msg)
            redirect(url(controller='accounts', action='detail',
                    userid=userid))
        c.id = userid
        return self.render('/accounts/addaddress.html')
Example #14
0
    def edit(self, userid):
        """GET /accounts/edit/id: Form to edit an existing item"""
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = user_update_form(user, c.user, request.POST, session)
        if request.method == 'POST' and c.form.validate():
            kwd = dict(userid=user.id)
            if update_changed(c.form, FORM_FIELDS, user):
                try:
                    update_user(user, c.user, request.host,
                                request.remote_addr)
                    flash(_('The account has been updated'))
                    kwd['uc'] = 1
                except IntegrityError:
                    Session.rollback()
                    flash_alert(
                        _('The account: %(acc)s could not be updated') %
                        dict(acc=user.username))
                if (user.id == c.user.id and c.form.active and
                    c.form.active.data is False):
                    redirect(url('/logout'))
            else:
                flash_info(_('No changes made to the account'))
            redirect(url(controller='accounts', action='detail', **kwd))
        c.fields = FORM_FIELDS
        c.id = userid
        return self.render('/accounts/edit.html')
Example #15
0
def get_list_data(list_type):
    "Return lists"
    # email to any
    email2any = Session.query(List).filter(List.list_type == list_type)\
                .filter(List.from_addr_type == 1)\
                .filter(List.to_address == u'any')
    email2any = windowed_query(email2any, List.id, 500)
    # non email to any
    nonemail2any = Session.query(List).filter(List.list_type == list_type)\
                .filter(List.from_addr_type != 1)\
                .filter(List.to_address == u'any')
    nonemail2any = windowed_query(nonemail2any, List.id, 500)
    # email to non any
    email2nonany = Session.query(List).filter(List.list_type == list_type)\
                .filter(List.from_addr_type == 1)\
                .filter(List.to_address != u'any')
    email2nonany = windowed_query(email2nonany, List.id, 500)
    # nonemail to non any
    nonemail2nonany = Session.query(List).filter(List.list_type == list_type)\
                .filter(List.from_addr_type != 1)\
                .filter(List.to_address != u'any')
    nonemail2nonany = windowed_query(nonemail2nonany, List.id, 500)
    kwargs = dict(email2any=email2any,
                  nonemail2any=nonemail2any,
                  email2nonany=email2nonany,
                  nonemail2nonany=nonemail2nonany)
    return kwargs
Example #16
0
 def domain_dkim_enable(self, domainid):
     "Enable or disable DKIM signing"
     domain = self._get_domain(domainid)
     if not domain or not domain.dkimkeys:
         abort(404)
     c.form = DKIMForm(request.POST, domain.dkimkeys[0],
                         csrf_context=session)
     if request.POST and c.form.validate():
         dkimkeys = domain.dkimkeys[0]
         if dkimkeys.enabled != c.form.enabled.data:
             dkimkeys.enabled = c.form.enabled.data
             Session.add(dkimkeys)
             Session.commit()
             if c.form.enabled.data:
                 state = _('enabled')
                 save_dkim_key.apply_async(args=[domain.name,
                                         dkimkeys.pri_key],
                                         queue='msbackend')
                 info = DKIMENABLED_MSG % dict(d=domain.name)
             else:
                 info = DKIMDISABLED_MSG % dict(d=domain.name)
                 delete_dkim_key.apply_async(args=[domain.name],
                                         queue='msbackend')
                 state = _('disabled')
             audit_log(c.user.username,
                     2, info, request.host,
                     request.remote_addr, datetime.now())
             reload_exim.delay()
             flash(_('DKIM signing for: %s has been %s') %
                     (domain.name, state))
         else:
             flash(_('DKIM signing status: No changes made'))
         redirect(url('domain-dkim', domainid=domain.id))
     c.domain = domain
     return render('/settings/domain_dkim_enable.html')
Example #17
0
def create_content_ruleset():
    """Create content ruleset"""
    def set_attrs(obj, dom=None):
        """Set attrs"""
        for key in POLICY_SETTINGS_MAP:
            attr = POLICY_SETTINGS_MAP[key]
            value = getattr(obj, attr)
            if value != 0:
                policy = Session.query(Policy.name)\
                                .filter(Policy.id == value)\
                                .one()
                setattr(obj, '%s-name' % attr, "%s.conf" % policy.name)
        if dom:
            setattr(obj, 'domain_name', dom.name)
            setattr(obj, 'domain_aliases', dom.aliases)
            return obj

    global_policy = Session.query(PolicySettings).get(1)
    set_attrs(global_policy)
    dpsq = Session.query(DomainPolicy, Domain)\
                    .filter(DomainPolicy.domain_id == Domain.id)\
                    .filter(Domain.status == true())
    domain_policies = [set_attrs(dps[0], dps[1]) for dps in dpsq]
    for policy_type in [1, 2, 3, 4]:
        kwargs = dict(gps=global_policy,
                      dps=domain_policies,
                      policy_type=POLICY_SETTINGS_MAP[policy_type],
                      default="%s.conf" % POLICY_FILE_MAP[policy_type])
        write_ruleset(POLICY_FILE_MAP[policy_type], kwargs,
                      'content.protection.ruleset')
Example #18
0
    def command(self):
        "run command"
        self.init()
        if self.options.username is None:
            print >> sys.stderr, "\nProvide an username\n"
            print self.parser.print_help()
            sys.exit(126)

        try:
            user = Session\
                    .query(User)\
                    .filter(User.username == self.options.username)\
                    .filter(User.local == true())\
                    .one()
            if user.validate_password(os.environ['BARUWA_ADMIN_PASSWD']):
                print >> sys.stderr, "The account password is valid"
                sys.exit(0)
            else:
                print >> sys.stderr, "The account password is invalid"
                sys.exit(2)
        except KeyError:
            print >> sys.stderr, "BARUWA_ADMIN_PASSWD env variable not set"
            sys.exit(126)
        except NoResultFound:
            print >> sys.stderr, ("No local user found with username %s" %
                                    self.options.username)
            sys.exit(126)
        finally:
            Session.close()
Example #19
0
def update_queue_stats(hostname):
    "Update queue stats"
    inqdir = get_config_option('IncomingQueueDir')
    outqdir = get_config_option('OutgoingQueueDir')

    allids, inqueue = process_queue(inqdir, 1)
    tmpids, outqueue = process_queue(outqdir, 2)
    allids.extend(tmpids)

    dbids = [item.messageid
            for item in Session.query(MailQueueItem.messageid)
                        .filter(MailQueueItem.hostname ==
                        hostname.decode('utf-8')).all()]
    remids = [item for item in dbids if item not in allids]
    preids = [item for item in dbids if item not in remids]

    if remids:
        print >> sys.stderr, ("== Deleting %(items)d queue "
                "items from DB ==" % dict(items=len(remids)))
        Session.query(MailQueueItem)\
                .filter(MailQueueItem.messageid.in_(remids))\
                .delete(synchronize_session='fetch')
        Session.commit()

    populate_db(inqueue, inqdir, 1, preids)
    populate_db(outqueue, outqdir, 2, preids)
Example #20
0
    def edit(self, domainid):
        "Edit a domain"
        domain = self._get_domain(domainid)
        if not domain:
            abort(404)

        c.id = domainid
        c.form = domain_update_form(c.user, request.POST, domain,
                                    get_organizations, session)
        if request.method == 'POST' and c.form.validate():
            kwd = dict(domainid=domain.id)
            if domain_update_if_changed(c.form, domain):
                try:
                    update_domain(domain, c.user, request.host,
                                  request.remote_addr)
                    flash(
                        _('The domain: %(dom)s has been updated') %
                        dict(dom=domain.name))
                    kwd['uc'] = 1
                except IntegrityError:
                    Session.rollback()
                    msg = _('The domain %(dom)s could not be updated') % \
                            dict(dom=domain.name)
                    flash(msg)
                    log.info(msg)
            else:
                msg = _('No changes were made to the domain')
                flash_info(msg)
                log.info(msg)
            redirect(url('domain-detail', **kwd))
        return self.render('/domains/edit.html')
Example #21
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        def check_url():
            "check if user should have totals calculated"
            if ('format' in environ['pylons.routes_dict'] and
                    environ['pylons.routes_dict']['format'] in ['csv', 'pdf']):
                return False
            if environ['PATH_INFO'] == '/jsi18n.js':
                return False
            return True

        self.identity = environ.get('repoze.who.identity')
        if (self.identity is not None and 'user' in self.identity
                and environ['pylons.routes_dict']['controller'] != 'error'
                and check_url()):

            if self.identity['user']:
                totals = DailyTotals(Session, self.identity['user'])
                mailq = MailQueue(Session, self.identity['user'])
                c.baruwa_totals = totals.get()
                c.baruwa_inbound = mailq.get(1)[0]
                c.baruwa_outbound = mailq.get(2)[0]
                if self.identity['user'].is_admin:
                    c.baruwa_status = cluster_status()

                tzinfo = self.identity['user'].timezone or UTC
                c.tzinfo = make_tz(tzinfo)
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()
Example #22
0
    def adddestination(self, domainid):
        "Add a destination server"
        domain = self._get_domain(domainid)
        if not domain:
            abort(404)

        c.id = domainid
        c.form = AddDeliveryServerForm(request.POST, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            server = DeliveryServer()
            server.from_form(c.form)
            try:
                create_destination(domain, server, c.user, request.host,
                                   request.remote_addr)
                flash(_('The destination server has been created'))
                redirect(
                    url(controller='domains',
                        action='detail',
                        domainid=domain.id))
            except IntegrityError:
                Session.rollback()
                msg = _('The destination server %(dest)s already exists ') % \
                        dict(dest=server.address)
                flash_alert(msg)
                log.info(msg)
        return self.render('/domains/adddestination.html')
Example #23
0
 def delete_auth(self, authid):
     "Delete auth server"
     server = self._get_authserver(authid)
     if not server:
         abort(404)
     c.form = AddAuthForm(request.POST, server, csrf_context=session)
     if request.POST and c.form.validate():
         name = server.domains.name
         server_addr = server.address
         domainid = server.domains.id
         Session.delete(server)
         Session.commit()
         flash(_('The authentication settings have been deleted'))
         info = DELETEAUTHSVR_MSG % dict(d=name, ds=server_addr)
         audit_log(c.user.username, 4, info, request.host,
                   request.remote_addr, now())
         redirect(url('domain-detail', domainid=domainid))
     else:
         flash(
             _('The authentication server: %(s)s will be deleted,'
               ' This action is not reversible') % dict(s=server.address))
     c.domainid = server.domains.id
     c.domainname = server.domains.name
     c.authid = authid
     return render('/domains/deleteauth.html')
Example #24
0
 def editdestination(self, destinationid):
     "Edit destination server"
     server = self._get_server(destinationid)
     if not server:
         abort(404)
     c.form = AddDeliveryServerForm(request.POST,
                                    server,
                                    csrf_context=session)
     if request.method == 'POST' and c.form.validate():
         kwd = dict(domainid=server.domain_id)
         if update_if_changed(c.form, server):
             try:
                 update_destination(server, c.user, request.host,
                                    request.remote_addr)
                 self.invalidate = 1
                 self._get_server(destinationid)
                 kwd['uc'] = 1
                 flash(_('The destination server has been updated'))
                 redirect(url('domain-detail', **kwd))
             except IntegrityError:
                 Session.rollback()
                 msg = _('The update failed')
                 flash_alert(msg)
                 log.info(msg)
         else:
             msg = _('No changes were made to the destination server')
             flash_info(msg)
             log.info(msg)
             redirect(url('domain-detail', **kwd))
     c.id = destinationid
     c.domainid = server.domain_id
     return self.render('/domains/editdestination.html')
Example #25
0
    def delete(self, userid):
        """/accounts/delete/id"""
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = EditUserForm(request.POST, user, csrf_context=session)
        del c.form.domains

        if request.POST and c.form.validate():
            username = user.username
            user_id = unicode(user.id)
            Session.delete(user)
            Session.commit()
            update_serial.delay()
            flash(_('The account has been deleted'))
            info = DELETEACCOUNT_MSG % dict(u=username)
            audit_log(c.user.username,
                    4, unicode(info), request.host,
                    request.remote_addr, now())
            if userid == user_id:
                redirect(url('/logout'))
            redirect(url(controller='accounts', action='index'))
        else:
            flash_info(_('The account: %(a)s and all associated data'
                ' will be deleted, This action is not reversible.') %
                dict(a=user.username))
        c.fields = FORM_FIELDS
        c.id = userid
        return render('/accounts/delete.html')
Example #26
0
 def add_auth(self, domainid):
     "Add auth server"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     c.form = AddAuthForm(request.POST, csrf_context=session)
     if request.method == 'POST' and c.form.validate():
         server = AuthServer()
         server.from_form(c.form)
         try:
             create_auth(domain, server, c.user, request.host,
                         request.remote_addr)
             flash(_('The authentication settings have been created'))
             redirect(
                 url(controller='domains',
                     action='detail',
                     domainid=domain.id))
         except IntegrityError:
             Session.rollback()
             auth = dict(AUTH_PROTOCOLS)[str(server.protocol)]
             msg = _('The host %(dest)s already configured for %(auth)s '
                     'authentication for this domain') % \
                     dict(dest=server.address, auth=auth)
             flash_alert(msg)
             log.info(msg)
     c.domainid = domainid
     c.domainname = domain.name
     return self.render('/domains/addauth.html')
Example #27
0
    def command(self):
        "run command"
        self.init()
        if self.options.index_name is None:
            print "\nProvide an index to update\n"
            print self.parser.print_help()
            sys.exit(2)

        if self.options.index_name not in ['messages', 'archive']:
            print "\nProvide a valid index to update\n"
            print self.parser.print_help()
            sys.exit(2)
        if not os.path.exists('/usr/bin/indexer'):
            print "\nSphinx indexer is not installed\n"
            sys.exit(2)

        try:
            lockfile = os.path.join(self.conf['baruwa.locks.dir'],
                                    'updatedelta.lock')
            with open(lockfile, 'w+') as lock:
                fcntl.lockf(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
                update_index(self.conf['sphinx.url'],
                        self.options.index_name,
                        self.options.index_has_rt)
        except IOError:
            print >> sys.stderr, "Another instance is running."
            sys.exit(2)
        finally:
            Session.close()
Example #28
0
 def edit_auth(self, authid):
     "Edit auth server"
     server = self._get_authserver(authid)
     if not server:
         abort(404)
     c.form = AddAuthForm(request.POST, server, csrf_context=session)
     if request.method == 'POST' and c.form.validate():
         kwd = dict(domainid=server.domain_id)
         if auth_update_if_changed(c.form, server):
             try:
                 edit_auth(server, c.user, request.host,
                           request.remote_addr)
                 flash(_('The authentication settings have been updated'))
                 self.invalidate = 1
                 self._get_authserver(authid)
                 kwd['uc'] = 1
                 redirect(url('domain-detail', **kwd))
             except IntegrityError:
                 Session.rollback()
                 msg = _('The authentication settings update failed')
                 flash_alert(msg)
                 log.info(msg)
         else:
             msg = _('No changes were made to the authentication settings')
             flash_info(msg)
             log.info(msg)
             redirect(url('domain-detail', **kwd))
     c.domainid = server.domains.id
     c.domainname = server.domains.name
     c.authid = authid
     return self.render('/domains/editauth.html')
Example #29
0
def get_tagged_addrs(user):
    """Generate a list of tagged addresses for a user"""
    query1 = Session.query(Message.to_address)
    query2 = Session.query(Message.from_address)
    addrs = [addr.address for addr in user.addresses
            if '+*' not in addr.address and '-*' not in addr.address]
    addrs.append(user.email)
    tagged_addrs = [addr.address for addr in user.addresses
            if '+*' in addr.address or '-*' in addr.address]
    if tagged_addrs:
        tagged_opts1 = func._(or_(*[Message.to_address
                            .like(TAGGED_RE.sub(r'\g<one>%', taddr))
                        for taddr in tagged_addrs]))
        tagged_opts2 = func._(or_(*[Message.from_address
                            .like(TAGGED_RE.sub(r'\g<one>%', taddr))
                        for taddr in tagged_addrs]))
        query1 = query1.filter(func._(
                        or_(tagged_opts1, Message.to_address.in_(addrs))))
        query2 = query2.filter(func._(
                        or_(tagged_opts2, Message.from_address.in_(addrs))))
    else:
        query1 = query1.filter(Message.to_address.in_(addrs))
        query2 = query2.filter(Message.from_address.in_(addrs))
    query1 = query1.distinct()
    query2 = query2.distinct()
    to_addrs = [val.to_address for val in query1]
    from_addrs = [val.from_address for val in query2]
    all_addrs = set(to_addrs + from_addrs)
    return [str(crc32(val)) for val in all_addrs]
Example #30
0
    def addalias(self, domainid):
        "Add alias domain"
        domain = self._get_domain(domainid)
        if not domain:
            abort(404)

        c.form = AddDomainAlias(request.POST, csrf_context=session)
        c.form.domain.query = Session.query(Domain)\
                                    .filter(Domain.id == domainid)
        if request.method == 'POST' and c.form.validate():
            alias = DomainAlias()
            alias.from_form(c.form)
            try:
                create_alias(domain, alias, c.user, request.host,
                             request.remote_addr)
                flash(_('The domain alias: %s has been created') % alias.name)
                redirect(
                    url(controller='domains',
                        action='detail',
                        domainid=domain.id))
            except IntegrityError:
                Session.rollback()
                msg = _('The domain alias: %s already exists') % alias.name
                flash_alert(msg)
                log.info(msg)

        c.domainid = domain.id
        c.domainname = domain.name
        return self.render('/domains/addalias.html')
Example #31
0
def get_sig_data(sigtype):
    "Get signature data"
    usersql = """SELECT users.username, users.email, ''
                AS address  FROM users,
                user_signatures WHERE users.active = 't'
                AND users.id=user_signatures.user_id
                AND user_signatures.enabled='t' AND
                user_signatures.signature_type = :sigtype
                UNION
                SELECT users.username, users.email,
                addresses.address FROM users,addresses,
                user_signatures WHERE users.id=addresses.user_id
                AND users.id=user_signatures.user_id AND
                addresses.enabled='t' AND
                user_signatures.enabled='t' AND
                user_signatures.signature_type = :sigtype
                """
    domainsql = """SELECT name FROM alldomains,
                domain_signatures WHERE alldomains.id =
                domain_signatures.domain_id AND
                alldomains.status='t' AND
                domain_signatures.enabled='t' AND
                domain_signatures.signature_type = :sigtype
                """
    users = Session.execute(usersql, params=dict(sigtype=sigtype))
    domains = Session.execute(domainsql, params=dict(sigtype=sigtype))
    kwargs = dict(users=users, domains=domains)
    return kwargs
Example #32
0
    def editalias(self, aliasid):
        "Edit alias domain"
        alias = self._get_alias(aliasid)
        if not alias:
            abort(404)

        c.form = EditDomainAlias(request.POST, alias, csrf_context=session)
        c.form.domain.query = Session.query(Domain)\
                            .filter(Domain.id == alias.domain_id)
        if request.method == 'POST' and c.form.validate():
            if update_if_changed(c.form, alias):
                try:
                    edit_alias(alias, c.user, request.host,
                               request.remote_addr)
                    flash(
                        _('The domain alias: %s has been updated') %
                        alias.name)
                    redirect(url('domain-detail', domainid=alias.domain_id))
                except IntegrityError:
                    Session.rollback()
                    msg = _('The update failed')
                    flash_alert(msg)
                    log.info(msg)
            else:
                msg = _('No changes were made to the domain alias')
                flash_info(msg)
                log.info(msg)
                redirect(url('domain-detail', domainid=alias.domain_id))

        c.aliasid = aliasid
        c.domainid = alias.domain_id
        c.domainname = alias.domain.name
        return self.render('/domains/editalias.html')
Example #33
0
def create_language_based():
    "Generate file base language ruleset"
    domains = Session.query(Domain).filter(Domain.language != u'en').all()
    kwargs = dict(domains=domains)
    write_ruleset('languages.rules', kwargs)
    write_ruleset('rejectionreport.rules', kwargs)
    write_ruleset('deletedcontentmessage.rules', kwargs)
    write_ruleset('deletedfilenamemessage.rules', kwargs)
    write_ruleset('deletedvirusmessage.rules', kwargs)
    write_ruleset('deletedsizemessage.rules', kwargs)
    write_ruleset('storedcontentmessage.rules', kwargs)
    write_ruleset('storedfilenamemessage.rules', kwargs)
    write_ruleset('storedvirusmessage.rules', kwargs)
    write_ruleset('storedsizemessage.rules', kwargs)
    write_ruleset('disinfectedreport.rules', kwargs)
    write_ruleset('inlinewarninghtml.rules', kwargs)
    write_ruleset('inlinewarningtxt.rules', kwargs)
    write_ruleset('sendercontentreport.rules', kwargs)
    write_ruleset('sendererrorreport.rules', kwargs)
    write_ruleset('senderfilenamereport.rules', kwargs)
    write_ruleset('sendervirusreport.rules', kwargs)
    write_ruleset('sendersizereport.rules', kwargs)
    write_ruleset('senderspamreport.rules', kwargs)
    write_ruleset('senderspamrblreport.rules', kwargs)
    write_ruleset('senderspamsareport.rules', kwargs)
    write_ruleset('inlinespamwarning.rules', kwargs)
    write_ruleset('recipientspamreport.rules', kwargs)
    Session.close()
Example #34
0
 def command(self):
     "run command"
     self.init()
     if self.options.username is None:
         print "\nProvide an username\n"
         print self.parser.print_help()
         sys.exit(2)
     try:
         user = Session\
                 .query(User)\
                 .filter(User.username == self.options.username)\
                 .filter(User.local == True)\
                 .one()
         pass1 = getpass.getpass(prompt="Please enter the password:"******"Please reenter the password:"******"Passwords cannot be blank"
         assert pass1 == pass2, "Passwords entered do not match"
         cracklib.VeryFascistCheck(pass1)
         user.set_password(pass1)
         Session.add(user)
         Session.commit()
         print "The account password has been updated"
     except NoResultFound:
         print >> sys.stderr, ("No local user found with username %s" %
                                 self.options.username)
     except AssertionError, message:
         print >> sys.stderr, str(message)
Example #35
0
    def command(self):
        "run command"
        self.init()
        if self.options.username is None:
            print >> sys.stderr, "\nProvide an username\n"
            print self.parser.print_help()
            sys.exit(126)

        try:
            user = Session\
                    .query(User)\
                    .filter(User.username == self.options.username)\
                    .filter(User.local == true())\
                    .one()
            if user.validate_password(os.environ['BARUWA_ADMIN_PASSWD']):
                print >> sys.stderr, "The account password is valid"
                sys.exit(0)
            else:
                print >> sys.stderr, "The account password is invalid"
                sys.exit(2)
        except KeyError:
            print >> sys.stderr, "BARUWA_ADMIN_PASSWD env variable not set"
            sys.exit(126)
        except NoResultFound:
            print >> sys.stderr, ("No local user found with username %s" %
                                  self.options.username)
            sys.exit(126)
        finally:
            Session.close()
Example #36
0
 def pwchange(self, userid):
     """Reset a user password"""
     user = self._get_user(userid)
     if not user:
         abort(404)
     c.form = ChangePasswordForm(request.POST, csrf_context=session)
     if request.POST and c.form.validate():
         if user.local:
             user.set_password(c.form.password1.data)
             Session.add(user)
             Session.commit()
             flash(
                 _('The account password for %(name)s has been reset') %
                 dict(name=user.username))
             info = PASSWORDCHANGE_MSG % dict(u=user.username)
             audit_log(c.user.username, 2, info, request.host,
                       request.remote_addr, now())
         else:
             flash(
                 _('This is an external account, use'
                   ' external system to reset the password'))
         redirect(url('account-detail', userid=user.id))
     c.id = userid
     c.username = user.username
     c.posturl = 'accounts-pw-change'
     return render('/accounts/pwchange.html')
Example #37
0
 def evaluate(self, environ, credentials):
     "Evaluate"
     identity = environ.get('repoze.who.identity')
     user = identity['user']
     if not user.is_superadmin or not user.active:
         try:
             varbs = self.parse_variables(environ)
             if 'domainid' in varbs['named_args']:
                 domainid = varbs['named_args'].get('domainid')
             if 'destinationid' in varbs['named_args']:
                 destinationid = varbs['named_args'].get('destinationid')
                 dest = Session.query(DeliveryServer.domain_id)\
                             .filter(DeliveryServer.id == destinationid)\
                             .one()
                 domainid = dest.domain_id
             if 'authid' in varbs['named_args']:
                 authid = varbs['named_args'].get('authid')
                 authsvr = Session.query(AuthServer.domain_id)\
                             .filter(AuthServer.id == authid).one()
                 domainid = authsvr.domain_id
             if 'sigid' in varbs['named_args']:
                 sigid = varbs['named_args'].get('sigid')
                 sig = Session.query(DomSignature.domain_id)\
                         .filter(DomSignature.id == sigid).one()
                 domainid = sig.domain_id
             if not check_domain_ownership(user.id, domainid):
                 self.unmet()
         except NoResultFound:
             self.unmet()
Example #38
0
 def upwchange(self, userid):
     """User change own password"""
     user = self._get_user(userid)
     if not user:
         abort(404)
     if user.id != c.user.id or c.user.is_superadmin:
         abort(403)
     c.form = UserPasswordForm(request.POST, csrf_context=session)
     if (request.POST and c.form.validate()
             and user.validate_password(c.form.password3.data)):
         if user.local:
             user.set_password(c.form.password1.data)
             Session.add(user)
             Session.commit()
             flash(
                 _('The account password for %(name)s has been reset') %
                 dict(name=user.username))
             info = PASSWORDCHANGE_MSG % dict(u=user.username)
             audit_log(c.user.username, 2, info, request.host,
                       request.remote_addr, now())
         else:
             flash(
                 _('This is an external account, use'
                   ' external system to reset the password'))
         redirect(url('account-detail', userid=user.id))
     elif (request.POST
           and not user.validate_password(c.form.password3.data)
           and not c.form.password3.errors):
         flash_alert(
             _('The old password supplied does'
               ' not match our records'))
     c.id = userid
     c.username = user.username
     c.posturl = 'accounts-pw-uchange'
     return render('/accounts/pwchange.html')
Example #39
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)
Example #40
0
    def delete(self, userid):
        """/accounts/delete/id"""
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = EditUserForm(request.POST, user, csrf_context=session)
        c.form.domains.query = Session.query(Domain)
        if request.POST and c.form.validate():
            username = user.username
            Session.delete(user)
            Session.commit()
            update_serial.delay()
            flash(_('The account has been deleted'))
            info = DELETEACCOUNT_MSG % dict(u=username)
            audit_log(c.user.username, 4, info, request.host,
                      request.remote_addr, now())
            if userid == c.user.id:
                redirect(url('/logout'))
            redirect(url(controller='accounts', action='index'))
        else:
            flash_info(
                _('The account: %(a)s and all associated data'
                  ' will be deleted, This action is not reversible.') %
                dict(a=user.username))
        c.fields = FORM_FIELDS
        c.id = userid
        return render('/accounts/delete.html')
Example #41
0
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        def check_url():
            "check if user should have totals calculated"
            if ('format' in environ['pylons.routes_dict'] and
                environ['pylons.routes_dict']['format'] in ['csv', 'pdf']):
                return False
            if environ['PATH_INFO'] == '/jsi18n.js':
                return False
            return True

        self.identity = environ.get('repoze.who.identity')
        if (self.identity is not None and 'user' in self.identity and
            environ['pylons.routes_dict']['controller'] != 'error' and
            check_url()):

            if self.identity['user']:
                totals = DailyTotals(Session, self.identity['user'])
                mailq = MailQueue(Session, self.identity['user'])
                c.baruwa_totals = totals.get()
                c.baruwa_inbound = mailq.get(1)[0]
                c.baruwa_outbound = mailq.get(2)[0]
                if self.identity['user'].is_admin:
                    c.baruwa_status = cluster_status()

                tzinfo = self.identity['user'].timezone or UTC
                c.tzinfo = make_tz(tzinfo)
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()
Example #42
0
def create_ldap_domains():
    """Generate LDAP domains"""
    sql = """SELECT name AS key, name AS value FROM
            mtasettings WHERE ldap_callout='t'"""
    domains = Session.execute(sql)
    generate_cdb_file(domains, 'ldapdomains.cdb')
    Session.close()
Example #43
0
def update_queue_stats(hostname):
    "Update queue stats"
    inqdir = get_config_option('IncomingQueueDir')
    outqdir = get_config_option('OutgoingQueueDir')

    allids, inqueue = process_queue(inqdir, 1)
    tmpids, outqueue = process_queue(outqdir, 2)
    allids.extend(tmpids)

    dbids = [item.messageid
            for item in Session.query(MailQueueItem.messageid)\
                                .filter(MailQueueItem.hostname == hostname)\
                                .all()]
    remids = [item for item in dbids if not item in allids]
    preids = [item for item in dbids if not item in remids]

    if remids:
        print >> sys.stderr, ("== Deleting %(items)d queue "
                "items from DB ==" % dict(items=len(remids)))
        Session.query(MailQueueItem)\
                .filter(MailQueueItem.messageid.in_(remids))\
                .delete(synchronize_session='fetch')
        Session.commit()

    populate_db(inqueue, inqdir, 1, preids)
    populate_db(outqueue, outqdir, 2, preids)
Example #44
0
def create_callback_domains():
    """Generate SMTP callback domains"""
    sql = """SELECT name AS key, name AS value FROM
            mtasettings WHERE smtp_callout='t'"""
    domains = Session.execute(sql)
    generate_cdb_file(domains, 'cbdomains.cdb')
    Session.close()
Example #45
0
 def deletedestination(self, destinationid):
     "Delete destination server"
     server = self._get_server(destinationid)
     if not server:
         abort(404)
     c.form = AddDeliveryServerForm(request.POST,
                                    server,
                                    csrf_context=session)
     if request.POST and c.form.validate():
         name = server.domains.name
         server_addr = server.address
         domainid = server.domain_id
         Session.delete(server)
         Session.commit()
         flash(_('The destination server has been deleted'))
         info = DELETEDELSVR_MSG % dict(d=name, ds=server_addr)
         audit_log(c.user.username, 4, info, request.host,
                   request.remote_addr, now())
         redirect(url('domain-detail', domainid=domainid))
     else:
         flash(
             _('The destination server: %(s)s will be deleted,'
               ' This action is not reversible') % dict(s=server.address))
     c.id = destinationid
     c.domainid = server.domain_id
     return render('/domains/deletedestination.html')
Example #46
0
def create_post_smtp_av():
    """Create post smtp av domains"""
    sql = """SELECT name AS key, '1' AS value FROM
            alldomains WHERE virus_checks_at_smtp='f'"""
    domains = Session.execute(sql)
    generate_cdb_file(domains, 'postsmtpav.cdb')
    Session.close()
Example #47
0
    def deletealias(self, aliasid):
        "Delete alias domain"
        alias = self._get_alias(aliasid)
        if not alias:
            abort(404)

        c.form = AddDomainAlias(request.POST, alias, csrf_context=session)
        c.form.domain.query = Session.query(Domain)\
                            .filter(Domain.id==alias.domain_id)
        if request.POST and c.form.validate():
            domainid = alias.domain_id
            aliasname = alias.name
            Session.delete(alias)
            Session.commit()
            update_serial.delay()
            info = DELETEDOMALIAS_MSG % dict(d=aliasname)
            audit_log(c.user.username, 4, info, request.host,
                      request.remote_addr, now())
            flash(_('The domain alias: %s has been deleted') % aliasname)
            redirect(url('domain-detail', domainid=domainid))

        c.aliasid = aliasid
        c.domainid = alias.domain_id
        c.domainname = alias.domain.name
        return render('/domains/deletealias.html')
Example #48
0
def create_av_disabled():
    """Create AV checks disabled domains"""
    sql = """SELECT name AS key, '1' AS value FROM
            alldomains WHERE virus_checks='f'"""
    domains = Session.execute(sql)
    generate_cdb_file(domains, 'avdisabled.cdb')
    Session.close()
Example #49
0
 def upwchange(self, userid):
     """User change own password"""
     user = self._get_user(userid)
     if not user:
         abort(404)
     if user.id != c.user.id or c.user.is_superadmin:
         abort(403)
     c.form = UserPasswordForm(request.POST, csrf_context=session)
     if (request.POST and c.form.validate() and
         user.validate_password(c.form.password3.data)):
         if user.local:
             user.set_password(c.form.password1.data)
             Session.add(user)
             Session.commit()
             flash(_('The account password for %(name)s has been reset')
                 % dict(name=user.username))
             info = PASSWORDCHANGE_MSG % dict(u=user.username)
             audit_log(c.user.username,
                     2, unicode(info), request.host,
                     request.remote_addr, now())
         else:
             flash(_('This is an external account, use'
                 ' external system to reset the password'))
         redirect(url('account-detail', userid=user.id))
     elif (request.POST and not
         user.validate_password(c.form.password3.data)
         and not c.form.password3.errors):
         flash_alert(_('The old password supplied does'
                     ' not match our records'))
     c.id = userid
     c.username = user.username
     c.posturl = 'accounts-pw-uchange'
     return render('/accounts/pwchange.html')
Example #50
0
    def command(self):
        "command"
        self.init()

        if acquire_lock('dbclean', self.conf):
            try:
                if self.options.days > 0:
                    days = self.options.days
                else:
                    days = int(self.conf.get('baruwa.messages.keep.days', 30))
                if self.options.adays > 0:
                    adays = self.options.adays
                else:
                    adays = int(self.conf.get('baruwa.archive.keep.days', 90))

                interval = datetime.timedelta(days=days)
                archive_interval = datetime.timedelta(days=adays)
                current_date = arrow.utcnow().datetime
                msgs_date = current_date - interval
                last_achive_date = current_date - archive_interval
                releases_date = current_date - datetime.timedelta(days=2)
                # process messages table
                process_messages(msgs_date)
                # process archive table
                prune_archive(last_achive_date)
                # process message status table
                prune_table('messagestatus', last_achive_date)
                # process releases table
                prune_table('releases', releases_date)
                # process awl table
                prune_table('awl', msgs_date)
            finally:
                Session.close()
                release_lock('dbclean', self.conf)
Example #51
0
    def edit(self, userid):
        """GET /accounts/edit/id: Form to edit an existing item"""
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = user_update_form(user, c.user, request.POST, session)
        if request.method == 'POST' and c.form.validate():
            kwd = dict(userid=user.id)
            if update_changed(c.form, FORM_FIELDS, user):
                try:
                    update_user(user, c.user, request.host,
                                request.remote_addr)
                    flash(_('The account has been updated'))
                    kwd['uc'] = 1
                except IntegrityError:
                    Session.rollback()
                    flash_alert(
                        _('The account: %(acc)s could not be updated') %
                        dict(acc=user.username))
                if (user.id == c.user.id and c.form.active
                        and c.form.active.data is False):
                    redirect(url('/logout'))
            else:
                flash_info(_('No changes made to the account'))
            redirect(url(controller='accounts', action='detail', **kwd))
        c.fields = FORM_FIELDS
        c.id = userid
        return self.render('/accounts/edit.html')
Example #52
0
    def edit(self, orgid):
        "Edit an organization"
        org = get_org(orgid)
        if not org:
            abort(404)

        c.id = org.id
        c.form = org_add_form(request.POST, session, org)
        if request.method == 'POST' and c.form.validate():
            if update_if_changed(c.form, org):
                try:
                    edit_org(org, c.user, request.host, request.remote_addr)
                    msg = _('The organization has been updated')
                    flash(msg)
                    log.info(msg)
                except IntegrityError:
                    Session.rollback()
                    msg = _('The organization could not be updated')
                    flash(msg)
                    log.info(msg)
            else:
                msg = _('No changes made, Organization not updated')
                flash_info(msg)
                log.info(msg)
            redirect(url(controller='organizations'))
        return self.render('/organizations/edit.html')
Example #53
0
    def editaddress(self, addressid):
        "Edit address"
        address = get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            try:
                if (address.address != c.form.address.data
                        or address.enabled != c.form.enabled.data):
                    update_address(c.form, address, c.user, request.host,
                                   request.remote_addr)
                    flash(_('The alias address has been updated'))
                else:
                    flash_info(_('No changes were made to the address'))
            except IntegrityError:
                Session.rollback()
                msg = _('The address %(addr)s already exists') % \
                        dict(addr=c.form.address.data)
                flash_alert(msg)
                log.info(msg)
            except NoResultFound:
                domain = c.form.address.data.split('@')[1]
                msg = _('Domain: %(d)s does not belong to you') % \
                        dict(d=domain)
                flash(msg)
                log.info(msg)
            redirect(
                url(controller='accounts',
                    action='detail',
                    userid=address.user_id))
        c.id = addressid
        c.userid = address.user_id
        return self.render('/accounts/editaddress.html')
Example #54
0
    def edit_relay(self, settingid):
        "Edit a mail relay"
        relay = get_relay(settingid)
        if not relay:
            abort(404)

        c.relayname = relay.address or relay.username
        c.relayid = relay.id
        c.orgid = relay.org_id
        c.form = RelayEditForm(request.POST, relay, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            if relay_update_if_changed(c.form, relay):
                try:
                    edit_relay(relay, c.user, request.host,
                                request.remote_addr)
                    msg = _('The outbound settings have been updated')
                    flash(msg)
                    log.info(msg)
                except IntegrityError:
                    Session.rollback()
                    msg = _('The outbound settings could not be updated')
                    flash(msg)
                    log.info(msg)
            else:
                msg = _('No changes made, The outbound settings not updated')
                flash(msg)
                log.info(msg)
            redirect(url('org-detail', orgid=relay.org_id))
        return self.render('/organizations/editrelay.html')
Example #55
0
def update_index(sphinx_url, index, has_rt):
    "Update Sphinx index"
    sql_temp = """SELECT set_var('maxts',
                (SELECT maxts FROM indexer_counters
                WHERE tablename='messages_delta'));
                UPDATE indexer_counters
                SET maxts=get_var('maxts')
                WHERE tablename='%s';"""

    main_index = index
    delta_index = '%sdelta' % index
    indexer_cmd = ['/usr/bin/indexer', '--rotate', '--merge',
                    main_index, delta_index]
    pipe = subprocess.Popen(indexer_cmd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    _, stderr = pipe.communicate()
    pipe.wait()
    if pipe.returncode == 0:
        sql = text(sql_temp % main_index)
        Session.execute(sql, params={})
        Session.commit()
        delta_index_cmd = ['/usr/bin/indexer', '--rotate', delta_index]
        pipe = subprocess.Popen(delta_index_cmd,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        _, stderr = pipe.communicate()
        pipe.wait()
        if has_rt:
            update_rt_index(index, sphinx_url)
    else:
        print >> sys.stderr, stderr
Example #56
0
    def addalias(self, domainid):
        "Add alias domain"
        domain = self._get_domain(domainid)
        if not domain:
            abort(404)

        c.form = AddDomainAlias(request.POST, csrf_context=session)
        c.form.domain.query = Session.query(Domain)\
                                    .filter(Domain.id == domainid)
        if request.method == 'POST' and c.form.validate():
            alias = DomainAlias()
            alias.from_form(c.form)
            try:
                create_alias(domain, alias, c.user,
                            request.host, request.remote_addr)
                flash(_('The domain alias: %s has been created') % alias.name)
                redirect(url(controller='domains', action='detail',
                        domainid=domain.id))
            except IntegrityError:
                Session.rollback()
                msg = _('The domain alias: %s already exists') % alias.name
                flash_alert(msg)
                log.info(msg)

        c.domainid = domain.id
        c.domainname = domain.name
        return self.render('/domains/addalias.html')