Пример #1
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')
Пример #2
0
    def add(self, orgid=None):
        "Add a domain"
        c.form = AddDomainForm(request.POST, csrf_context=session)
        c.form.organizations.query = self._get_organizations(orgid)
        if request.POST and c.form.validate():
            try:
                domain = Domain()
                for field in c.form:
                    if field.name != 'csrf_token':
                        setattr(domain, field.name, field.data)
                Session.add(domain)
                Session.commit()
                update_serial.delay()
                info = ADDDOMAIN_MSG % dict(d=domain.name)
                audit_log(c.user.username, 3, info, request.host,
                          request.remote_addr, now())
                flash(
                    _('The domain: %(dom)s has been created') %
                    dict(dom=domain.name))
                redirect(url(controller='domains'))
            except IntegrityError:
                Session.rollback()
                flash_alert(
                    _('The domain name %(dom)s already exists') %
                    dict(dom=domain.name))

        return render('/domains/new.html')
Пример #3
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')
Пример #4
0
    def add(self, orgid=None):
        "Add a domain"
        c.form = AddDomainForm(request.POST, csrf_context=session)
        c.form.organizations.query = self._get_organizations(orgid)
        if request.POST and c.form.validate():
            try:
                domain = Domain()
                for field in c.form:
                    if field.name != 'csrf_token':
                        setattr(domain, field.name, field.data)
                Session.add(domain)
                Session.commit()
                update_serial.delay()
                info = ADDDOMAIN_MSG % dict(d=domain.name)
                audit_log(c.user.username,
                        3, unicode(info), request.host,
                        request.remote_addr, now())
                flash(_('The domain: %(dom)s has been created') %
                    dict(dom=domain.name))
                redirect(url(controller='domains'))
            except IntegrityError:
                Session.rollback()
                flash_alert(_('The domain name %(dom)s already exists') %
                    dict(dom=domain.name))

        return render('/domains/new.html')
Пример #5
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.POST and c.form.validate():
            updated = False
            for field in c.form:
                if field.name != "csrf_token" and field.data != getattr(alias, field.name):
                    setattr(alias, field.name, field.data)
                    updated = True
            if updated:
                try:
                    Session.add(alias)
                    Session.commit()
                    update_serial.delay()
                    info = UPDATEDOMALIAS_MSG % dict(d=alias.name)
                    audit_log(c.user.username, 2, info, request.host, request.remote_addr, datetime.now())
                    flash(_("The domain alias: %s has been updated") % alias.name)
                    redirect(url("domain-detail", domainid=alias.domain_id))
                except IntegrityError:
                    Session.rollback()
                    flash_alert(_("The update failed"))
            else:
                flash_info(_("No changes were made to the domain alias"))
                redirect(url("domain-detail", domainid=alias.domain_id))

        c.aliasid = aliasid
        c.domainid = alias.domain_id
        c.domainname = alias.domain.name
        return render("/domains/editalias.html")
Пример #6
0
    def edit_server(self, serverid):
        "Edit scan server"
        server = self._get_server(serverid)
        if not server:
            abort(404)

        c.form = ServerForm(request.POST, server, csrf_context=session)
        c.id = server.id
        if request.POST and c.form.validate():
            if (server.hostname != c.form.hostname.data
                    or server.enabled != c.form.enabled.data):
                try:
                    server.hostname = c.form.hostname.data
                    server.enabled = c.form.enabled.data
                    Session.add(server)
                    Session.commit()
                    update_serial.delay()
                    info = HOSTUPDATE_MSG % dict(n=server.hostname)
                    audit_log(c.user.username, 2, info, request.host,
                              request.remote_addr, now())
                    flash(_('The scanning server has been updated'))
                except IntegrityError:
                    Session.rollback()
                    flash(_('Update of server failed'))
            else:
                flash_info(_('No changes were made to the server'))
            redirect(url(controller='settings'))
        return render('/settings/editserver.html')
Пример #7
0
    def edit_server(self, serverid):
        "Edit scan server"
        server = self._get_server(serverid)
        if not server:
            abort(404)

        c.form = ServerForm(request.POST, server, csrf_context=session)
        c.id = server.id
        if request.POST and c.form.validate():
            if (server.hostname != c.form.hostname.data or
                server.enabled != c.form.enabled.data):
                try:
                    server.hostname = c.form.hostname.data
                    server.enabled = c.form.enabled.data
                    Session.add(server)
                    Session.commit()
                    update_serial.delay()
                    info = HOSTUPDATE_MSG % dict(n=server.hostname)
                    audit_log(c.user.username,
                            2, info, request.host,
                            request.remote_addr, datetime.now())
                    flash(_('The scanning server has been updated'))
                except IntegrityError:
                    Session.rollback()
                    flash(_('Update of server failed'))
            else:
                flash_info(_('No changes were made to the server'))
            redirect(url(controller='settings'))
        return render('/settings/editserver.html')
Пример #8
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.POST and c.form.validate():
            alias = DomainAlias()
            for field in c.form:
                if field.data and field.name != "csrf_token":
                    setattr(alias, field.name, field.data)
            try:
                domain.aliases.append(alias)
                Session.add(alias)
                Session.add(domain)
                Session.commit()
                update_serial.delay()
                info = ADDDOMALIAS_MSG % dict(d=alias.name)
                audit_log(c.user.username, 3, info, request.host, request.remote_addr, datetime.now())
                flash(_("The domain alias: %s has been created") % alias.name)
                redirect(url(controller="domains", action="detail", domainid=domain.id))
            except IntegrityError:
                Session.rollback()
                flash_alert(_("The domain alias: %s already exists") % alias.name)

        c.domainid = domain.id
        c.domainname = domain.name
        return render("/domains/addalias.html")
