Esempio n. 1
0
    def login(self):
        "login"
        if request.remote_addr in session:
            if session[request.remote_addr] > now():
                abort(409,
                      _('You have been banned after'
                        ' several failed logins'))
            else:
                del session[request.remote_addr]
                session.save()

        identity = request.environ.get('repoze.who.identity')
        came_from = unquote(str(request.GET.get('came_from', '')))
        if not came_from or ' ' in came_from:
            came_from = url('home')
        if '://' in came_from:
            from_url = urlparse(came_from)
            came_from = from_url[2]

        if identity:
            redirect(url(came_from))
        else:
            c.came_from = came_from
            c.login_counter = request.environ['repoze.who.logins']
            if c.login_counter >= 3:
                ban_until = now() + timedelta(minutes=5)
                if request.remote_addr not in session:
                    session[request.remote_addr] = ban_until
                    session.save()
                else:
                    if now() > session[request.remote_addr]:
                        del session[request.remote_addr]
                        session.save()
            return render('/accounts/login.html')
Esempio n. 2
0
    def login(self):
        "login"
        if request.remote_addr in session:
            if session[request.remote_addr] > now():
                abort(409, _('You have been banned after'
                            ' several failed logins'))
            else:
                del session[request.remote_addr]
                session.save()

        identity = request.environ.get('repoze.who.identity')
        came_from = unquote(str(request.GET.get('came_from', '')))
        if not came_from or ' ' in came_from:
            came_from = url('home')
        if '://' in came_from:
            from_url = urlparse(came_from)
            came_from = from_url[2]

        if identity:
            redirect(url(came_from))
        else:
            c.came_from = came_from
            c.login_counter = request.environ['repoze.who.logins']
            if c.login_counter >= 3:
                ban_until = now() + timedelta(minutes=5)
                if request.remote_addr not in session:
                    session[request.remote_addr] = ban_until
                    session.save()
                else:
                    if now() > session[request.remote_addr]:
                        del session[request.remote_addr]
                        session.save()
            c.form = ResetPwForm(request.POST, csrf_context=session)
            return render('/accounts/login.html')
Esempio n. 3
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')
Esempio n. 4
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')
Esempio n. 5
0
    def add_relay(self, orgid):
        "Add a mail relay"
        org = self._get_org(orgid)
        if not org:
            abort(404)

        c.form = RelayForm(request.POST, csrf_context=session)
        if request.POST and c.form.validate():
            try:
                outbound = Relay()
                outbound.address = c.form.address.data
                outbound.username = c.form.username.data
                outbound.enabled = c.form.enabled.data
                outbound.org = org
                if c.form.password1.data:
                    outbound.set_password(c.form.password1.data)
                Session.add(outbound)
                Session.commit()
                relay_name = c.form.address.data or c.form.username.data
                info = ADDRELAY_MSG % dict(r=relay_name)
                audit_log(c.user.username, 3, info, request.host,
                          request.remote_addr, now())
                flash(_('The outbound settings have been created'))
            except IntegrityError:
                Session.rollback()
                flash(_('The outbound settings could not created, Try again'))
            redirect(url('org-detail', orgid=orgid))
        c.orgid = org.id
        c.orgname = org.name
        return render('/organizations/addrelay.html')
Esempio n. 6
0
    def delete(self, orgid):
        "Delete an organization"
        org = self._get_org(orgid)
        if not org:
            abort(404)

        c.form = DelOrgForm(request.POST, org, csrf_context=session)
        c.form.domains.query = Session.query(Domain)
        c.form.admins.query = Session.query(User).filter(
            User.account_type == 2)
        c.id = org.id
        if request.POST and c.form.validate():
            org_name = org.name
            if c.form.delete_domains.data:
                for domain in org.domains:
                    Session.delete(domain)
            Session.delete(org)
            Session.commit()
            info = DELETEORG_MSG % dict(o=org_name)
            audit_log(c.user.username, 4, info, request.host,
                      request.remote_addr, now())
            flash(_('The organization has been deleted'))
            redirect(url(controller='organizations'))
        else:
            flash(
                _('The organization: %(s)s will be deleted,'
                  ' This action is not reversible') % dict(s=org.name))
        return render('/organizations/delete.html')
