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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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_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_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 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(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 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 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 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_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 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 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 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')
def setup_app(command, conf, variables): """Place any commands to setup baruwa here""" # Don't reload the app if it was loaded under the testing environment if not pylons.test.pylonsapp: load_environment(conf.global_conf, conf.local_conf) # Create the tables if they don't already exist print '-' * 100 log.info("Creating tables") Base.metadata.create_all(bind=Session.bind) basepath = os.path.dirname(os.path.dirname(__file__)) # Create the custom functions print '-' * 100 log.info("Creating custom functions") sqlfile = os.path.join(basepath, 'baruwa', 'config', 'sql', 'functions.sql') if os.path.exists(sqlfile): with open(sqlfile, 'r') as handle: sql = handle.read() try: conn = Session.connection() conn.execute(text(sql)) Session.commit() except ProgrammingError: Session.rollback() defaultserver = Session.query(Server)\ .filter(Server.hostname == 'default')\ .all() # Create the Mailscanner SQL config views print '-' * 100 log.info("Populating initial sql") sqlfile = os.path.join(basepath, 'baruwa', 'config', 'sql', 'integration.sql') if os.path.exists(sqlfile): with open(sqlfile, 'r') as handle: sql = handle.read() for sqlcmd in sql.split(';'): if sqlcmd: try: sqlcmd = "%s;" % sqlcmd Session.execute(text(sqlcmd)) Session.commit() except ProgrammingError: Session.rollback() if not defaultserver: log.info("Creating the default settings node") dfls = Server('default', True) Session.add(dfls) confserial = ConfigSettings('confserialnumber', 'ConfSerialNumber', 0) confserial.value = 1 confserial.server_id = 1 Session.add(confserial) Session.commit() log.info("Default settings node created !")
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 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()
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 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 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 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()
def update_autorelease(msg_uuid, ignore_result=True): "Update the autorelease link record" logger = update_autorelease.get_logger() try: record = Session.query(Release)\ .filter(Release.uuid==msg_uuid)\ .one() logger.info("RECORD1: %s" % str(record.released)) record.released = True logger.info("RECORD2: %s" % str(record.released)) Session.add(record) Session.commit() logger.info("RECORD3: %s" % str(record.released)) logger.info("Auto Release record: %s updated" % msg_uuid) except NoResultFound: logger.info("Release Record: %s not found" % msg_uuid)
def edit(self, domainid): "Edit a domain" domain = self._get_domain(domainid) if not domain: abort(404) c.form = AddDomainForm(request.POST, domain, csrf_context=session) if c.user.is_superadmin: c.form.organizations.query_factory = self._get_organizations else: del c.form.organizations c.id = domainid if request.POST and c.form.validate(): updated = False kw = {'domainid': domain.id} for field in c.form: intfields = [ 'spam_actions', 'highspam_actions', 'delivery_mode', 'report_every' ] if (field.name in intfields and int(field.data) == getattr(domain, field.name)): continue if (field.name != 'csrf_token' and field.data != getattr(domain, field.name)): setattr(domain, field.name, field.data) updated = True if updated: try: Session.add(domain) Session.commit() update_serial.delay() info = UPDATEDOMAIN_MSG % dict(d=domain.name) audit_log(c.user.username, 2, info, request.host, request.remote_addr, now()) flash( _('The domain: %(dom)s has been updated') % dict(dom=domain.name)) kw['uc'] = 1 except IntegrityError: Session.rollback() flash( _('The domain %(dom)s could not be updated') % dict(dom=domain.name)) else: flash_info(_('No changes were made to the domain')) redirect(url('domain-detail', **kw)) return render('/domains/edit.html')
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')
def updatedb(line): """Update or save the rule name and description to the database""" match = RULE_DESCRIPTION_RE.match(line) if match: matchdict = match.groupdict() oldrule = _get_rule(matchdict['ruleid']) if oldrule is None: if not matchdict['ruleid'].startswith('__'): rule = SARule(**matchdict) Session.add(rule) Session.commit() else: if oldrule.description != matchdict['description']: oldrule.description = matchdict['description'] Session.add(oldrule) Session.commit()
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')
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')
def update_ms_serial(logger): """Update MS configuration serial""" try: msconf = Session.query(ConfigSettings)\ .filter(ConfigSettings.internal == '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 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')
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 new_server(self): "Add scan server" c.form = ServerForm(request.POST, csrf_context=session) if request.POST and c.form.validate(): try: server = Server(hostname=c.form.hostname.data, enabled=c.form.enabled.data) Session.add(server) Session.commit() info = HOSTADD_MSG % dict(n=server.hostname) audit_log(c.user.username, 3, info, request.host, request.remote_addr, now()) flash(_('The scanning server has been added')) redirect(url(controller='settings')) except IntegrityError: Session.rollback() flash_info(_('The server already exists')) return render('/settings/addserver.html')
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')