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, datetime.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')
def update_index(sphinx_url, index, has_rt): "Update Sphinx index" sql_temp = """SELECT set_var('maxts', (SELECT maxts FROM indexer_counters WHERE tablename='messages_delta')); UPDATE indexer_counters SET maxts=get_var('maxts') WHERE tablename='%s';""" main_index = index delta_index = '%sdelta' % index indexer_cmd = ['/usr/bin/indexer', '--rotate', '--merge', main_index, delta_index] pipe = subprocess.Popen(indexer_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = pipe.communicate() pipe.wait() if pipe.returncode == 0: sql = text(sql_temp % main_index) Session.execute(sql, params={}) Session.commit() delta_index_cmd = ['/usr/bin/indexer', '--rotate', delta_index] pipe = subprocess.Popen(delta_index_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = pipe.communicate() pipe.wait() if has_rt: update_rt_index(index, sphinx_url) else: print >> sys.stderr, stderr
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")
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")
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")
def delete_auth(self, authid): "Delete auth server" server = self._get_authserver(authid) if not server: abort(404) c.form = AddAuthForm(request.POST, server, csrf_context=session) if request.POST and c.form.validate(): name = server.domains.name server_addr = server.address domainid = server.domains.id Session.delete(server) Session.commit() flash(_("The authentication settings have been deleted")) info = DELETEAUTHSVR_MSG % dict(d=name, ds=server_addr) audit_log(c.user.username, 4, info, request.host, request.remote_addr, datetime.now()) redirect(url("domain-detail", domainid=domainid)) else: flash( _("The authentication server: %(s)s will be deleted," " This action is not reversible") % dict(s=server.address) ) c.domainid = server.domains.id c.domainname = server.domains.name c.authid = authid return render("/domains/deleteauth.html")
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")
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")
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')
def add_address(row, user, requester): "Add address" session_dict = {} dummy = AddressForm(dict2mdict({}), csrf_context=session_dict) fields = getkeys(row, 'af') post_data = dict2mdict(fields) post_data.add('csrf_token', dummy.csrf_token.current_token) form = AddressForm(post_data, csrf_context=session_dict) if form.validate(): try: if requester.is_domain_admin: # check if they own the domain domainname = form.address.data.split('@')[1] Session.query(Domain).options( joinedload('organizations')).join( domain_owners, (oa, domain_owners.c.organization_id == \ oa.c.organization_id))\ .filter(oa.c.user_id == user.id)\ .filter(Domain.name == domainname).one() addr = Address(address=form.address.data) addr.enabled = form.enabled.data addr.user = user Session.add(addr) Session.commit() except (IntegrityError, NoResultFound): pass
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, datetime.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')
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.method == '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], exchange=FANOUT_XCHG) backend_sig_update(c.form.signature_type.data) info = auditmsgs.ADDDOMSIG_MSG % dict(d=domain.name) audit_log(c.user.username, 3, unicode(info), request.host, request.remote_addr, arrow.utcnow().datetime) flash(_('The signature has been created')) redirect(url('domain-settings-sigs', domainid=domainid)) except IntegrityError: Session.rollback() msg = _('This signature type already exists') flash(msg) log.info(msg) c.domain = domain return self.render('/settings/domain_addsig.html')
def update_audit_log(username, category, info, hostname, remoteip, timestamp=None): "Update the audit log" logger = update_audit_log.get_logger() try: entry = AuditLog(username, category, info, hostname, remoteip) if timestamp: entry.timestamp = timestamp Session.add(entry) Session.commit() logger.info("Audit Log update for: %s from: %s" % (username, remoteip)) except DatabaseError, err: logger.error("Audit Log FAILURE: %s %s %s %s %s %s Error: %s" % (username, category, info, hostname, remoteip, timestamp, err))
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')
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')
def edit_server(self, serverid): "Edit scan server" server = self._get_server(serverid) if not server: abort(404) c.form = ServerForm(request.POST, server, csrf_context=session) c.id = server.id if request.POST and c.form.validate(): if (server.hostname != c.form.hostname.data or server.enabled != c.form.enabled.data): try: server.hostname = c.form.hostname.data server.enabled = c.form.enabled.data Session.add(server) Session.commit() update_serial.delay() info = HOSTUPDATE_MSG % dict(n=server.hostname) audit_log(c.user.username, 2, info, request.host, request.remote_addr, datetime.now()) flash(_('The scanning server has been updated')) except IntegrityError: Session.rollback() flash(_('Update of server failed')) else: flash_info(_('No changes were made to the server')) redirect(url(controller='settings')) return render('/settings/editserver.html')
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')
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')
def command(self): "run command" self.init() try: for option in ['username', 'password', 'email']: if getattr(self.options, option) is None: if option == 'password' and \ 'BARUWA_ADMIN_PASSWD' in os.environ and \ os.environ['BARUWA_ADMIN_PASSWD']: VeryFascistCheck(os.environ['BARUWA_ADMIN_PASSWD']) self.options.password = \ os.environ['BARUWA_ADMIN_PASSWD'] continue print "\nOption: %s is required\n" % option print self.parser.print_help() sys.exit(2) user = User(username=self.options.username, email=self.options.email) user.active = True user.timezone = self.options.timezone user.account_type = 1 user.local = True user.set_password(self.options.password) Session.add(user) Session.commit() print "Admin account %s created" % self.options.username except ValueError, message: print >> sys.stderr, "%s." % str(message)[3:] sys.exit(2)
def edit_relay(self, settingid): "Edit a mail relay" relay = self._get_setting(settingid) if not relay: abort(404) c.form = RelayEditForm(request.POST, relay, csrf_context=session) c.relayname = relay.address or relay.username c.relayid = relay.id c.orgid = relay.org_id if request.POST and c.form.validate(): updated = False for field in c.form: if field.name == "csrf_token": continue if not field.name in ["password1", "password2"] and field.data != getattr(relay, field.name): setattr(relay, field.name, field.data) updated = True if field.name == "password1" and field.data != "": relay.set_password(field.data) updated = True if updated: try: Session.add(relay) Session.commit() info = UPDATERELAY_MSG % dict(r=c.relayname) audit_log(c.user.username, 2, info, request.host, request.remote_addr, now()) flash(_("The outbound settings have been updated")) except IntegrityError: Session.rollback() flash(_("The outbound settings could not be updated")) else: flash(_("No changes made, The outbound settings not updated")) redirect(url("org-detail", orgid=relay.org_id)) return render("/organizations/editrelay.html")
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, datetime.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')
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, datetime.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')
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, datetime.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')
def domain_dkim_enable(self, domainid): "Enable or disable DKIM signing" domain = self._get_domain(domainid) if not domain or not domain.dkimkeys: abort(404) c.form = DKIMForm(request.POST, domain.dkimkeys[0], csrf_context=session) if request.POST and c.form.validate(): dkimkeys = domain.dkimkeys[0] if dkimkeys.enabled != c.form.enabled.data: dkimkeys.enabled = c.form.enabled.data Session.add(dkimkeys) Session.commit() if c.form.enabled.data: state = _('enabled') save_dkim_key.apply_async(args=[domain.name, dkimkeys.pri_key], queue='msbackend') info = DKIMENABLED_MSG % dict(d=domain.name) else: info = DKIMDISABLED_MSG % dict(d=domain.name) delete_dkim_key.apply_async(args=[domain.name], queue='msbackend') state = _('disabled') audit_log(c.user.username, 2, info, request.host, request.remote_addr, datetime.now()) reload_exim.delay() flash(_('DKIM signing for: %s has been %s') % (domain.name, state)) else: flash(_('DKIM signing status: No changes made')) redirect(url('domain-dkim', domainid=domain.id)) c.domain = domain return render('/settings/domain_dkim_enable.html')
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))
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))
def update_index(sphinx_url, index, has_rt): "Update Sphinx index" sql_temp = """SELECT set_var('maxts', (SELECT maxts FROM indexer_counters WHERE tablename='messages_delta')); UPDATE indexer_counters SET maxts=get_var('maxts') WHERE tablename='%s';""" main_index = index delta_index = '%sdelta' % index indexer_cmd = [ '/usr/bin/indexer', '--rotate', '--merge', main_index, delta_index ] pipe = subprocess.Popen(indexer_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = pipe.communicate() pipe.wait() if pipe.returncode == 0: sql = text(sql_temp % main_index) Session.execute(sql, params={}) Session.commit() delta_index_cmd = ['/usr/bin/indexer', '--rotate', delta_index] pipe = subprocess.Popen(delta_index_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = pipe.communicate() pipe.wait() if has_rt: update_rt_index(index, sphinx_url) else: print >> sys.stderr, stderr
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')
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')
def deletedestination(self, destinationid): "Delete destination server" server = self._get_server(destinationid) if not server: abort(404) c.form = AddDeliveryServerForm(request.POST, server, csrf_context=session) if request.POST and c.form.validate(): name = server.domains.name server_addr = server.address domainid = server.domain_id Session.delete(server) Session.commit() flash(_('The destination server has been deleted')) info = DELETEDELSVR_MSG % dict(d=name, ds=server_addr) audit_log(c.user.username, 4, unicode(info), request.host, request.remote_addr, now()) redirect(url('domain-detail', domainid=domainid)) else: flash(_('The destination server: %(s)s will be deleted,' ' This action is not reversible') % dict(s=server.address)) c.id = destinationid c.domainid = server.domain_id return render('/domains/deletedestination.html')
def command(self): "run command" self.init() if self.options.username is None: print "\nProvide an username\n" print self.parser.print_help() sys.exit(2) try: user = Session\ .query(User)\ .filter(User.username == self.options.username)\ .filter(User.local == True)\ .one() pass1 = getpass.getpass(prompt="Please enter the password:"******"Please reenter the password:"******"Passwords cannot be blank" assert pass1 == pass2, "Passwords entered do not match" cracklib.VeryFascistCheck(pass1) user.set_password(pass1) Session.add(user) Session.commit() print "The account password has been updated" except NoResultFound: print >> sys.stderr, ("No local user found with username %s" % self.options.username) except AssertionError, message: print >> sys.stderr, str(message)
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')
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')
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')
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')
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')
def save(self, filterid, format=None): "Save a temp filter" filters = session.get('filter_by', []) try: filt = filters[int(filterid)] filteritems = dict(FILTER_ITEMS) filterby = dict(FILTER_BY) saved = SavedFilter(name="%s %s %s" % (filteritems[filt["field"]], filterby[filt["filter"]], filt["value"]), field=filt["field"], option=filt["filter"], user=c.user) saved.value = filt["value"] Session.add(saved) Session.commit() success = True error_msg = '' self.invalidate = True except IndexError: success = False error_msg = _("The filter does not exist") except IntegrityError: success = False error_msg = _("The filter already exists") Session.rollback() if format == 'json': response.headers['Content-Type'] = JSON_HEADER errors = dict(msg=error_msg) return json.dumps(self._get_data(format, success, errors)) if success: flash(_("The filter has been saved")) else: flash(error_msg) redirect(url('toplevel', controller='reports'))
def update_queue_stats(hostname): "Update queue stats" inqdir = get_config_option('IncomingQueueDir') outqdir = get_config_option('OutgoingQueueDir') allids, inqueue = process_queue(inqdir, 1) tmpids, outqueue = process_queue(outqdir, 2) allids.extend(tmpids) dbids = [item.messageid for item in Session.query(MailQueueItem.messageid)\ .filter(MailQueueItem.hostname == hostname)\ .all()] remids = [item for item in dbids if not item in allids] preids = [item for item in dbids if not item in remids] if remids: print >> sys.stderr, ("== Deleting %(items)d queue " "items from DB ==" % dict(items=len(remids))) Session.query(MailQueueItem)\ .filter(MailQueueItem.messageid.in_(remids))\ .delete(synchronize_session='fetch') Session.commit() populate_db(inqueue, inqdir, 1, preids) populate_db(outqueue, outqdir, 2, preids)
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, datetime.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')
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')
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, datetime.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')
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')
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')
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')
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')
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')
def update_queue_stats(hostname): "Update queue stats" inqdir = get_config_option('IncomingQueueDir') outqdir = get_config_option('OutgoingQueueDir') allids, inqueue = process_queue(inqdir, 1) tmpids, outqueue = process_queue(outqdir, 2) allids.extend(tmpids) dbids = [item.messageid for item in Session.query(MailQueueItem.messageid) .filter(MailQueueItem.hostname == hostname.decode('utf-8')).all()] remids = [item for item in dbids if item not in allids] preids = [item for item in dbids if item not in remids] if remids: print >> sys.stderr, ("== Deleting %(items)d queue " "items from DB ==" % dict(items=len(remids))) Session.query(MailQueueItem)\ .filter(MailQueueItem.messageid.in_(remids))\ .delete(synchronize_session='fetch') Session.commit() populate_db(inqueue, inqdir, 1, preids) populate_db(outqueue, outqdir, 2, preids)
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')
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')
def swap_order(self, next_rule): """Swap ordering""" prev_order = self.ordering self.ordering = next_rule.ordering next_rule.ordering = prev_order Session.add(self) Session.commit() Session.add(next_rule) Session.commit()
def savemodel(model, form, domainid=None): "save form data" for field in form: if field.name != 'csrf_token': setattr(model, field.name, field.data) if domainid: model.domain_id = domainid try: Session.add(model) Session.commit() except IntegrityError: Session.rollback()
def passwdreset(self): """Render password reset page""" c.came_from = '/' c.login_counter = 0 c.form = ResetPwForm(request.POST, csrf_context=session) if request.method == 'POST' and c.form.validate(): key_seed = '%s%s' % (c.form.email.data, arrow.utcnow().ctime()) token = hashlib.sha1(key_seed).hexdigest() user = Session.query(User)\ .filter(User.email == c.form.email.data)\ .one() if not user.local: flash( _('The account %s is an external account, use your' ' External systems to change the password. ' 'Contact your system adminstrator if you do not ' 'know which external systems you authenticate to') % user.email) redirect(url('/accounts/login')) rtoken = Session\ .query(ResetToken.used)\ .filter(ResetToken.used == false())\ .filter(ResetToken.user_id == user.id)\ .all() if not rtoken: rtoken = ResetToken(token, user.id) Session.add(rtoken) Session.commit() host = URL_PREFIX_RE.sub('', request.host_url) c.username = user.username c.firstname = user.firstname or user.username c.reset_url = url('accounts-pw-token-reset', token=token, host=host) text = self.render('/email/pwreset.txt') mailer = Mailer(get_conf_options(config)) mailer.start() sdrnme = config.get('baruwa.custom.name', 'Baruwa') email = Msg(author=[(sdrnme, config.get('baruwa.reports.sender'))], to=[('', c.form.email.data)], subject=_("[%s] Password reset request") % sdrnme) email.plain = text mailer.send(email) mailer.stop() flash( _('An email has been sent to the address provided, ' 'please follow the instructions in that email to ' 'reset your password.')) redirect(url('/accounts/login')) return self.render('/accounts/login.html')
def index(self, page=1, orgid=None, format=None): "Browse domains" num_items = session.get('domains_num_items', 10) c.form = BulkDelDomains(request.POST, csrf_context=session) if request.method == 'POST': if c.form.domainid.data and c.form.whatdo.data == 'disable': Session.query(Domain).filter( Domain.id.in_(c.form.domainid.data)).update( {'status': False}, synchronize_session='fetch') Session.commit() if c.form.domainid.data and c.form.whatdo.data == 'enable': Session.query(Domain).filter( Domain.id.in_(c.form.domainid.data)).update( {'status': True}, synchronize_session='fetch') Session.commit() if c.form.domainid.data and c.form.whatdo.data == 'delete': session['bulk_domain_delete'] = c.form.domainid.data session.save() # redirect for confirmation redirect(url('domains-confirm-delete')) domains = Session.query(Domain).options( joinedload(Domain.organizations)) domcount = Session.query(Domain.id) if orgid and c.user.is_superadmin: domains = domains.join(domain_owners).filter( domain_owners.c.organization_id == orgid) domcount = domcount.join(domain_owners).filter( domain_owners.c.organization_id == orgid) 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) pages = paginate.Page(domains, page=int(page), items_per_page=num_items, item_count=domcount.count()) if format == 'json': response.headers['Content-Type'] = 'application/json' data = convert_dom_to_json(pages, orgid) return data c.orgid = orgid c.page = pages return self.render('/domains/index.html')
def update_ms_serial(logger): """Update MS configuration serial""" try: msconf = Session.query(ConfigSettings)\ .filter(ConfigSettings.internal == u'confserialnumber').one() msconf.value = int(msconf.value) + 1 except NoResultFound: msconf = ConfigSettings('confserialnumber', 'ConfSerialNumber', 0) msconf.value = 1 msconf.server_id = 1 Session.add(msconf) Session.commit() # Session.close() logger.info('Scanner serial number updated: %s' % str(msconf.value))
def delete_stored(self, filterid, format=None): "Delete a saved dilter" savedfilter = self._get_filter(filterid) if not savedfilter: abort(404) Session.delete(savedfilter) Session.commit() if format == 'json': response.headers['Content-Type'] = JSON_HEADER self.invalidate = True return json.dumps(self._get_data(format, True, {})) flash(_("The filter has been deleted")) redirect(url('toplevel', controller='reports'))
def update_autorelease(msg_uuid): "Update the autorelease link record" logger = update_autorelease.get_logger() try: record = Session.query(Release)\ .filter(Release.uuid == msg_uuid)\ .one() record.released = True Session.add(record) Session.commit() logger.info("Auto Release record: %s updated" % msg_uuid) except NoResultFound: logger.info("Release Record: %s not found" % msg_uuid) finally: Session.close()