Esempio n. 7
0
    def edit(self, orgid):
        "Edit an organization"
        org = self._get_org(orgid)
        if not org:
            abort(404)

        c.form = OrgForm(request.POST, org, csrf_context=session)
        c.form.domains.query = Session.query(Domain)
        c.form.admins.query = Session.query(User).filter(
            User.account_type == 2)
        c.id = org.id
        if request.POST and c.form.validate():
            updated = False
            for field in c.form:
                if (field.name != 'csrf_token'
                        and field.data != getattr(org, field.name)):
                    setattr(org, field.name, field.data)
                    updated = True
            if updated:
                try:
                    Session.add(org)
                    Session.commit()
                    info = UPDATEORG_MSG % dict(o=org.name)
                    audit_log(c.user.username, 2, info, request.host,
                              request.remote_addr, now())
                    flash(_('The organization has been updated'))
                except IntegrityError:
                    Session.rollback()
                    flash(_('The organization could not be updated'))
            else:
                flash_info(_('No changes made, Organization not updated'))
            redirect(url(controller='organizations'))
        return render('/organizations/edit.html')
Esempio n. 8
0
    def edit_account_sigs(self, sigid):
        "Edit account signatures"
        sign = self._get_usrsign(sigid)
        if not sign:
            abort(404)

        c.form = SigForm(request.POST, sign, csrf_context=session)
        del c.form['signature_type']
        if request.POST and c.form.validate():
            try:
                updated = False
                for field in c.form:
                    if (field.name != 'csrf_token' and
                        field.data != getattr(sign, field.name)):
                        updated = True
                        setattr(sign, field.name, field.data)
                if updated:
                    Session.add(sign)
                    Session.commit()
                    save_user_sig.apply_async(args=[sigid], queue='msbackend')
                    info = UPDATEACCSIG_MSG % dict(u=sign.user.username)
                    audit_log(c.user.username,
                            2, unicode(info), request.host,
                            request.remote_addr, now())
                    flash(_('The signature has been updated'))
                else:
                    flash(_('No changes made, signature not updated'))
                redirect(url('account-detail', userid=sign.user_id))
            except IntegrityError:
                Session.rollback()
                flash(_('Error occured updating the signature'))
        c.sign = sign
        return render('/settings/account_editsig.html')
Esempio n. 9
0
    def add_account_sigs(self, userid):
        "Add account signature"
        account = self._get_user(userid)
        if not account:
            abort(404)

        c.form = SigForm(request.POST, csrf_context=session)
        if request.POST and c.form.validate():
            try:
                sig = UserSignature()
                for field in c.form:
                    if field.name != 'csrf_token':
                        setattr(sig, field.name, field.data)
                account.signatures.append(sig)
                Session.add(sig)
                Session.add(account)
                Session.commit()
                save_user_sig.apply_async(args=[sig.id], queue='msbackend')
                info = ADDACCSIG_MSG % dict(u=account.username)
                audit_log(c.user.username,
                        3, unicode(info), request.host,
                        request.remote_addr, now())
                flash(_('The signature has been created'))
                redirect(url('account-detail', userid=userid))
            except IntegrityError:
                Session.rollback()
                flash(_('This signature type already exists'))
        c.account = account
        return render('/settings/account_addsig.html')
Esempio n. 10
0
    def add_domain_sigs(self, domainid):
        "Add domain signature"
        domain = self._get_domain(domainid)
        if not domain:
            abort(404)

        c.form = SigForm(request.POST, csrf_context=session)
        if request.POST and c.form.validate():
            try:
                sig = DomSignature()
                for field in c.form:
                    if field.name != 'csrf_token':
                        setattr(sig, field.name, field.data)
                domain.signatures.append(sig)
                Session.add(sig)
                Session.add(domain)
                Session.commit()
                save_dom_sig.apply_async(args=[sig.id], queue='msbackend')
                info = ADDDOMSIG_MSG % dict(d=domain.name)
                audit_log(c.user.username,
                        3, unicode(info), request.host,
                        request.remote_addr, now())
                flash(_('The signature has been created'))
                redirect(url('domain-settings-sigs', domainid=domainid))
            except IntegrityError:
                Session.rollback()
                flash(_('This signature type already exists'))
        c.domain = domain
        return render('/settings/domain_addsig.html')
Esempio n. 11
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, unicode(info), request.host,
                     request.remote_addr, 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')
Esempio n. 12
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')
Esempio n. 13
0
 def adddestination(self, domainid):
     "Add a destination server"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     c.form = AddDeliveryServerForm(request.POST, csrf_context=session)
     c.id = domainid
     if request.POST and c.form.validate():
         server = DeliveryServer()
         for field in c.form:
             if field.name != 'csrf_token':
                 setattr(server, field.name, field.data)
         try:
             domain.servers.append(server)
             Session.add(server)
             Session.add(domain)
             Session.commit()
             info = ADDDELSVR_MSG % dict(d=domain.name, ds=server.address)
             audit_log(c.user.username, 3, info, request.host,
                       request.remote_addr, now())
             flash(_('The destination server has been created'))
             redirect(
                 url(controller='domains',
                     action='detail',
                     domainid=domain.id))
         except IntegrityError:
             Session.rollback()
             flash_alert(
                 _('The destination server %(dest)s already exists ') %
                 dict(dest=server.address))
     return render('/domains/adddestination.html')
