Esempio n. 1
0
    def addalias(self, domainid):
        "Add alias domain"
        domain = self._get_domain(domainid)
        if not domain:
            abort(404)

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

        c.domainid = domain.id
        c.domainname = domain.name
        return self.render('/domains/addalias.html')
Esempio n. 2
0
    def editalias(self, aliasid):
        "Edit alias domain"
        alias = self._get_alias(aliasid)
        if not alias:
            abort(404)

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

        c.aliasid = aliasid
        c.domainid = alias.domain_id
        c.domainname = alias.domain.name
        return self.render('/domains/editalias.html')
Esempio n. 3
0
 def edit_auth(self, authid):
     "Edit auth server"
     server = self._get_authserver(authid)
     if not server:
         abort(404)
     c.form = AddAuthForm(request.POST, server, csrf_context=session)
     if request.method == 'POST' and c.form.validate():
         kwd = dict(domainid=server.domain_id)
         if auth_update_if_changed(c.form, server):
             try:
                 edit_auth(server, c.user, request.host,
                         request.remote_addr)
                 flash(_('The authentication settings have been updated'))
                 self.invalidate = 1
                 self._get_authserver(authid)
                 kwd['uc'] = 1
                 redirect(url('domain-detail', **kwd))
             except IntegrityError:
                 Session.rollback()
                 msg = _('The authentication settings update failed')
                 flash_alert(msg)
                 log.info(msg)
         else:
             msg = _('No changes were made to the authentication settings')
             flash_info(msg)
             log.info(msg)
             redirect(url('domain-detail', **kwd))
     c.domainid = server.domains.id
     c.domainname = server.domains.name
     c.authid = authid
     return self.render('/domains/editauth.html')
Esempio n. 4
0
    def editalias(self, aliasid):
        "Edit alias domain"
        alias = self._get_alias(aliasid)
        if not alias:
            abort(404)

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

        c.aliasid = aliasid
        c.domainid = alias.domain_id
        c.domainname = alias.domain.name
        return self.render('/domains/editalias.html')
Esempio n. 5
0
 def editdestination(self, destinationid):
     "Edit destination server"
     server = self._get_server(destinationid)
     if not server:
         abort(404)
     c.form = AddDeliveryServerForm(request.POST,
                                     server,
                                     csrf_context=session)
     if request.method == 'POST' and c.form.validate():
         kwd = dict(domainid=server.domain_id)
         if update_if_changed(c.form, server):
             try:
                 update_destination(server, c.user, request.host,
                                     request.remote_addr)
                 self.invalidate = 1
                 self._get_server(destinationid)
                 kwd['uc'] = 1
                 flash(_('The destination server has been updated'))
                 redirect(url('domain-detail', **kwd))
             except IntegrityError:
                 Session.rollback()
                 msg = _('The update failed')
                 flash_alert(msg)
                 log.info(msg)
         else:
             msg = _('No changes were made to the destination server')
             flash_info(msg)
             log.info(msg)
             redirect(url('domain-detail', **kwd))
     c.id = destinationid
     c.domainid = server.domain_id
     return self.render('/domains/editdestination.html')
Esempio n. 6
0
    def editaddress(self, addressid):
        "Edit address"
        address = get_address(addressid)
        if not address:
            abort(404)

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

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

        c.form = user_update_form(user, c.user, request.POST, session)
        if request.method == 'POST' and c.form.validate():
            kwd = dict(userid=user.id)
            if update_changed(c.form, FORM_FIELDS, user):
                try:
                    update_user(user, c.user, request.host,
                                request.remote_addr)
                    flash(_('The account has been updated'))
                    kwd['uc'] = 1
                except IntegrityError:
                    Session.rollback()
                    flash_alert(
                        _('The account: %(acc)s could not be updated') %
                        dict(acc=user.username))
                if (user.id == c.user.id and c.form.active
                        and c.form.active.data is False):
                    redirect(url('/logout'))
            else:
                flash_info(_('No changes made to the account'))
            redirect(url(controller='accounts', action='detail', **kwd))
        c.fields = FORM_FIELDS
        c.id = userid
        return self.render('/accounts/edit.html')