Пример #9
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')
Пример #10
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')
Пример #11
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 = EditUserForm(request.POST, user, csrf_context=session)
        c.form.domains.query = Session.query(Domain)
        if c.user.is_domain_admin:
            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)

        if user.account_type != 3 or c.user.is_peleb:
            del c.form.domains
        if c.user.is_peleb:
            del c.form.username
            del c.form.email
            del c.form.active

        if request.POST and c.form.validate():
            update = False
            kwd = dict(userid=userid)
            for attr in FORM_FIELDS:
                field = getattr(c.form, attr)
                if field and field.data != getattr(user, attr):
                    setattr(user, attr, field.data)
                    update = True
            if update:
                try:
                    Session.add(user)
                    Session.commit()
                    update_serial.delay()
                    flash(_('The account has been updated'))
                    kwd['uc'] = 1
                    info = UPDATEACCOUNT_MSG % dict(u=user.username)
                    audit_log(c.user.username,
                            2, unicode(info), request.host,
                            request.remote_addr, now())
                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 == 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 render('/accounts/edit.html')
Пример #12
0
    def import_status(self, taskid):
        "import domains status"
        result = AsyncResult(taskid)
        if result is None or taskid not in session['taskids']:
            msg = _('The task status requested has expired or does not exist')
            flash(msg)
            log.info(msg)
            redirect(url(controller='organizations', action='index'))

        if result.ready():
            finished = True
            flash.pop_messages()
            if isinstance(result.result, Exception):
                msg = _('Error occured in processing %s') % result.result
                if c.user.is_superadmin:
                    flash_alert(msg)
                    log.info(msg)
                else:
                    flash_alert(_('Backend error occured during processing.'))
                    log.info(msg)
                redirect(url(controller='organizations'))
            update_serial.delay()
            info = auditmsgs.IMPORTORG_MSG % dict(o='-')
            audit_log(c.user.username, 3, unicode(info), request.host,
                      request.remote_addr,
                      arrow.utcnow().datetime)
        else:
            session['dimport-counter'] += 1
            session.save()
            if (session['dimport-counter'] >= 10
                    and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                try:
                    os.unlink(session['dimport-file'])
                except OSError:
                    pass
                del session['dimport-file']
                del session['dimport-counter']
                session.save()
                flash_alert(
                    _('The import could not be processed,'
                      ' try again later'))
                redirect(url(controller='organizations'))
            finished = False

        c.finished = finished
        c.results = result.result
        c.success = result.successful()
        return self.render('/organizations/importstatus.html')
Пример #13
0
    def import_status(self, taskid):
        "import domains status"
        result = AsyncResult(taskid)
        if result is None or taskid not in session['taskids']:
            msg = _('The task status requested has expired or does not exist')
            flash(msg)
            log.info(msg)
            redirect(url(controller='organizations', action='index'))

        if result.ready():
            finished = True
            flash.pop_messages()
            if isinstance(result.result, Exception):
                msg = _('Error occured in processing %s') % result.result
                if c.user.is_superadmin:
                    flash_alert(msg)
                    log.info(msg)
                else:
                    flash_alert(_('Backend error occured during processing.'))
                    log.info(msg)
                redirect(url(controller='organizations'))
            update_serial.delay()
            info = auditmsgs.IMPORTORG_MSG % dict(o='-')
            audit_log(c.user.username,
                    3, unicode(info), request.host,
                    request.remote_addr, arrow.utcnow().datetime)
        else:
            session['dimport-counter'] += 1
            session.save()
            if (session['dimport-counter'] >= 10 and
                result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                try:
                    os.unlink(session['dimport-file'])
                except OSError:
                    pass
                del session['dimport-file']
                del session['dimport-counter']
                session.save()
                flash_alert(_('The import could not be processed,'
                            ' try again later'))
                redirect(url(controller='organizations'))
            finished = False

        c.finished = finished
        c.results = result.result
        c.success = result.successful()
        return self.render('/organizations/importstatus.html')
Пример #14
0
    def editaddress(self, addressid):
        "Edit address"
        address = self._get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.POST and c.form.validate():
            try:
                if (address.address != c.form.address.data
                        or address.enabled != c.form.enabled.data):
                    if c.user.is_domain_admin:
                        # check if they own the domain
                        domain = c.form.address.data.split('@')[1]
                        domain = Session.query(Domain).options(
                                    joinedload('organizations')).join(
                                    dom_owns, (oas,
                                    dom_owns.c.organization_id ==
                                    oas.c.organization_id))\
                                    .filter(oas.c.user_id == c.user.id)\
                                    .filter(Domain.name == domain).one()
                    address.address = c.form.address.data
                    address.enabled = c.form.enabled.data
                    Session.add(address)
                    Session.commit()
                    update_serial.delay()
                    info = ADDRUPDATE_MSG % dict(a=address.address,
                                                 ac=address.user.username)
                    audit_log(c.user.username, 2, info, request.host,
                              request.remote_addr, now())
                    flash(_('The alias address has been updated'))
                else:
                    flash_info(_('No changes were made to the address'))
            except IntegrityError:
                flash_alert(
                    _('The address %(addr)s already exists') %
                    dict(addr=c.form.address.data))
            except NoResultFound:
                flash(
                    _('Domain: %(d)s does not belong to you') % dict(d=domain))
            redirect(
                url(controller='accounts',
                    action='detail',
                    userid=address.user_id))
        c.id = addressid
        c.userid = address.user_id
        return render('/accounts/editaddress.html')
Пример #15
0
 def edit(self, domainid):
     "Edit a domain"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     c.form = AddDomainForm(request.POST, domain, csrf_context=session)
     if c.user.is_superadmin:
         c.form.organizations.query_factory = self._get_organizations
     else:
         del c.form.organizations
     c.id = domainid
     if request.POST and c.form.validate():
         updated = False
         kw = {'domainid': domain.id}
         for field in c.form:
             intfields = [
                 'spam_actions', 'highspam_actions', 'delivery_mode',
                 'report_every'
             ]
             if (field.name in intfields
                     and int(field.data) == getattr(domain, field.name)):
                 continue
             if (field.name != 'csrf_token'
                     and field.data != getattr(domain, field.name)):
                 setattr(domain, field.name, field.data)
                 updated = True
         if updated:
             try:
                 Session.add(domain)
                 Session.commit()
                 update_serial.delay()
                 info = UPDATEDOMAIN_MSG % dict(d=domain.name)
                 audit_log(c.user.username, 2, info, request.host,
                           request.remote_addr, now())
                 flash(
                     _('The domain: %(dom)s has been updated') %
                     dict(dom=domain.name))
                 kw['uc'] = 1
             except IntegrityError:
                 Session.rollback()
                 flash(
                     _('The domain %(dom)s could not be updated') %
                     dict(dom=domain.name))
         else:
             flash_info(_('No changes were made to the domain'))
         redirect(url('domain-detail', **kw))
     return render('/domains/edit.html')
Пример #16
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 = EditUserForm(request.POST, user, csrf_context=session)
        c.form.domains.query = Session.query(Domain)
        if user.account_type != 3 or c.user.is_peleb:
            del c.form.domains
        if c.user.is_peleb:
            del c.form.username
            del c.form.email
            del c.form.active
        if request.POST and c.form.validate():
            update = False
            kwd = dict(userid=userid)
            for attr in FORM_FIELDS:
                field = getattr(c.form, attr)
                if field and field.data != getattr(user, attr):
                    setattr(user, attr, field.data)
                    update = True
            if update:
                try:
                    Session.add(user)
                    Session.commit()
                    update_serial.delay()
                    flash(_('The account has been updated'))
                    kwd['uc'] = 1
                    info = UPDATEACCOUNT_MSG % dict(u=user.username)
                    audit_log(c.user.username, 2, info, request.host,
                              request.remote_addr, now())
                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 == 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 render('/accounts/edit.html')
Пример #17
0
    def editaddress(self, addressid):
        "Edit address"
        address = self._get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.POST and c.form.validate():
            try:
                if (address.address != c.form.address.data or
                    address.enabled != c.form.enabled.data):
                    if c.user.is_domain_admin:
                        # check if they own the domain
                        domain = c.form.address.data.split('@')[1]
                        domain = Session.query(Domain).options(
                                    joinedload('organizations')).join(
                                    dom_owns, (oas,
                                    dom_owns.c.organization_id ==
                                    oas.c.organization_id))\
                                    .filter(oas.c.user_id == c.user.id)\
                                    .filter(Domain.name == domain).one()
                    address.address = c.form.address.data
                    address.enabled = c.form.enabled.data
                    Session.add(address)
                    Session.commit()
                    update_serial.delay()
                    info = ADDRUPDATE_MSG % dict(a=address.address,
                                                ac=address.user.username)
                    audit_log(c.user.username,
                            2, unicode(info), request.host,
                            request.remote_addr, now())
                    flash(_('The alias address has been updated'))
                else:
                    flash_info(_('No changes were made to the address'))
            except IntegrityError:
                Session.rollback()
                flash_alert(_('The address %(addr)s already exists') %
                dict(addr=c.form.address.data))
            except NoResultFound:
                flash(_('Domain: %(d)s does not belong to you') %
                    dict(d=domain))
            redirect(url(controller='accounts', action='detail',
            userid=address.user_id))
        c.id = addressid
        c.userid = address.user_id
        return render('/accounts/editaddress.html')
Пример #18
0
 def edit(self, domainid):
     "Edit a domain"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     c.form = EditDomainForm(request.POST, domain, csrf_context=session)
     if c.user.is_superadmin:
         c.form.organizations.query_factory = self._get_organizations
     else:
         del c.form.organizations
     c.id = domainid
     if request.POST and c.form.validate():
         updated = False
         kw = {'domainid': domain.id}
         for field in c.form:
             intfields = ['spam_actions', 'highspam_actions',
                         'delivery_mode', 'report_every']
             if (field.name in intfields and
                 int(field.data) == getattr(domain, field.name)):
                 continue
             if (field.name != 'csrf_token' and
                 field.data != getattr(domain, field.name)):
                 setattr(domain, field.name, field.data)
                 updated = True
         if updated:
             try:
                 Session.add(domain)
                 Session.commit()
                 update_serial.delay()
                 info = UPDATEDOMAIN_MSG % dict(d=domain.name)
                 audit_log(c.user.username,
                         2, unicode(info), request.host,
                         request.remote_addr, now())
                 flash(_('The domain: %(dom)s has been updated') %
                     dict(dom=domain.name))
                 kw['uc'] = 1
             except IntegrityError:
                 Session.rollback()
                 flash(_('The domain %(dom)s could not be updated') %
                     dict(dom=domain.name))
         else:
             flash_info(_('No changes were made to the domain'))
         redirect(url('domain-detail', **kw))
     return render('/domains/edit.html')
Пример #19
0
    def list_delete(self, listid):
        "Delete a list item"
        item = self._get_listitem(listid)
        if not item:
            abort(404)

        if c.user.account_type != 1 and c.user.id != item.user_id:
            abort(403)

        c.form = list_forms[c.user.account_type](request.POST,
                                                item,
                                                csrf_context=session)
        if not c.user.is_superadmin:
            del c.form.add_to_alias
        if c.user.is_domain_admin:
            orgs = [group.id for group in c.user.organizations]
            query = Session.query(Domain.name).join(domain_owners)\
                    .filter(domain_owners.c.organization_id.in_(orgs))
            options = [(domain.name, domain.name) for domain in query]
            c.form.to_domain.choices = options
        if c.user.is_peleb:
            query = self._user_addresses()
            options = [(addr.email, addr.email) for addr in query]
            c.form.to_address.choices = options
        c.id = item.id
        if request.POST and c.form.validate():
            if item.list_type == 1:
                listname = _('Approved senders')
            else:
                listname = _('Banned senders')
            name = item.from_address
            Session.delete(item)
            Session.commit()
            update_serial.delay()
            info = LISTDEL_MSG % dict(s=name, l=listname)
            audit_log(c.user.username,
                    4, info, request.host,
                    request.remote_addr, datetime.now())
            flash(_('The item has been deleted'))
            if not request.is_xhr:
                redirect(url(controller='lists'))
            else:
                c.delflag = True
        return render('/lists/delete.html')
Пример #20
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.POST and c.form.validate():
            try:
                if c.user.is_domain_admin:
                    # check if they own the domain
                    domain = c.form.address.data.split('@')[1]
                    domain = Session.query(Domain).options(
                                joinedload('organizations')).join(
                                dom_owns, (oas,
                                dom_owns.c.organization_id ==
                                oas.c.organization_id))\
                                .filter(oas.c.user_id == c.user.id)\
                                .filter(Domain.name == domain).one()
                addr = Address(address=c.form.address.data)
                addr.enabled = c.form.enabled.data
                addr.user = user
                Session.add(addr)
                Session.commit()
                update_serial.delay()
                info = ADDRADD_MSG % dict(a=addr.address, ac=user.username)
                audit_log(c.user.username,
                        3, unicode(info), request.host,
                        request.remote_addr, now())
                flash(
                _('The alias address %(address)s was successfully created.' %
                dict(address=addr.address)))
            except IntegrityError:
                Session.rollback()
                flash_alert(_('The address %(addr)s already exists') %
                dict(addr=addr.address))
            except NoResultFound:
                flash(_('Domain: %(d)s does not belong to you') %
                    dict(d=domain))
            redirect(url(controller='accounts', action='detail',
                    userid=userid))
        c.id = userid
        return render('/accounts/addaddress.html')
Пример #21
0
    def delete_server(self, serverid):
        "Delete a scan server"
        server = self._get_server(serverid)
        if not server:
            abort(404)

        c.form = ServerForm(request.POST, server, csrf_context=session)
        c.id = server.id
        if request.POST and c.form.validate():
            hostname = server.hostname
            Session.delete(server)
            Session.commit()
            update_serial.delay()
            info = HOSTDELETE_MSG % dict(n=hostname)
            audit_log(c.user.username, 4, info, request.host,
                      request.remote_addr, now())
            flash(_('The scanning server has been deleted'))
            redirect(url(controller='settings'))
        return render('/settings/deleteserver.html')
Пример #22
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.POST and c.form.validate():
            try:
                if c.user.is_domain_admin:
                    # check if they own the domain
                    domain = c.form.address.data.split('@')[1]
                    domain = Session.query(Domain).options(
                                joinedload('organizations')).join(
                                dom_owns, (oas,
                                dom_owns.c.organization_id ==
                                oas.c.organization_id))\
                                .filter(oas.c.user_id == c.user.id)\
                                .filter(Domain.name == domain).one()
                addr = Address(address=c.form.address.data)
                addr.enabled = c.form.enabled.data
                addr.user = user
                Session.add(addr)
                Session.commit()
                update_serial.delay()
                info = ADDRADD_MSG % dict(a=addr.address, ac=user.username)
                audit_log(c.user.username, 3, info, request.host,
                          request.remote_addr, now())
                flash(
                    _('The alias address %(address)s was successfully created.'
                      % dict(address=addr.address)))
            except IntegrityError:
                flash_alert(
                    _('The address %(addr)s already exists') %
                    dict(addr=addr.address))
            except NoResultFound:
                flash(
                    _('Domain: %(d)s does not belong to you') % dict(d=domain))
            redirect(url(controller='accounts', action='detail',
                         userid=userid))
        c.id = userid
        return render('/accounts/addaddress.html')
Пример #23
0
    def delete_server(self, serverid):
        "Delete a scan server"
        server = self._get_server(serverid)
        if not server:
            abort(404)

        c.form = ServerForm(request.POST, server, csrf_context=session)
        c.id = server.id
        if request.POST and c.form.validate():
            hostname = server.hostname
            Session.delete(server)
            Session.commit()
            update_serial.delay()
            info = HOSTDELETE_MSG % dict(n=hostname)
            audit_log(c.user.username,
                    4, info, request.host,
                    request.remote_addr, datetime.now())
            flash(_('The scanning server has been deleted'))
            redirect(url(controller='settings'))
        return render('/settings/deleteserver.html')
Пример #24
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')
Пример #25
0
    def import_status(self, taskid):
        "import status"
        result = AsyncResult(taskid)
        if result is None or taskid not in session['taskids']:
            flash(_('The task status requested has expired or does not exist'))
            redirect(url(controller='accounts', action='index'))

        if result.ready():
            finished = True
            flash.pop_messages()
            if isinstance(result.result, Exception):
                if c.user.is_superadmin:
                    flash_alert(_('Error occured in processing %s') %
                                result.result)
                else:
                    flash_alert(_('Backend error occured during processing.'))
                redirect(url(controller='accounts'))
            update_serial.delay()
            audit_log(c.user.username,
                    3, unicode(ACCOUNTIMPORT_MSG), request.host,
                    request.remote_addr, now())
        else:
            session['acimport-count'] += 1
            if (session['acimport-count'] >= 10 and
                result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                try:
                    os.unlink(session['acimport-file'])
                except OSError:
                    pass
                del session['acimport-count']
                session.save()
                flash_alert(_('The import could not be processed,'
                            ' try again later'))
                redirect(url(controller='accounts'))
            finished = False

        c.finished = finished
        c.results = result.result
        c.success = result.successful()
        return render('/accounts/importstatus.html')
Пример #26
0
    def import_status(self, taskid):
        "import status"
        result = AsyncResult(taskid)
        if result is None or taskid not in session['taskids']:
            flash(_('The task status requested has expired or does not exist'))
            redirect(url(controller='accounts', action='index'))

        if result.ready():
            finished = True
            flash.pop_messages()
            if isinstance(result.result, Exception):
                if c.user.is_superadmin:
                    flash_alert(
                        _('Error occured in processing %s') % result.result)
                else:
                    flash_alert(_('Backend error occured during processing.'))
                redirect(url(controller='accounts'))
            update_serial.delay()
            audit_log(c.user.username, 3, ACCOUNTIMPORT_MSG, request.host,
                      request.remote_addr, now())
        else:
            session['acimport-count'] += 1
            if (session['acimport-count'] >= 10
                    and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                try:
                    os.unlink(session['acimport-file'])
                except OSError:
                    pass
                del session['acimport-count']
                session.save()
                flash_alert(
                    _('The import could not be processed,'
                      ' try again later'))
                redirect(url(controller='accounts'))
            finished = False

        c.finished = finished
        c.results = result.result
        c.success = result.successful()
        return render('/accounts/importstatus.html')
Пример #27
0
    def import_status(self, taskid):
        "import domains status"
        result = AsyncResult(taskid)
        if result is None or taskid not in session["taskids"]:
            flash(_("The task status requested has expired or does not exist"))
            redirect(url(controller="organizations", action="index"))

        if result.ready():
            finished = True
            flash.pop_messages()
            if isinstance(result.result, Exception):
                if c.user.is_superadmin:
                    flash_alert(_("Error occured in processing %s") % result.result)
                else:
                    flash_alert(_("Backend error occured during processing."))
                redirect(url(controller="organizations"))
            update_serial.delay()
            info = IMPORTORG_MSG % dict(o="-")
            audit_log(c.user.username, 3, info, request.host, request.remote_addr, now())
        else:
            session["dimport-counter"] += 1
            session.save()
            if session["dimport-counter"] >= 10 and result.state in ["PENDING", "RETRY", "FAILURE"]:
                result.revoke()
                try:
                    os.unlink(session["dimport-file"])
                except OSError:
                    pass
                del session["dimport-file"]
                del session["dimport-counter"]
                session.save()
                flash_alert(_("The import could not be processed," " try again later"))
                redirect(url(controller="organizations"))
            finished = False

        c.finished = finished
        c.results = result.result
        c.success = result.successful()
        return render("/organizations/importstatus.html")
Пример #28
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.POST and c.form.validate():
            updated = False
            for field in c.form:
                if (field.name != 'csrf_token'
                        and field.data != getattr(alias, field.name)):
                    setattr(alias, field.name, field.data)
                    updated = True
            if updated:
                try:
                    Session.add(alias)
                    Session.commit()
                    update_serial.delay()
                    info = UPDATEDOMALIAS_MSG % dict(d=alias.name)
                    audit_log(c.user.username, 2, info, request.host,
                              request.remote_addr, now())
                    flash(
                        _('The domain alias: %s has been updated') %
                        alias.name)
                    redirect(url('domain-detail', domainid=alias.domain_id))
                except IntegrityError:
                    Session.rollback()
                    flash_alert(_('The update failed'))
            else:
                flash_info(_('No changes were made to the domain alias'))
                redirect(url('domain-detail', domainid=alias.domain_id))

        c.aliasid = aliasid
        c.domainid = alias.domain_id
        c.domainname = alias.domain.name
        return render('/domains/editalias.html')
Пример #29
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')
Пример #30
0
 def delete(self, domainid):
     "Delete a domain"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     c.form = AddDomainForm(request.POST, domain, csrf_context=session)
     del c.form.organizations
     c.id = domainid
     if request.POST and c.form.validate():
         name = domain.name
         Session.delete(domain)
         Session.commit()
         update_serial.delay()
         info = DELETEDOMAIN_MSG % dict(d=name)
         audit_log(c.user.username, 4, info, request.host, request.remote_addr, datetime.now())
         flash(_("The domain has been deleted"))
         redirect(url(controller="domains"))
     else:
         flash(
             _("The domain: %(name)s and all associated data will" " be deleted, This action cannot be reversed.")
             % dict(name=domain.name)
         )
     return render("/domains/delete.html")
Пример #31
0
    def deleteaddress(self, addressid):
        "Delete address"
        address = self._get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.POST and c.form.validate():
            user_id = address.user_id
            addr = address.address
            username = address.user.username
            Session.delete(address)
            Session.commit()
            update_serial.delay()
            info = ADDRDELETE_MSG % dict(a=addr, ac=username)
            audit_log(c.user.username, 4, info, request.host,
                      request.remote_addr, now())
            flash(_('The address has been deleted'))
            redirect(
                url(controller='accounts', action='detail', userid=user_id))
        c.id = addressid
        c.userid = address.user_id
        return render('/accounts/deleteaddress.html')
Пример #32
0
 def edit(self, domainid):
     "Edit a domain"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     c.form = AddDomainForm(request.POST, domain, csrf_context=session)
     if c.user.is_superadmin:
         c.form.organizations.query_factory = self._get_organizations
     else:
         del c.form.organizations
     c.id = domainid
     if request.POST and c.form.validate():
         updated = False
         kw = {"domainid": domain.id}
         for field in c.form:
             intfields = ["spam_actions", "highspam_actions", "delivery_mode", "report_every"]
             if field.name in intfields and int(field.data) == getattr(domain, field.name):
                 continue
             if field.name != "csrf_token" and field.data != getattr(domain, field.name):
                 setattr(domain, field.name, field.data)
                 updated = True
         if updated:
             try:
                 Session.add(domain)
                 Session.commit()
                 update_serial.delay()
                 info = UPDATEDOMAIN_MSG % dict(d=domain.name)
                 audit_log(c.user.username, 2, info, request.host, request.remote_addr, datetime.now())
                 flash(_("The domain: %(dom)s has been updated") % dict(dom=domain.name))
                 kw["uc"] = 1
             except IntegrityError:
                 Session.rollback()
                 flash(_("The domain %(dom)s could not be updated") % dict(dom=domain.name))
         else:
             flash_info(_("No changes were made to the domain"))
         redirect(url("domain-detail", **kw))
     return render("/domains/edit.html")
Пример #33
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.POST and c.form.validate():
            alias = DomainAlias()
            for field in c.form:
                if field.data and field.name != 'csrf_token':
                    setattr(alias, field.name, field.data)
            try:
                domain.aliases.append(alias)
                Session.add(alias)
                Session.add(domain)
                Session.commit()
                update_serial.delay()
                info = ADDDOMALIAS_MSG % dict(d=alias.name)
                audit_log(c.user.username, 3, info, request.host,
                          request.remote_addr, now())
                flash(_('The domain alias: %s has been created') % alias.name)
                redirect(
                    url(controller='domains',
                        action='detail',
                        domainid=domain.id))
            except IntegrityError:
                Session.rollback()
                flash_alert(
                    _('The domain alias: %s already exists') % alias.name)

        c.domainid = domain.id
        c.domainname = domain.name
        return render('/domains/addalias.html')
Пример #34
0
 def delete(self, domainid):
     "Delete a domain"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     c.form = AddDomainForm(request.POST, domain, csrf_context=session)
     del c.form.organizations
     c.id = domainid
     if request.POST and c.form.validate():
         name = domain.name
         Session.delete(domain)
         Session.commit()
         update_serial.delay()
         info = DELETEDOMAIN_MSG % dict(d=name)
         audit_log(c.user.username, 4, info, request.host,
                   request.remote_addr, now())
         flash(_('The domain has been deleted'))
         redirect(url(controller='domains'))
     else:
         flash(
             _('The domain: %(name)s and all associated data will'
               ' be deleted, This action cannot be reversed.') %
             dict(name=domain.name))
     return render('/domains/delete.html')
Пример #35
0
    def deleteaddress(self, addressid):
        "Delete address"
        address = self._get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.POST and c.form.validate():
            user_id = address.user_id
            addr = address.address
            username = address.user.username
            Session.delete(address)
            Session.commit()
            update_serial.delay()
            info = ADDRDELETE_MSG % dict(a=addr, ac=username)
            audit_log(c.user.username,
                    4, unicode(info), request.host,
                    request.remote_addr, now())
            flash(_('The address has been deleted'))
            redirect(url(controller='accounts', action='detail',
            userid=user_id))
        c.id = addressid
        c.userid = address.user_id
        return render('/accounts/deleteaddress.html')
Пример #36
0
    def section(self, serverid=1, sectionid='1'):
        "Settings section"
        server = self._get_server(serverid)
        if not server:
            abort(404)

        if not int(sectionid) in CONFIG_SECTIONS:
            abort(404)

        c.serverid = serverid
        c.sectionid = sectionid
        c.scanner = server
        c.sections = CONFIG_SECTIONS
        c.form = settings_forms[sectionid](request.POST, csrf_context=session)
        if not request.method == 'POST':
            for field in c.form:
                if (sectionid == '1' and '_' in field.name
                    and not field.name == 'csrf_token'):
                    internal = global_settings_dict[field.name]
                else:
                    internal = field.name
                conf = self._get_setting(serverid, internal)
                if conf:
                    attr = getattr(c.form, field.name)
                    attr.data = conf.value

        updated = None
        if request.method == 'POST' and c.form.validate():
            for field in c.form:
                if field.type == 'SelectMultipleField' or \
                        (field.data and not field.name == 'csrf_token'):
                    if sectionid == '1':
                        if '_' in field.name:
                            external = global_settings_dict[field.name]
                            internal = external
                        else:
                            external = CONFIG_RE.sub(u'',
                                        unicode(field.label.text))
                            internal = field.name
                    else:
                        external = CONFIG_RE.sub(u'',
                                    unicode(field.label.text))
                        internal = field.name
                    conf = self._get_setting(serverid, internal)
                    if conf is None:
                        if (field.type == 'SelectMultipleField' and
                            len(field.data) and field.data != field.default)\
                            or (field.type != 'SelectMultipleField' and
                                field.data != field.default):
                            check_field(field)
                            conf = ConfigSettings(
                                        internal=internal,
                                        external=external,
                                        section=sectionid
                                    )
                            conf.value = field.data
                            conf.server = server
                            updated = True
                            Session.add(conf)
                            Session.commit()
                            subs = dict(svr=server.hostname,
                                        s=external,
                                        a=conf.value)
                            info = auditmsgs.HOSTSETTING_MSG % subs
                            audit_log(c.user.username,
                                    3, unicode(info), request.host,
                                    request.remote_addr,
                                    arrow.utcnow().datetime)
                    else:
                        subs = dict(svr=conf.server.hostname,
                                    s=external,
                                    a=conf.value)
                        info = auditmsgs.HOSTSETTING_MSG % subs
                        check_value = get_check_value(field.type, conf.value)
                        if check_value != field.data:
                            # stored value not equal to updated value
                            if (field.type == 'SelectMultipleField' and
                                len(field.data) and
                                field.data != field.default) or \
                                (field.type != 'SelectMultipleField' and
                                field.data != field.default):
                                # not a default, we can update
                                check_field(field)
                                conf.value = field.data
                                updated = True
                                Session.add(conf)
                                Session.commit()
                                audit_log(c.user.username,
                                    2, unicode(info), request.host,
                                    request.remote_addr,
                                    arrow.utcnow().datetime)
                            else:
                                # is the default lets delete the stored value
                                Session.delete(conf)
                                Session.commit()
                                updated = True
                                audit_log(c.user.username,
                                        4, unicode(info), request.host,
                                        request.remote_addr,
                                        arrow.utcnow().datetime)

            if updated:
                flash(_('%(settings)s updated') % dict(
                    settings=CONFIG_SECTIONS[int(sectionid)]))
                create_ms_settings.apply_async(exchange=FANOUT_XCHG)
                update_serial.delay()
            else:
                flash_info(_('No configuration changes made'))
            # redirect(url('settings-scanner', serverid=serverid))
        elif request.method == 'POST' and not c.form.validate():
            msg = _("Error detected, check the settings below")
            flash_alert(msg)
            log.info(msg)
        return self.render('/settings/section.html')
Пример #37
0
    def section(self, serverid=1, sectionid='1'):
        "Settings section"
        server = self._get_server(serverid)
        if not server:
            abort(404)

        if not int(sectionid) in CONFIG_SECTIONS:
            abort(404)

        c.serverid = serverid
        c.sectionid = sectionid
        c.scanner = server
        c.sections = CONFIG_SECTIONS
        c.form = settings_forms[sectionid](request.POST, csrf_context=session)
        if not request.POST:
            for field in c.form:
                if (sectionid == '1' and '_' in field.name
                    and not field.name == 'csrf_token'):
                    internal = global_settings_dict[field.name]
                else:
                    internal = field.name
                conf = self._get_setting(serverid, internal)
                if conf:
                    attr = getattr(c.form, field.name)
                    attr.data = conf.value

        updated = None
        if request.POST and c.form.validate():
            for field in c.form:
                if field.data and not field.name == 'csrf_token':
                    if sectionid == '1':
                        if '_' in field.name:
                            external = global_settings_dict[field.name]
                            internal = external
                        else:
                            external = CONFIG_RE.sub('', field.label.text)
                            internal = field.name
                    else:
                        external = CONFIG_RE.sub('', field.label.text)
                        internal = field.name
                    conf = self._get_setting(serverid, internal)
                    if conf is None:
                        if field.data != field.default:
                            conf = ConfigSettings(
                                        internal=internal,
                                        external=external,
                                        section=sectionid
                                    )
                            conf.value = field.data
                            conf.server = server
                            updated = True
                            Session.add(conf)
                            Session.commit()
                            subs = dict(svr=server.hostname,
                                        s=external,
                                        a=conf.value)
                            info = HOSTSETTING_MSG % subs
                            audit_log(c.user.username,
                                    3, info, request.host,
                                    request.remote_addr, datetime.now())
                    else:
                        if conf.value != field.data:
                            conf.value = field.data
                            updated = True
                            Session.add(conf)
                            Session.commit()
                            subs = dict(svr=conf.server.hostname,
                                        s=external,
                                        a=conf.value)
                            info = HOSTSETTING_MSG % subs
                            audit_log(c.user.username,
                                    2, info, request.host,
                                    request.remote_addr, datetime.now())
            if updated:
                flash(_('%(settings)s updated') % dict(
                settings=CONFIG_SECTIONS[int(sectionid)]))
                update_serial.delay()
            else:
                flash_info(_('No configuration changes made'))
            #redirect(url('settings-scanner', serverid=serverid))
        return render('/settings/section.html')
Пример #38
0
    def confirm_delete(self):
        "Confirm mass delete"
        accountids = session.get('bulk_account_delete', [])
        if not accountids:
            redirect(url(controller='accounts', action='index'))

        num_items = 10
        if len(accountids) > num_items and len(accountids) <= 20:
            num_items = 20
        if len(accountids) > num_items and len(accountids) <= 50:
            num_items = 50
        if len(accountids) > num_items and len(accountids) <= 100:
            num_items = 100

        users = Session.query(User).filter(User.id.in_(accountids))
        usrcount = Session.query(User.id)

        if c.user.is_domain_admin and usrcount:
            users = users.join(domain_users, (dom_owns,
                    domain_users.c.domain_id == dom_owns.c.domain_id),
                    (oas, dom_owns.c.organization_id == oas.c.organization_id))\
                    .filter(oas.c.user_id == c.user.id)
            usrcount = usrcount.join(domain_users, (dom_owns,
                        domain_users.c.domain_id == dom_owns.c.domain_id),
                        (oas, dom_owns.c.organization_id ==
                        oas.c.organization_id))\
                        .filter(oas.c.user_id == c.user.id)

        if request.POST:
            tasks = []
            # try:
            for account in users.all():
                info = DELETEACCOUNT_MSG % dict(u=account.username)
                Session.delete(account)
                tasks.append([
                    c.user.username, 4, info, request.host,
                    request.remote_addr,
                    now()
                ])
            Session.commit()
            # except DataError:
            #     flash_alert(_('An error occured try again'))
            #     redirect(url(controller='accounts', action='index'))
            del session['bulk_account_delete']
            session.save()
            update_serial.delay()
            for task in tasks:
                audit_log(*task)
            flash(_('The accounts have been deleted'))
            redirect(url(controller='accounts'))
        else:
            flash(
                _('The following accounts are about to be deleted,'
                  ' this action is not reversible, Do you wish to '
                  'continue ?'))

        try:
            c.page = paginate.Page(users,
                                   page=1,
                                   items_per_page=num_items,
                                   item_count=usrcount.count())
        except DataError:
            flash_alert(_('An error occured try again'))
            redirect(url(controller='accounts', action='index'))
        return render('/accounts/confirmbulkdel.html')
Пример #39
0
    def confirm_delete(self):
        "Confirm mass delete"
        accountids = session.get('bulk_account_delete', [])
        if not accountids:
            redirect(url(controller='accounts', action='index'))

        num_items = 10
        if len(accountids) > num_items and len(accountids) <= 20:
            num_items = 20
        if len(accountids) > num_items and len(accountids) <= 50:
            num_items = 50
        if len(accountids) > num_items and len(accountids) <= 100:
            num_items = 100

        users = Session.query(User).filter(User.id.in_(accountids))
        usrcount = Session.query(User.id)

        if c.user.is_domain_admin and usrcount:
            users = users.join(domain_users, (dom_owns,
                    domain_users.c.domain_id == dom_owns.c.domain_id),
                    (oas, dom_owns.c.organization_id == oas.c.organization_id))\
                    .filter(oas.c.user_id == c.user.id)
            usrcount = usrcount.join(domain_users, (dom_owns,
                        domain_users.c.domain_id == dom_owns.c.domain_id),
                        (oas, dom_owns.c.organization_id ==
                        oas.c.organization_id))\
                        .filter(oas.c.user_id == c.user.id)

        if request.method == 'POST':
            tasks = []
            # try:
            for account in users.all():
                info = DELETEACCOUNT_MSG % dict(u=account.username)
                Session.delete(account)
                tasks.append([c.user.username,
                            4,
                            unicode(info),
                            request.host,
                            request.remote_addr,
                            now()])
            Session.commit()
            # except DataError:
            #     flash_alert(_('An error occured try again'))
            #     redirect(url(controller='accounts', action='index'))
            del session['bulk_account_delete']
            session.save()
            update_serial.delay()
            for task in tasks:
                audit_log(*task)
            flash(_('The accounts have been deleted'))
            redirect(url(controller='accounts'))
        else:
            flash(_('The following accounts are about to be deleted,'
                    ' this action is not reversible, Do you wish to '
                    'continue ?'))

        try:
            c.page = paginate.Page(users, page=1,
                                    items_per_page=num_items,
                                    item_count=usrcount.count())
        except DataError:
            flash_alert(_('An error occured try again'))
            redirect(url(controller='accounts', action='index'))
        return render('/accounts/confirmbulkdel.html')
Пример #40
0
 def new(self):
     "Add a new list item"
     c.form = list_forms[c.user.account_type](request.POST,
                                         csrf_context=session)
     if c.user.is_domain_admin:
         orgs = [group.id for group in c.user.organizations]
         query = Session.query(Domain.name).join(domain_owners)\
                 .filter(domain_owners.c.organization_id.in_(orgs))
         options = [(domain.name, domain.name) for domain in query]
         c.form.to_domain.choices = options
     if c.user.is_peleb:
         query = self._user_addresses()
         options = [(item.email, item.email) for item in query]
         c.form.to_address.choices = options
     if request.POST and c.form.validate():
         # item = List()
         # item.user = c.user
         # item.list_type = c.form.list_type.data
         # item.from_address = c.form.from_address.data
         item = make_item(c.form)
         _set_type(item)
         aliases = []
         if c.user.is_superadmin or c.user.is_peleb:
             if c.form.to_address.data != '':
                 item.to_address = c.form.to_address.data
                 if ('add_to_alias' in c.form and c.form.add_to_alias.data
                     and c.user.is_peleb):
                     for new_addr in options:
                         if new_addr[0] == item.to_address:
                             continue
                         newitem = make_item(c.form)
                         _set_type(newitem)
                         newitem.to_address = new_addr[0]
                         aliases.append(newitem)
             else:
                 item.to_address = 'any'
         if c.user.is_domain_admin:
             if c.form.to_address.data in ['', 'any']:
                 item.to_address = c.form.to_domain.data
                 if c.form.add_to_alias.data:
                     for dom in options:
                         if dom[0] == item.to_address:
                             continue
                         newitem = make_item(c.form)
                         _set_type(newitem)
                         newitem.to_address = dom[0]
                         aliases.append(newitem)
             else:
                 item.to_address = "%s@%s" % (c.form.to_address.data,
                 c.form.to_domain.data)
                 if c.form.add_to_alias.data:
                     for dom in options:
                         newitem = make_item(c.form)
                         _set_type(newitem)
                         newitem.to_address = "%s@%s" % \
                                             (c.form.to_address.data, dom[0])
                         if newitem.to_address == item.to_address:
                             continue
                         aliases.append(newitem)
         try:
             Session.add(item)
             Session.commit()
             for alias in aliases:
                 try:
                     Session.add(alias)
                     Session.commit()
                 except IntegrityError:
                     pass
             update_serial.delay()
             if item.list_type == 1:
                 listname = _('Approved senders')
             else:
                 listname = _('Banned senders')
             info = LISTADD_MSG % dict(s=item.from_address, l=listname)
             audit_log(c.user.username,
                     3, info, request.host,
                     request.remote_addr, datetime.now())
             flash(_('The item has been added to the list'))
             if not request.is_xhr:
                 redirect(url('lists-index',
                         list_type=c.form.list_type.data))
         except IntegrityError:
             Session.rollback()
             flash_alert(_('The list item already exists'))
     return render('/lists/add.html')
Пример #41
0
    def section(self, serverid=1, sectionid='1'):
        "Settings section"
        server = self._get_server(serverid)
        if not server:
            abort(404)

        if not int(sectionid) in CONFIG_SECTIONS:
            abort(404)

        c.serverid = serverid
        c.sectionid = sectionid
        c.scanner = server
        c.sections = CONFIG_SECTIONS
        c.form = settings_forms[sectionid](request.POST, csrf_context=session)
        if not request.POST:
            for field in c.form:
                if (sectionid == '1' and '_' in field.name
                        and not field.name == 'csrf_token'):
                    internal = global_settings_dict[field.name]
                else:
                    internal = field.name
                conf = self._get_setting(serverid, internal)
                if conf:
                    attr = getattr(c.form, field.name)
                    attr.data = conf.value

        updated = None
        if request.POST and c.form.validate():
            for field in c.form:
                if field.data and not field.name == 'csrf_token':
                    if sectionid == '1':
                        if '_' in field.name:
                            external = global_settings_dict[field.name]
                            internal = external
                        else:
                            external = CONFIG_RE.sub(u'',
                                                     unicode(field.label.text))
                            internal = field.name
                    else:
                        external = CONFIG_RE.sub(u'',
                                                 unicode(field.label.text))
                        internal = field.name
                    conf = self._get_setting(serverid, internal)
                    if conf is None:
                        if field.data != field.default:
                            conf = ConfigSettings(internal=internal,
                                                  external=external,
                                                  section=sectionid)
                            conf.value = field.data
                            conf.server = server
                            updated = True
                            Session.add(conf)
                            Session.commit()
                            subs = dict(svr=server.hostname,
                                        s=external,
                                        a=conf.value)
                            info = HOSTSETTING_MSG % subs
                            audit_log(c.user.username, 3, info, request.host,
                                      request.remote_addr, now())
                    else:
                        if conf.value != field.data:
                            conf.value = field.data
                            updated = True
                            Session.add(conf)
                            Session.commit()
                            subs = dict(svr=conf.server.hostname,
                                        s=external,
                                        a=conf.value)
                            info = HOSTSETTING_MSG % subs
                            audit_log(c.user.username, 2, info, request.host,
                                      request.remote_addr, now())
            if updated:
                flash(
                    _('%(settings)s updated') %
                    dict(settings=CONFIG_SECTIONS[int(sectionid)]))
                update_serial.delay()
            else:
                flash_info(_('No configuration changes made'))
            #redirect(url('settings-scanner', serverid=serverid))
        return render('/settings/section.html')