Esempio n. 14
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, unicode(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')
Esempio n. 15
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, unicode(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')
Esempio n. 16
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')
Esempio n. 17
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.POST and c.form.validate():
         server = AuthServer()
         for field in c.form:
             if field.data and field.name != 'csrf_token':
                 setattr(server, field.name, field.data)
         try:
             domain.authservers.append(server)
             Session.add(server)
             Session.add(domain)
             Session.commit()
             info = ADDAUTHSVR_MSG % dict(d=domain.name, ds=server.address)
             audit_log(c.user.username,
                     3, unicode(info), request.host,
                     request.remote_addr, now())
             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)]
             flash_alert(
                 _('The host %(dest)s already configured for %(auth)s '
                 'authentication for this domain') %
                 dict(dest=server.address, auth=auth))
     c.domainid = domainid
     c.domainname = domain.name
     return render('/domains/addauth.html')
Esempio n. 18
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')
Esempio n. 19
0
 def domain_dkim_generate(self, domainid):
     "Domain DKIM generate keys"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     pub_key, pri_key = make_key_pair()
     if domain.dkimkeys:
         dkimkeys = domain.dkimkeys[0]
     else:
         dkimkeys = DKIMKeys()
     dkimkeys.pub_key = pub_key
     dkimkeys.pri_key = pri_key
     try:
         if domain.dkimkeys:
             domain.dkimkeys[0] = dkimkeys
         else:
             domain.dkimkeys.append(dkimkeys)
         Session.add(dkimkeys)
         Session.add(domain)
         Session.commit()
         info = DKIMGEN_MSG % dict(d=domain.name)
         audit_log(c.user.username,
                 3, unicode(info), request.host,
                 request.remote_addr, now())
         flash(_('DKIM keys successfully generated'))
     except DatabaseError:
         flash_alert(_('Generation of DKIM keys failed'))
     redirect(url('domain-dkim', domainid=domain.id))
Esempio n. 20
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, unicode(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')
Esempio n. 21
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')
Esempio n. 22
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')
Esempio n. 23
0
    def add_account_sigs(self, userid):
        "Add account signature"
        account = self._get_user(userid)
        if not account:
            abort(404)

        c.form = SigForm(request.POST, csrf_context=session)
        if request.POST and c.form.validate():
            try:
                sig = UserSignature()
                for field in c.form:
                    if field.name != 'csrf_token':
                        setattr(sig, field.name, field.data)
                account.signatures.append(sig)
                Session.add(sig)
                Session.add(account)
                Session.commit()
                save_user_sig.apply_async(args=[sig.id], queue='msbackend')
                info = ADDACCSIG_MSG % dict(u=account.username)
                audit_log(c.user.username, 3, info, request.host,
                          request.remote_addr, now())
                flash(_('The signature has been created'))
                redirect(url('account-detail', userid=userid))
            except IntegrityError:
                Session.rollback()
                flash(_('This signature type already exists'))
        c.account = account
        return render('/settings/account_addsig.html')
Esempio n. 24
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.POST and c.form.validate():
         server = AuthServer()
         for field in c.form:
             if field.data and field.name != 'csrf_token':
                 setattr(server, field.name, field.data)
         try:
             domain.authservers.append(server)
             Session.add(server)
             Session.add(domain)
             Session.commit()
             info = ADDAUTHSVR_MSG % dict(d=domain.name, ds=server.address)
             audit_log(c.user.username, 3, info, request.host,
                       request.remote_addr, now())
             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)]
             flash_alert(
                 _('The host %(dest)s already configured for %(auth)s '
                   'authentication for this domain') %
                 dict(dest=server.address, auth=auth))
     c.domainid = domainid
     c.domainname = domain.name
     return render('/domains/addauth.html')
Esempio n. 25
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')
Esempio n. 26
0
    def add_domain_sigs(self, domainid):
        "Add domain signature"
        domain = self._get_domain(domainid)
        if not domain:
            abort(404)

        c.form = SigForm(request.POST, csrf_context=session)
        if request.POST and c.form.validate():
            try:
                sig = DomSignature()
                for field in c.form:
                    if field.name != 'csrf_token':
                        setattr(sig, field.name, field.data)
                domain.signatures.append(sig)
                Session.add(sig)
                Session.add(domain)
                Session.commit()
                save_dom_sig.apply_async(args=[sig.id], queue='msbackend')
                info = ADDDOMSIG_MSG % dict(d=domain.name)
                audit_log(c.user.username, 3, info, request.host,
                          request.remote_addr, now())
                flash(_('The signature has been created'))
                redirect(url('domain-settings-sigs', domainid=domainid))
            except IntegrityError:
                Session.rollback()
                flash(_('This signature type already exists'))
        c.domain = domain
        return render('/settings/domain_addsig.html')