Esempio n. 11
0
 def editdestination(self, destinationid):
     "Edit destination server"
     server = self._get_server(destinationid)
     if not server:
         abort(404)
     c.form = AddDeliveryServerForm(request.POST,
                                    server,
                                    csrf_context=session)
     if request.method == 'POST' and c.form.validate():
         kwd = dict(domainid=server.domain_id)
         if update_if_changed(c.form, server):
             try:
                 update_destination(server, c.user, request.host,
                                    request.remote_addr)
                 self.invalidate = 1
                 self._get_server(destinationid)
                 kwd['uc'] = 1
                 flash(_('The destination server has been updated'))
                 redirect(url('domain-detail', **kwd))
             except IntegrityError:
                 Session.rollback()
                 msg = _('The update failed')
                 flash_alert(msg)
                 log.info(msg)
         else:
             msg = _('No changes were made to the destination server')
             flash_info(msg)
             log.info(msg)
             redirect(url('domain-detail', **kwd))
     c.id = destinationid
     c.domainid = server.domain_id
     return self.render('/domains/editdestination.html')
Esempio n. 12
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. 13
0
    def adddestination(self, domainid):
        "Add a destination server"
        domain = self._get_domain(domainid)
        if not domain:
            abort(404)

        c.id = domainid
        c.form = AddDeliveryServerForm(request.POST, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            server = DeliveryServer()
            server.from_form(c.form)
            try:
                create_destination(domain, server, c.user, request.host,
                                   request.remote_addr)
                flash(_('The destination server has been created'))
                redirect(
                    url(controller='domains',
                        action='detail',
                        domainid=domain.id))
            except IntegrityError:
                Session.rollback()
                msg = _('The destination server %(dest)s already exists ') % \
                        dict(dest=server.address)
                flash_alert(msg)
                log.info(msg)
        return self.render('/domains/adddestination.html')
Esempio n. 14
0
    def edit(self, userid):
        """GET /accounts/edit/id: Form to edit an existing item"""
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = user_update_form(user, c.user, request.POST, session)
        if request.method == 'POST' and c.form.validate():
            kwd = dict(userid=user.id)
            if update_changed(c.form, FORM_FIELDS, user):
                try:
                    update_user(user, c.user, request.host,
                                request.remote_addr)
                    flash(_('The account has been updated'))
                    kwd['uc'] = 1
                except IntegrityError:
                    Session.rollback()
                    flash_alert(
                        _('The account: %(acc)s could not be updated') %
                        dict(acc=user.username))
                if (user.id == c.user.id and c.form.active and
                    c.form.active.data is False):
                    redirect(url('/logout'))
            else:
                flash_info(_('No changes made to the account'))
            redirect(url(controller='accounts', action='detail', **kwd))
        c.fields = FORM_FIELDS
        c.id = userid
        return self.render('/accounts/edit.html')
Esempio n. 15
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. 16
0
    def add(self, orgid=None):
        "Add a domain"
        c.form = AddDomainForm(request.POST, csrf_context=session)
        c.form.organizations.query = get_organizations(orgid)
        if request.method == 'POST' and c.form.validate():
            try:
                domain = create_domain(c.form, c.user, request.host,
                                       request.remote_addr)
                try:
                    from baruwa.tasks.invite import create_mx_records
                    create_mx_records.apply_async(args=[domain.name])
                except ImportError:
                    pass
                flash(
                    _('The domain: %(dom)s has been created') %
                    dict(dom=domain.name))
                redirect(url(controller='domains'))
            except IntegrityError:
                Session.rollback()
                msg = _('The domain name %(dom)s already exists') % \
                        dict(dom=domain.name)
                flash_alert(msg)
                log.info(msg)

        return self.render('/domains/new.html')
Esempio n. 17
0
    def addaddress(self, userid):
        "Add address"
        user = self._get_user(userid)
        if not user:
            abort(404)

        c.form = AddressForm(request.POST, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            try:
                addr = create_address(c.form, user, c.user, request.host,
                                      request.remote_addr)
                flash(
                    _('The alias address %(address)s was successfully created.'
                      % dict(address=addr.address)))
            except IntegrityError:
                Session.rollback()
                msg = _('The address %(addr)s already exists') % \
                        dict(addr=c.form.address.data)
                flash_alert(msg)
                log.info(msg)
            except NoResultFound:
                domain = c.form.address.data.split('@')[1]
                msg = _('Domain: %(d)s does not belong to you') % \
                        dict(d=domain)
                flash(msg)
                log.info(msg)
            redirect(url(controller='accounts', action='detail',
                         userid=userid))
        c.id = userid
        return self.render('/accounts/addaddress.html')
Esempio n. 18
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. 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, info, request.host,
                 request.remote_addr, datetime.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 addalias(self, domainid):
        "Add alias domain"
        domain = self._get_domain(domainid)
        if not domain:
            abort(404)

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

        c.domainid = domain.id
        c.domainname = domain.name
        return self.render('/domains/addalias.html')
Esempio n. 21
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")
Esempio n. 22
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")
Esempio n. 23
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, datetime.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. 24
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. 25
0
 def editdestination(self, destinationid):
     "Edit destination server"
     server = self._get_server(destinationid)
     if not server:
         abort(404)
     c.form = AddDeliveryServerForm(request.POST, server, csrf_context=session)
     if request.POST and c.form.validate():
         updated = False
         kw = dict(domainid=server.domain_id)
         for field in c.form:
             if field.name != "csrf_token" 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 destination server has been updated"))
                 info = UPDATEDELSVR_MSG % dict(d=server.domains.name, ds=server.address)
                 audit_log(c.user.username, 2, info, request.host, request.remote_addr, datetime.now())
                 self.invalidate = 1
                 self._get_server(destinationid)
                 redirect(url("domain-detail", **kw))
             except IntegrityError:
                 Session.rollback()
                 flash_alert(_("The update failed"))
         else:
             flash_info(_("No changes were made to the destination server"))
             redirect(url("domain-detail", **kw))
     c.id = destinationid
     c.domainid = server.domain_id
     return render("/domains/editdestination.html")
Esempio n. 26
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, datetime.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. 27
0
    def editaddress(self, addressid):
        "Edit address"
        address = get_address(addressid)
        if not address:
            abort(404)

        c.form = AddressForm(request.POST, address, csrf_context=session)
        if request.method == 'POST' and c.form.validate():
            try:
                if (address.address != c.form.address.data
                        or address.enabled != c.form.enabled.data):
                    update_address(c.form, address, c.user, request.host,
                                   request.remote_addr)
                    flash(_('The alias address has been updated'))
                else:
                    flash_info(_('No changes were made to the address'))
            except IntegrityError:
                Session.rollback()
                msg = _('The address %(addr)s already exists') % \
                        dict(addr=c.form.address.data)
                flash_alert(msg)
                log.info(msg)
            except NoResultFound:
                domain = c.form.address.data.split('@')[1]
                msg = _('Domain: %(d)s does not belong to you') % \
                        dict(d=domain)
                flash(msg)
                log.info(msg)
            redirect(
                url(controller='accounts',
                    action='detail',
                    userid=address.user_id))
        c.id = addressid
        c.userid = address.user_id
        return self.render('/accounts/editaddress.html')
Esempio n. 28
0
 def edit_auth(self, authid):
     "Edit auth server"
     server = self._get_authserver(authid)
     if not server:
         abort(404)
     c.form = AddAuthForm(request.POST, server, csrf_context=session)
     if request.method == 'POST' and c.form.validate():
         kwd = dict(domainid=server.domain_id)
         if auth_update_if_changed(c.form, server):
             try:
                 edit_auth(server, c.user, request.host,
                           request.remote_addr)
                 flash(_('The authentication settings have been updated'))
                 self.invalidate = 1
                 self._get_authserver(authid)
                 kwd['uc'] = 1
                 redirect(url('domain-detail', **kwd))
             except IntegrityError:
                 Session.rollback()
                 msg = _('The authentication settings update failed')
                 flash_alert(msg)
                 log.info(msg)
         else:
             msg = _('No changes were made to the authentication settings')
             flash_info(msg)
             log.info(msg)
             redirect(url('domain-detail', **kwd))
     c.domainid = server.domains.id
     c.domainname = server.domains.name
     c.authid = authid
     return self.render('/domains/editauth.html')
Esempio n. 29
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. 30
0
 def add_auth(self, domainid):
     "Add auth server"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     c.form = AddAuthForm(request.POST, csrf_context=session)
     if request.method == 'POST' and c.form.validate():
         server = AuthServer()
         server.from_form(c.form)
         try:
             create_auth(domain, server, c.user,
                         request.host, request.remote_addr)
             flash(_('The authentication settings have been created'))
             redirect(url(controller='domains', action='detail',
                     domainid=domain.id))
         except IntegrityError:
             Session.rollback()
             auth = dict(AUTH_PROTOCOLS)[str(server.protocol)]
             msg = _('The host %(dest)s already configured for %(auth)s '
                     'authentication for this domain') % \
                     dict(dest=server.address, auth=auth)
             flash_alert(msg)
             log.info(msg)
     c.domainid = domainid
     c.domainname = domain.name
     return self.render('/domains/addauth.html')
Esempio n. 31
0
 def add_auth(self, domainid):
     "Add auth server"
     domain = self._get_domain(domainid)
     if not domain:
         abort(404)
     c.form = AddAuthForm(request.POST, csrf_context=session)
     if request.method == 'POST' and c.form.validate():
         server = AuthServer()
         server.from_form(c.form)
         try:
             create_auth(domain, server, c.user, request.host,
                         request.remote_addr)
             flash(_('The authentication settings have been created'))
             redirect(
                 url(controller='domains',
                     action='detail',
                     domainid=domain.id))
         except IntegrityError:
             Session.rollback()
             auth = dict(AUTH_PROTOCOLS)[str(server.protocol)]
             msg = _('The host %(dest)s already configured for %(auth)s '
                     'authentication for this domain') % \
                     dict(dest=server.address, auth=auth)
             flash_alert(msg)
             log.info(msg)
     c.domainid = domainid
     c.domainname = domain.name
     return self.render('/domains/addauth.html')
Esempio n. 32
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. 33
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. 34
0
    def testdestination(self, destinationid):
        "Test mail destination server"
        server = self._get_server(destinationid)
        if not server:
            abort(404)

        taskid = request.GET.get('taskid', None)
        if not taskid:
            to_addr = 'postmaster@%s' % server.domains.name
            task = test_smtp_server.apply_async(args=[
                                    server.address,
                                    server.port,
                                    '<>',
                                    to_addr,
                                    server.id,
                                    3])
            taskid = task.task_id
            if not 'taskids' in session:
                session['taskids'] = []
            session['taskids'].append(taskid)
            session['testdest-count'] = 1
            session.save()
            redirect(url.current(taskid=taskid))
        else:
            result = AsyncResult(taskid)
            if result is None or taskid not in session['taskids']:
                flash(_('The connection test failed try again later'))
                redirect(url('domain-detail', domainid=server.domain_id))
            if result.ready():
                if ('smtp' in result.result and 'ping' in result.result
                    and result.result['smtp'] and result.result['ping']):
                    flash(_('The server: %s is up and accepting mail from us'
                        % server.address))
                else:
                    if 'ping' in result.result['errors']:
                        errors = result.result['errors']['ping']
                    else:
                        errors = result.result['errors']['smtp']
                    flash(_('The server: %s is not accepting mail from us: %s')
                        % (server.address, errors))
                redirect(url('domain-detail', domainid=server.domain_id))
            else:
                session['testdest-count'] += 1
                session.save()
                if (session['testdest-count'] >= 10 and
                    result.state in ['PENDING', 'RETRY', 'FAILURE']):
                    result.revoke()
                    del session['testdest-count']
                    session.save()
                    flash_alert('Failed to initialize backend,'
                                ' try again later')
                    redirect(url('domain-detail', domainid=server.domain_id))

        c.server = server
        c.domainid = server.domain_id
        c.taskid = taskid
        c.finished = False
        return render('/domains/testdestination.html')
Esempio n. 35
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. 36
0
    def testdestination(self, destinationid):
        "Test mail destination server"
        server = self._get_server(destinationid)
        if not server:
            abort(404)

        taskid = request.GET.get('taskid', None)
        if not taskid:
            to_addr = 'postmaster@%s' % server.domains.name
            task = test_smtp_server.apply_async(args=[
                server.address, server.port, '<>', to_addr, server.id, 3
            ])
            taskid = task.task_id
            session['taskids'].append(taskid)
            session['testdest-count'] = 1
            session.save()
            redirect(url.current(taskid=taskid))
        else:
            result = AsyncResult(taskid)
            if result is None or taskid not in session['taskids']:
                flash(_('The connection test failed try again later'))
                redirect(url('domain-detail', domainid=server.domain_id))
            if result.ready():
                if ('smtp' in result.result and 'ping' in result.result
                        and result.result['smtp'] and result.result['ping']):
                    flash(
                        _('The server: %s is up and accepting mail from us' %
                          server.address))
                else:
                    if 'ping' in result.result['errors']:
                        errors = result.result['errors']['ping']
                    else:
                        errors = result.result['errors']['smtp']
                    flash(
                        _('The server: %s is not accepting mail from us: %s') %
                        (server.address, errors))
                redirect(url('domain-detail', domainid=server.domain_id))
            else:
                session['testdest-count'] += 1
                session.save()
                if (session['testdest-count'] >= 10
                        and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                    result.revoke()
                    del session['testdest-count']
                    session.save()
                    flash_alert('Failed to initialize backend,'
                                ' try again later')
                    redirect(url('domain-detail', domainid=server.domain_id))

        c.server = server
        c.domainid = server.domain_id
        c.taskid = taskid
        c.finished = False
        return render('/domains/testdestination.html')
Esempio n. 37
0
    def testdestination(self, destinationid):
        "Test mail destination server"
        server = self._get_server(destinationid)
        if not server:
            abort(404)

        taskid = request.GET.get("taskid", None)
        if not taskid:
            to_addr = "postmaster@%s" % server.domains.name
            task = test_smtp_server.apply_async(args=[server.address, server.port, "<>", to_addr, server.id, 3])
            taskid = task.task_id
            session["taskids"].append(taskid)
            session["testdest-count"] = 1
            session.save()
            redirect(url.current(taskid=taskid))
        else:
            result = AsyncResult(taskid)
            if result is None or taskid not in session["taskids"]:
                flash(_("The connection test failed try again later"))
                redirect(url("domain-detail", domainid=server.domain_id))
            if result.ready():
                if (
                    "smtp" in result.result
                    and "ping" in result.result
                    and result.result["smtp"]
                    and result.result["ping"]
                ):
                    flash(_("The server: %s is up and accepting mail from us" % server.address))
                else:
                    if "ping" in result.result["errors"]:
                        errors = result.result["errors"]["ping"]
                    else:
                        errors = result.result["errors"]["smtp"]
                    flash(_("The server: %s is not accepting mail from us: %s") % (server.address, errors))
                redirect(url("domain-detail", domainid=server.domain_id))
            else:
                session["testdest-count"] += 1
                session.save()
                if session["testdest-count"] >= 10 and result.state in ["PENDING", "RETRY", "FAILURE"]:
                    result.revoke()
                    del session["testdest-count"]
                    session.save()
                    flash_alert("Failed to initialize backend," " try again later")
                    redirect(url("domain-detail", domainid=server.domain_id))

        c.server = server
        c.domainid = server.domain_id
        c.taskid = taskid
        c.finished = False
        return render("/domains/testdestination.html")
Esempio n. 38
0
    def audit_export(self, isquery=None, format=None):
        "Export audit logs"
        query = request.GET.get('q', None)
        if isquery and query is None:
            flash_alert(_('No query specified for audit log export'))
            redirect(url('status-audit-logs'))

        task = export_auditlog.apply_async(args=[format, query])
        if not 'taskids' in session:
            session['taskids'] = []
        session['taskids'].append(task.task_id)
        session['exportauditlog-counter'] = 1
        session.save()
        redirect(url('status-auditlog-export-status', taskid=task.task_id))
Esempio n. 39
0
    def audit_export(self, isquery=None, format=None):
        "Export audit logs"
        query = request.GET.get('q', None)
        if isquery and query is None:
            flash_alert(_('No query specified for audit log export'))
            redirect(url('status-audit-logs'))

        task = export_auditlog.apply_async(args=[format, query])
        if not 'taskids' in session:
            session['taskids'] = []
        session['taskids'].append(task.task_id)
        session['exportauditlog-counter'] = 1
        session.save()
        redirect(url('status-auditlog-export-status', taskid=task.task_id))
Esempio n. 40
0
    def process(self, taskid, format=None):
        "process a taskset"
        result = GroupResult.restore(taskid, backend=RBACKEND)
        if (result is None or 'taskids' not in session
                or taskid not in session['taskids']):
            if format == 'json':
                return ajax_code(
                    404,
                    _('The task status requested '
                      'has expired or does not exist'))
            flash(_('The task status requested has expired or does not exist'))
            redirect(url(controller='messages', action='quarantine'))
        percent = "0.0"
        status = 'PROGRESS'
        results = []
        if result.ready():
            finished = True
            results = result.join_native()
        else:
            session['bulkprocess-count'] += 1
            if (session['bulkprocess-count'] >= 10
                    and result.completed_count() == 0):
                result.revoke()
                del session['bulkprocess-count']
                session.save()
                if format == 'json':
                    return ajax_code(
                        503,
                        _('An error occured in processing, try again later'))
                flash_alert(
                    _('An error occured in processing, try again later'))
                redirect(url(controller='messages', action='quarantine'))
            finished = False
            percent = "%.1f" % (
                (1.0 * int(result.completed_count()) / len(result)) * 100)

        if format == 'json':
            response.headers['Content-Type'] = 'application/json'
            data = dict(finished=finished,
                        results=results,
                        status=status,
                        completed=percent)
            return json.dumps(data)

        c.finished = finished
        c.results = results
        c.status = status
        c.completed = percent
        return self.render('/messages/taskstatus.html')
Esempio n. 41
0
 def new(self):
     "Add an organization"
     c.form = org_add_form(request.POST, session)
     if request.method == 'POST' and c.form.validate():
         try:
             org = create_org(c.form, c.user, request.host,
                              request.remote_addr)
             msg = _('The organization: %s has been created') % org.name
             flash(msg)
             log.info(msg)
             redirect(url(controller='organizations'))
         except IntegrityError:
             Session.rollback()
             flash_alert(_('The organization already exists'))
     return self.render('/organizations/add.html')
Esempio n. 42
0
 def new(self):
     "Add an organization"
     c.form = org_add_form(request.POST, session)
     if request.method == 'POST' and c.form.validate():
         try:
             org = create_org(c.form, c.user, request.host,
                         request.remote_addr)
             msg = _('The organization: %s has been created') % org.name
             flash(msg)
             log.info(msg)
             redirect(url(controller='organizations'))
         except IntegrityError:
             Session.rollback()
             flash_alert(_('The organization already exists'))
     return self.render('/organizations/add.html')
Esempio n. 43
0
 def add(self):
     """/accounts/new"""
     c.form = user_add_form(c.user, request.POST, session)
     if request.method == 'POST' and c.form.validate():
         try:
             user = create_user(c.form, c.user.username, request.host,
                                 request.remote_addr)
             flash(_('The account: %(user)s was created successfully') %
                     {'user': user.username})
             redirect(url('account-detail', userid=user.id))
         except IntegrityError:
             Session.rollback()
             flash_alert(
                 _('Either the username or email address already exist'))
     return self.render('/accounts/new.html')
Esempio n. 44
0
    def process(self, taskid, format=None):
        "process a taskset"
        result = TaskSetResult.restore(taskid, backend=dbbackend)
        if (result is None or
            'taskids' not in session or
            taskid not in session['taskids']):
            if format == 'json':
                return ajax_code(404,
                        _('The task status requested '
                        'has expired or does not exist'))
            flash(_('The task status requested has expired or does not exist'))
            redirect(url(controller='messages', action='quarantine'))
        percent = "0.0"
        status = 'PROGRESS'
        results = []
        #print '=' * 20, result.completed_count(), result.total, result.ready()
        if result.ready():
            finished = True
            results = result.join()
        else:
            session['bulkprocess-count'] += 1
            if (session['bulkprocess-count'] >= 10 and
                result.completed_count() == 0):
                result.revoke()
                del session['bulkprocess-count']
                session.save()
                if format == 'json':
                    return ajax_code(503,
                            _('An error occured in processing, try again later'))
                flash_alert(_('An error occured in processing, try again later'))
                redirect(url(controller='messages', action='quarantine'))
            finished = False
            percent = "%.1f" % ((1.0 * int(result.completed_count()) /
                                int(result.total)) * 100)

        if format == 'json':
            response.headers['Content-Type'] = 'application/json'
            data = dict(finished=finished,
                        results=results,
                        status=status,
                        completed=percent)
            return json.dumps(data)

        c.finished = finished
        c.results = results
        c.status = status
        c.completed = percent
        return render('/messages/taskstatus.html')
Esempio n. 45
0
 def add(self):
     """/accounts/new"""
     c.form = user_add_form(c.user, request.POST, session)
     if request.method == 'POST' and c.form.validate():
         try:
             user = create_user(c.form, c.user.username, request.host,
                                request.remote_addr)
             flash(
                 _('The account: %(user)s was created successfully') %
                 {'user': user.username})
             redirect(url('account-detail', userid=user.id))
         except IntegrityError:
             Session.rollback()
             flash_alert(
                 _('Either the username or email address already exist'))
     return self.render('/accounts/new.html')
Esempio n. 46
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. 47
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. 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 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. 51
0
    def mailq_detail(self, queueid):
        "View a queued message's details"
        query = Session.query(MailQueueItem)
        uquery = UserFilter(Session, c.user, query, model=MailQueueItem)
        query = uquery.filter()

        try:
            mailqitem = query.filter(MailQueueItem.id == queueid).one()
        except NoResultFound:
            #abort(404)
            flash_alert(_('The requested queued message was not found.'))
            redirect(url('mailq-status'))

        c.mailqitem = mailqitem
        c.form = MailQueueProcessForm(request.POST, csrf_context=session)
        session['queue_choices'] = [(queueid, queueid),]
        session.save()
        return render('/status/detail.html')
Esempio n. 52
0
    def mailq_detail(self, queueid):
        "View a queued message's details"
        query = Session.query(MailQueueItem)
        uquery = UserFilter(Session, c.user, query, model=MailQueueItem)
        query = uquery.filter()

        try:
            mailqitem = query.filter(MailQueueItem.id == queueid).one()
        except NoResultFound:
            #abort(404)
            flash_alert(_('The requested queued message was not found.'))
            redirect(url('mailq-status'))

        c.mailqitem = mailqitem
        c.form = MailQueueProcessForm(request.POST, csrf_context=session)
        session['queue_choices'] = [(queueid, queueid),]
        session.save()
        return render('/status/detail.html')
Esempio n. 53
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. 54
0
 def new(self):
     "Add an organization"
     c.form = OrgForm(request.POST, csrf_context=session)
     c.form.domains.query = Session.query(Domain)
     c.form.admins.query = Session.query(User).filter(User.account_type == 2)
     if request.POST and c.form.validate():
         try:
             org = Group()
             org.name = c.form.name.data
             org.domains = c.form.domains.data
             Session.add(org)
             Session.commit()
             info = ADDORG_MSG % dict(o=org.name)
             audit_log(c.user.username, 3, info, request.host, request.remote_addr, now())
             flash(_("The organization has been created"))
             redirect(url(controller="organizations"))
         except IntegrityError:
             flash_alert(_("The organization already exists"))
     return render("/organizations/add.html")
Esempio n. 55
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')
Esempio n. 56
0
 def delete(self, filterid, format=None):
     "Delete a temp filter"
     filters = session.get('filter_by', [])
     errors = {}
     success = True
     try:
         del filters[int(filterid)]
     except IndexError:
         msg = _("The filter does not exist")
         if format != 'json':
             flash_alert(msg)
         errors = dict(msg=msg)
         success = False
     if format == 'json':
         response.headers['Content-Type'] = JSON_HEADER
         if not errors:
             self.invalidate = True
         return json.dumps(self._get_data(format, success, errors))
     flash(_("The filter has been removed"))
     redirect(url(controller='reports'))
Esempio n. 57
0
 def delete(self, filterid, format=None):
     "Delete a temp filter"
     filters = session.get('filter_by', [])
     errors = {}
     success = True
     try:
         del filters[int(filterid)]
     except IndexError:
         msg = _("The filter does not exist")
         if format != 'json':
             flash_alert(msg)
         errors = dict(msg=msg)
         success = False
     if format == 'json':
         response.headers['Content-Type'] = JSON_HEADER
         if not errors:
             self.invalidate = True
         return json.dumps(self._get_data(format, success, errors))
     flash(_("The filter has been removed"))
     redirect(url(controller='reports'))
Esempio n. 58
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')
Esempio n. 59
0
 def new(self):
     "Add an organization"
     c.form = OrgForm(request.POST, csrf_context=session)
     c.form.domains.query = Session.query(Domain)
     c.form.admins.query = Session.query(User).filter(
         User.account_type == 2)
     if request.POST and c.form.validate():
         try:
             org = Group()
             org.name = c.form.name.data
             org.domains = c.form.domains.data
             Session.add(org)
             Session.commit()
             info = ADDORG_MSG % dict(o=org.name)
             audit_log(c.user.username, 3, info, request.host,
                       request.remote_addr, datetime.now())
             flash(_('The organization has been created'))
             redirect(url(controller='organizations'))
         except IntegrityError:
             flash_alert(_('The organization already exists'))
     return render('/organizations/add.html')
Esempio n. 60
0
    def export_status(self, taskid):
        "export 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='accounts', 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='accounts', action='index'))
            results = dict(
                f=True if not result.result['global_error'] else False,
                id=taskid,
                global_error=result.result['global_error'])
            audit_log(c.user.username, 5, unicode(auditmsgs.ACCOUNTEXPORT_MSG),
                      request.host, request.remote_addr,
                      arrow.utcnow().datetime)
        else:
            try:
                session['acexport-count'] += 1
            except KeyError:
                session['acexport-count'] = 1
            session.save()
            if (session['acexport-count'] >= 10
                    and result.state in ['PENDING', 'RETRY', 'FAILURE']):
                result.revoke()
                del session['acexport-count']
                session.save()
                msg = _('The export could not be processed, try again later')
                flash_alert(msg)
                log.info(msg)
                redirect(url(controller='accounts', action='index'))
            finished = False
            results = dict(f=None, global_error=None)

        c.finished = finished
        c.results = results
        c.success = result.successful()
        dwn = request.GET.get('d', None)
        if finished and (dwn and dwn == 'y'):
            response.content_type = 'text/csv'
            response.headers['Cache-Control'] = 'max-age=0'
            csvdata = result.result['f']
            disposition = 'attachment; filename=accounts-export-%s.csv' % \
                            taskid
            response.headers['Content-Disposition'] = str(disposition)
            response.headers['Content-Length'] = len(csvdata)
            return csvdata
        return self.render('/accounts/exportstatus.html')