Esempio n. 27
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')
Esempio n. 28
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')
Esempio n. 29
0
 def __init__(self, dbsession, user):
     self.dbsession = dbsession
     self.user = user
     self.query = self.dbsession.query(
         func.count(Message.id).label('total'),
         func.sum(case([(and_(Message.virusinfected == 0,
             Message.nameinfected == 0, Message.otherinfected == 0,
             Message.spam == 0, Message.highspam == 0), 1)],
             else_=0)).label('clean'),
         func.sum(case([(Message.virusinfected > 0, 1)],
             else_=0)).label('virii'),
         func.sum(case([(and_(Message.highspam == 0,
             Message.spam == 0, Message.virusinfected == 0,
             or_(Message.nameinfected > 0, Message.otherinfected > 0)), 1)],
             else_=0)).label('infected'),
         func.sum(case([(and_(Message.virusinfected == 0,
             Message.otherinfected == 0, Message.nameinfected == 0,
             or_(Message.spam > 0, Message.highspam > 0)), 1)],
             else_=0)).label('spam'),
         func.sum(case([(and_(Message.virusinfected == 0,
             Message.otherinfected == 0, Message.nameinfected == 0,
             Message.spam > 0, Message.highspam == 0), 1)],
             else_=0)).label('lowspam'),
         func.sum(case([(and_(Message.virusinfected == 0,
             Message.otherinfected == 0, Message.nameinfected == 0,
             Message.highspam > 0), 1)],
             else_=0)).label('highspam'))\
             .filter(Message.date == now().date())
Esempio n. 30
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')
Esempio n. 31
0
def domain_pie_query(domain, reportid, num_of_days=0):
    "Run domain query"
    queryfield = getattr(Message, REPORTS[reportid]['address'])
    orderby = REPORTS[reportid]['sort']
    query = Session.query(queryfield.label('address'),
                        func.count(queryfield).label('count'),
                        func.sum(Message.size).label('size'))
    if reportid == '10':
        query = query.filter(queryfield != u'127.0.0.1')\
                        .group_by(queryfield)\
                        .order_by(desc(orderby))
    else:
        query = query.filter(queryfield != u'')\
                        .group_by(queryfield)\
                        .order_by(desc(orderby))
    if reportid in ['5', '6', '7', '8']:
        query = query.filter(Message.to_domain == domain)
    else:
        query = query.filter(func._(or_(Message.from_domain == domain,
                                        Message.to_domain == domain)))
    if int(num_of_days) > 0:
        numofdays = datetime.timedelta(days=num_of_days)
        startdate = now().date() - numofdays
        query = query.filter(Message.timestamp > str(startdate))
    data = query[:10]
    return data
Esempio n. 32
0
 def domain_dkim_generate(self, domainid):
     "Domain DKIM generate keys"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     pub_key, pri_key = make_key_pair()
     if domain.dkimkeys:
         dkimkeys = domain.dkimkeys[0]
     else:
         dkimkeys = DKIMKeys()
     dkimkeys.pub_key = pub_key
     dkimkeys.pri_key = pri_key
     try:
         if domain.dkimkeys:
             domain.dkimkeys[0] = dkimkeys
         else:
             domain.dkimkeys.append(dkimkeys)
         Session.add(dkimkeys)
         Session.add(domain)
         Session.commit()
         info = DKIMGEN_MSG % dict(d=domain.name)
         audit_log(c.user.username, 3, info, request.host,
                   request.remote_addr, now())
         flash(_('DKIM keys successfully generated'))
     except DatabaseError:
         flash_alert(_('Generation of DKIM keys failed'))
     redirect(url('domain-dkim', domainid=domain.id))
Esempio n. 33
0
 def adddestination(self, domainid):
     "Add a destination server"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     c.form = AddDeliveryServerForm(request.POST, csrf_context=session)
     c.id = domainid
     if request.POST and c.form.validate():
         server = DeliveryServer()
         for field in c.form:
             if field.name != 'csrf_token':
                 setattr(server, field.name, field.data)
         try:
             domain.servers.append(server)
             Session.add(server)
             Session.add(domain)
             Session.commit()
             info = ADDDELSVR_MSG % dict(d=domain.name, ds=server.address)
             audit_log(c.user.username,
                     3, unicode(info), request.host,
                     request.remote_addr, now())
             flash(_('The destination server has been created'))
             redirect(url(controller='domains', action='detail',
                     domainid=domain.id))
         except IntegrityError:
             Session.rollback()
             flash_alert(
                 _('The destination server %(dest)s already exists ') %
                 dict(dest=server.address))
     return render('/domains/adddestination.html')
Esempio n. 34
0
    def edit_account_sigs(self, sigid):
        "Edit account signatures"
        sign = self._get_usrsign(sigid)
        if not sign:
            abort(404)

        c.form = SigForm(request.POST, sign, csrf_context=session)
        del c.form['signature_type']
        if request.POST and c.form.validate():
            try:
                updated = False
                for field in c.form:
                    if (field.name != 'csrf_token'
                            and field.data != getattr(sign, field.name)):
                        updated = True
                        setattr(sign, field.name, field.data)
                if updated:
                    Session.add(sign)
                    Session.commit()
                    save_user_sig.apply_async(args=[sigid], queue='msbackend')
                    info = UPDATEACCSIG_MSG % dict(u=sign.user.username)
                    audit_log(c.user.username, 2, info, request.host,
                              request.remote_addr, now())
                    flash(_('The signature has been updated'))
                else:
                    flash(_('No changes made, signature not updated'))
                redirect(url('account-detail', userid=sign.user_id))
            except IntegrityError:
                Session.rollback()
                flash(_('Error occured updating the signature'))
        c.sign = sign
        return render('/settings/account_editsig.html')
Esempio n. 35
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')
Esempio n. 36
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')
Esempio n. 37
0
    def confirm_delete(self):
        "Confirm bulk delete of domains"
        domainids = session.get('bulk_domain_delete', [])
        if not domainids:
            redirect(url(controller='domains', action='index'))

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

        domains = Session.query(Domain).filter(Domain.id.in_(domainids))\
                    .options(joinedload('organizations'))
        domcount = Session.query(Domain.id).filter(Domain.id.in_(domainids))

        if c.user.is_domain_admin:
            domains = domains.join(domain_owners,
                        (oa,
                        domain_owners.c.organization_id ==
                        oa.c.organization_id))\
                        .filter(oa.c.user_id == c.user.id)
            domcount = domcount.join(domain_owners,
                        (oa, domain_owners.c.organization_id ==
                        oa.c.organization_id))\
                        .filter(oa.c.user_id == c.user.id)

        if request.POST:
            tasks = []
            for domain in domains.all():
                info = DELETEDOMAIN_MSG % dict(d=domain.name)
                tasks.append((c.user.username,
                        4, unicode(info), request.host,
                        request.remote_addr,
                        now()))
                Session.delete(domain)
            Session.commit()
            del session['bulk_domain_delete']
            session.save()
            for task in tasks:
                audit_log(*task)
            flash(_('The domains have been deleted'))
            redirect(url(controller='domains'))
        else:
            flash(_('The following domains are about to be deleted,'
                    ' this action is not reversible, Do you wish to'
                    ' continue ?'))

        try:
            c.page = paginate.Page(domains, page=1,
                                    items_per_page=num_items,
                                    item_count=domcount.count())
        except DataError:
            flash_alert(_('An error occured try again'))
            redirect(url(controller='domains', action='index'))
        return render('/domains/confirmbulkdel.html')
Esempio n. 38
0
    def confirm_delete(self):
        "Confirm bulk delete of domains"
        domainids = session.get('bulk_domain_delete', [])
        if not domainids:
            redirect(url(controller='domains', action='index'))

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

        domains = Session.query(Domain).filter(Domain.id.in_(domainids))\
                    .options(joinedload('organizations'))
        domcount = Session.query(Domain.id).filter(Domain.id.in_(domainids))

        if c.user.is_domain_admin:
            domains = domains.join(domain_owners,
                        (oa,
                        domain_owners.c.organization_id ==
                        oa.c.organization_id))\
                        .filter(oa.c.user_id == c.user.id)
            domcount = domcount.join(domain_owners,
                        (oa, domain_owners.c.organization_id ==
                        oa.c.organization_id))\
                        .filter(oa.c.user_id == c.user.id)

        if request.POST:
            tasks = []
            for domain in domains.all():
                info = DELETEDOMAIN_MSG % dict(d=domain.name)
                tasks.append((c.user.username, 4, info, request.host,
                              request.remote_addr, now()))
                Session.delete(domain)
            Session.commit()
            del session['bulk_domain_delete']
            session.save()
            for task in tasks:
                audit_log(*task)
            flash(_('The domains have been deleted'))
            redirect(url(controller='domains'))
        else:
            flash(
                _('The following domains are about to be deleted,'
                  ' this action is not reversible, Do you wish to'
                  ' continue ?'))

        try:
            c.page = paginate.Page(domains,
                                   page=1,
                                   items_per_page=num_items,
                                   item_count=domcount.count())
        except DataError:
            flash_alert(_('An error occured try again'))
            redirect(url(controller='domains', action='index'))
        return render('/domains/confirmbulkdel.html')
Esempio n. 39
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')
Esempio n. 40
0
def pie_report_query(user, reportid, num_of_days):
    "Run report query"
    query = ReportQuery(user, reportid)
    if int(num_of_days) > 0:
        numofdays = datetime.timedelta(days=num_of_days)
        startdate = now().date() - numofdays
        query = query.get().filter(Message.timestamp > str(startdate))
        data = query[:10]
    else:
        data = query.get()[:10]
    return data
Esempio n. 41
0
    def export_status(self, taskid):
        "export 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='domains', 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='domains'))
            results = dict(
                f=True if not result.result['global_error'] else False,
                id=taskid,
                global_error=result.result['global_error'])
        else:
            session['dexport-count'] += 1
            if (session['dexport-count'] >= 10
                    and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                flash_alert(
                    _('The export could not be processed,'
                      ' try again later'))
                del session['dexport-count']
                session.save()
                redirect(url(controller='domains'))
            finished = False
            results = dict(f=None, global_error=None)

        c.finished = finished
        c.results = results
        c.success = result.successful()
        d = request.GET.get('d', None)
        if finished and (d and d == 'y'):
            info = EXPORTDOM_MSG % dict(d='all')
            audit_log(c.user.username, 5, info, request.host,
                      request.remote_addr, now())
            response.content_type = 'text/csv'
            response.headers['Cache-Control'] = 'max-age=0'
            csvdata = result.result['f']
            disposition = 'attachment; filename=domains-export-%s.csv' % taskid
            response.headers['Content-Disposition'] = str(disposition)
            response.headers['Content-Length'] = len(csvdata)
            return csvdata
        return render('/domains/exportstatus.html')
Esempio n. 42
0
    def export_status(self, taskid):
        "export 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='domains', 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='domains'))
            results = dict(
                        f=True if not result.result['global_error'] else False,
                        id=taskid, global_error=result.result['global_error'])
        else:
            session['dexport-count'] += 1
            if (session['dexport-count'] >= 10 and
                result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                flash_alert(_('The export could not be processed,'
                            ' try again later'))
                del session['dexport-count']
                session.save()
                redirect(url(controller='domains'))
            finished = False
            results = dict(f=None, global_error=None)

        c.finished = finished
        c.results = results
        c.success = result.successful()
        d = request.GET.get('d', None)
        if finished and (d and d == 'y'):
            info = EXPORTDOM_MSG % dict(d='all')
            audit_log(c.user.username,
                    5, unicode(info), request.host,
                    request.remote_addr, now())
            response.content_type = 'text/csv'
            response.headers['Cache-Control'] = 'max-age=0'
            csvdata = result.result['f']
            disposition = 'attachment; filename=domains-export-%s.csv' % taskid
            response.headers['Content-Disposition'] = str(disposition)
            response.headers['Content-Length'] = len(csvdata)
            return csvdata
        return render('/domains/exportstatus.html')
Esempio n. 43
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')
Esempio n. 44
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')
Esempio n. 45
0
    def export_status(self, taskid):
        "export 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="domains", 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="domains"))
            results = dict(
                f=True if not result.result["global_error"] else False,
                id=taskid,
                global_error=result.result["global_error"],
            )
        else:
            session["dexport-count"] += 1
            if session["dexport-count"] >= 10 and result.state in ["PENDING", "RETRY", "FAILURE"]:
                result.revoke()
                flash_alert(_("The export could not be processed," " try again later"))
                del session["dexport-count"]
                session.save()
                redirect(url(controller="domains"))
            finished = False
            results = dict(f=None, global_error=None)

        c.finished = finished
        c.results = results
        c.success = result.successful()
        d = request.GET.get("d", None)
        if finished and (d and d == "y"):
            info = EXPORTDOM_MSG % dict(d="all")
            audit_log(c.user.username, 5, info, request.host, request.remote_addr, now())
            response.content_type = "text/csv"
            response.headers["Cache-Control"] = "max-age=0"
            csvdata = result.result["f"]
            disposition = "attachment; filename=domains-export-%s.csv" % taskid
            response.headers["Content-Disposition"] = str(disposition)
            response.headers["Content-Length"] = len(csvdata)
            return csvdata
        return render("/domains/exportstatus.html")
Esempio n. 46
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')
Esempio n. 47
0
    def server_status(self, serverid):
        "Display server status"
        server = self._get_server(serverid)
        if not server:
            abort(404)

        totals = DailyTotals(Session, c.user)
        mailq = MailQueue(Session, c.user)
        totals = totals.get(server.hostname)
        inbound = mailq.get(1, server.hostname)[0]
        outbound = mailq.get(2, server.hostname)[0]

        statusdict = dict(total=totals.total,
                        mta=0,
                        scanners=0,
                        av=0,
                        clean_mail=totals.clean,
                        high_spam=totals.highspam,
                        virii=totals.virii,
                        spam_mail=totals.lowspam,
                        inq=inbound,
                        outq=outbound,
                        otherinfected=totals.infected,
                        uptime='Unknown',
                        time=None,
                        load=(0, 0, 0),
                        mem=dict(free=0, used=0, total=0,
                                percent=0),
                        partitions=[],
                        net={},
                        cpu=0)
        try:
            task = systemstatus.apply_async(queue=server.hostname)
            task.wait(30)
            hoststatus = task.result
            statusdict.update(hoststatus)
            info = HOSTSTATUS_MSG % dict(n=server.hostname)
            audit_log(c.user.username,
                    1, info, request.host,
                    request.remote_addr, now())
        except (TimeoutError, QueueNotFound):
            pass

        c.server = server
        c.status = statusdict
        return render('/status/serverstatus.html')
Esempio n. 48
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')
Esempio n. 49
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)
     #del c.form.protocol
     if request.POST and c.form.validate():
         updated = False
         kw = dict(domainid=server.domain_id)
         for field in c.form:
             if field.name == 'protocol' or field.name == 'csrf_token':
                 continue
             if (field.data != getattr(server, field.name)
                 and field.data != ''):
                 setattr(server, field.name, field.data)
                 updated = True
             if (field.name == 'user_map_template' and
                 field.data != getattr(server, field.name)):
                 setattr(server, field.name, field.data)
                 updated = True
         if updated:
             try:
                 Session.add(server)
                 Session.commit()
                 flash(_('The authentication settings have been updated'))
                 self.invalidate = 1
                 self._get_authserver(authid)
                 info = UPDATEAUTHSVR_MSG % dict(d=server.domains.name,
                                                 ds=server.address)
                 audit_log(c.user.username,
                         2, unicode(info), request.host,
                         request.remote_addr, now())
                 redirect(url('domain-detail', **kw))
             except IntegrityError:
                 Session.rollback()
                 flash_alert(_('The authentication settings update failed'))
         else:
             flash_info(_('No changes were made to the '
                         'authentication settings'))
             redirect(url('domain-detail', **kw))
     c.domainid = server.domains.id
     c.domainname = server.domains.name
     c.authid = authid
     return render('/domains/editauth.html')
Esempio n. 50
0
    def audit_export_status(self, taskid):
        "Audit log export 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('status-audit-logs'))

        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('status-audit-logs'))
        else:
            session['exportauditlog-counter'] += 1
            session.save()
            if (session['exportauditlog-counter'] >= 20 and
                result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                del session['exportauditlog-counter']
                session.save()
                flash_alert(_('The audit log export failed, try again later'))
                redirect(url('status-audit-logs'))
            finished = False

        c.finished = finished
        c.results = result.result
        c.success = result.successful()
        d = request.GET.get('d', None)
        if finished and (d and d == 'y'):
            audit_log(c.user.username,
                    5, AUDITLOGEXPORT_MSG, request.host,
                    request.remote_addr, now())
            response.content_type = result.result['content_type']
            response.headers['Cache-Control'] = 'max-age=0'
            respdata = result.result['f']
            disposition = 'attachment; filename=%s' % result.result['filename']
            response.headers['Content-Disposition'] = str(disposition)
            response.headers['Content-Length'] = len(respdata)
            return respdata
        return render('/status/auditexportstatus.html')
Esempio n. 51
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)
     #del c.form.protocol
     if request.POST and c.form.validate():
         updated = False
         kw = dict(domainid=server.domain_id)
         for field in c.form:
             if field.name == 'protocol' or field.name == 'csrf_token':
                 continue
             if (field.data != getattr(server, field.name)
                     and field.data != ''):
                 setattr(server, field.name, field.data)
                 updated = True
             if (field.name == 'user_map_template'
                     and field.data != getattr(server, field.name)):
                 setattr(server, field.name, field.data)
                 updated = True
         if updated:
             try:
                 Session.add(server)
                 Session.commit()
                 flash(_('The authentication settings have been updated'))
                 self.invalidate = 1
                 self._get_authserver(authid)
                 info = UPDATEAUTHSVR_MSG % dict(d=server.domains.name,
                                                 ds=server.address)
                 audit_log(c.user.username, 2, info, request.host,
                           request.remote_addr, now())
                 redirect(url('domain-detail', **kw))
             except IntegrityError:
                 Session.rollback()
                 flash_alert(_('The authentication settings update failed'))
         else:
             flash_info(
                 _('No changes were made to the '
                   'authentication settings'))
             redirect(url('domain-detail', **kw))
     c.domainid = server.domains.id
     c.domainname = server.domains.name
     c.authid = authid
     return render('/domains/editauth.html')
Esempio n. 52
0
    def server_salint_stat(self, serverid):
        "Display server salint output"
        server = self._get_server(serverid)
        if not server:
            abort(404)

        try:
            task = salint.apply_async(queue=server.hostname)
            task.wait(30)
            result = task.result
            info = HOSTSALINT_MSG % dict(n=server.hostname)
            audit_log(c.user.username, 1, info, request.host,
                      request.remote_addr, now())
        except (TimeoutError, QueueNotFound, OSError):
            result = []
        c.server = server
        c.data = result
        return render('/status/salint.html')
Esempio n. 53
0
    def server_bayes_status(self, serverid):
        "Display bayes stats"
        server = self._get_server(serverid)
        if not server:
            abort(404)

        try:
            task = bayesinfo.apply_async(queue=server.hostname)
            task.wait(30)
            result = task.result
            info = HOSTBAYES_MSG % dict(n=server.hostname)
            audit_log(c.user.username, 1, info, request.host,
                      request.remote_addr, now())
        except (TimeoutError, QueueNotFound, OSError):
            result = {}
        c.server = server
        c.data = result
        return render('/status/bayes.html')
Esempio n. 54
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')
Esempio n. 55
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')
Esempio n. 56
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, unicode(info), request.host,
                    request.remote_addr, 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')
Esempio n. 57
0
    def server_status(self, serverid):
        "Display server status"
        server = self._get_server(serverid)
        if not server:
            abort(404)

        totals = DailyTotals(Session, c.user)
        mailq = MailQueue(Session, c.user)
        totals = totals.get(server.hostname)
        inbound = mailq.get(1, server.hostname)[0]
        outbound = mailq.get(2, server.hostname)[0]

        statusdict = dict(total=totals.total,
                          mta=0,
                          scanners=0,
                          av=0,
                          clean_mail=totals.clean,
                          high_spam=totals.highspam,
                          virii=totals.virii,
                          spam_mail=totals.lowspam,
                          inq=inbound,
                          outq=outbound,
                          otherinfected=totals.infected,
                          uptime='Unknown',
                          time=None,
                          load=(0, 0, 0),
                          mem=dict(free=0, used=0, total=0, percent=0),
                          partitions=[],
                          net={},
                          cpu=0)
        try:
            task = systemstatus.apply_async(queue=server.hostname)
            task.wait(30)
            hoststatus = task.result
            statusdict.update(hoststatus)
            info = HOSTSTATUS_MSG % dict(n=server.hostname)
            audit_log(c.user.username, 1, info, request.host,
                      request.remote_addr, now())
        except (TimeoutError, QueueNotFound):
            pass

        c.server = server
        c.status = statusdict
        return render('/status/serverstatus.html')
Esempio n. 58
0
    def audit_export_status(self, taskid):
        "Audit log export 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('status-audit-logs'))

        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('status-audit-logs'))
        else:
            session['exportauditlog-counter'] += 1
            session.save()
            if (session['exportauditlog-counter'] >= 20
                    and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                del session['exportauditlog-counter']
                session.save()
                flash_alert(_('The audit log export failed, try again later'))
                redirect(url('status-audit-logs'))
            finished = False

        c.finished = finished
        c.results = result.result
        c.success = result.successful()
        d = request.GET.get('d', None)
        if finished and (d and d == 'y'):
            audit_log(c.user.username, 5, AUDITLOGEXPORT_MSG, request.host,
                      request.remote_addr, now())
            response.content_type = result.result['content_type']
            response.headers['Cache-Control'] = 'max-age=0'
            respdata = result.result['f']
            disposition = 'attachment; filename=%s' % result.result['filename']
            response.headers['Content-Disposition'] = str(disposition)
            response.headers['Content-Length'] = len(respdata)
            return respdata
        return render('/status/auditexportstatus.html')
Esempio n. 59
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')
Esempio n. 60
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')