def passwdreset(self): """Render password reset page""" c.came_from = '/' c.login_counter = 0 c.form = ResetPwForm(request.POST, csrf_context=session) if request.POST and c.form.validate(): key_seed = '%s%s' % (c.form.email.data, datetime.now().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 = render('/email/pwreset.txt') mailer = Mailer(get_conf_options(config)) mailer.start() email = Msg(author=[(_('Baruwa Hosted'), config.get('baruwa.reports.sender'))], to=[('', c.form.email.data)], subject=_("[Baruwa] Password reset request")) 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 render('/accounts/login.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 detail(self, orgid): "Organization details" org = self._get_org(orgid) if not org: abort(404) c.org = org return render('/organizations/detail.html')
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 login(self): "login" if request.remote_addr in session: if session[request.remote_addr] > now(): abort(409, _('You have been banned after' ' several failed logins')) else: del session[request.remote_addr] session.save() identity = request.environ.get('repoze.who.identity') came_from = unquote(str(request.GET.get('came_from', ''))) if not came_from or ' ' in came_from: came_from = url('home') if '://' in came_from: from_url = urlparse(came_from) came_from = from_url[2] if identity: redirect(url(came_from)) else: c.came_from = came_from c.login_counter = request.environ['repoze.who.logins'] if c.login_counter >= 3: ban_until = now() + timedelta(minutes=5) if request.remote_addr not in session: session[request.remote_addr] = ban_until session.save() else: if now() > session[request.remote_addr]: del session[request.remote_addr] session.save() return render('/accounts/login.html')
def detail(self, userid): """GET /accounts/userid/ Show a specific item""" user = self._get_user(userid) if not user: abort(404) c.account = user return render('/accounts/account.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 domain_dkim(self, domainid): "Domain DKIM settings" domain = self._get_domain(domainid) if not domain: abort(404) c.domain = domain return render('/settings/domain_dkim.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 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 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 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 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 index(self, format=None): "return recent messages" num_items = session.get('msgs_num_items', 50) query = self._get_messagez().order_by(desc('timestamp')) if ('X-Last-Timestamp' in request.headers and request.headers['X-Last-Timestamp']): tstmp = request.headers.get('X-Last-Timestamp') query = query.filter(Message.timestamp > tstmp) uquery = UserFilter(Session, c.user, query) query = uquery.filter() items = query[:num_items] if format == 'json': response.headers['Content-Type'] = 'application/json' msgs = [item.json for item in items] tmp = dict( totals=c.baruwa_totals, inbound=c.baruwa_inbound, outbound=c.baruwa_outbound, items=msgs, num_items=num_items ) if c.user.is_admin: tmp['status'] = c.baruwa_status return json.dumps(tmp) c.messages = items c.num_items = num_items return render('/messages/index.html')
def show_filters(self): "Show filters" filters = session.get('filter_by', []) c.active_filters = filters c.FILTER_BY = FILTER_BY c.FILTER_ITEMS = FILTER_ITEMS return render('/reports/show_filters.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 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 domain_sigs(self, domainid): "Domain signatures landing" domain = self._get_domain(domainid) if not domain: abort(404) c.domain = domain return render('/settings/domain_sigs.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 domain_rules(self, domainid): "Domain rulesets" domain = self._get_domain(domainid) if not domain: abort(404) c.domain = domain return render('/settings/domain_rules.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 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 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_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_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 index(self, format=None): "Index page" c.form = FilterForm(request.POST, csrf_context=session) errors = '' success = True if request.POST and c.form.validate(): fitem = dict(field=c.form.filtered_field.data, filter=c.form.filtered_by.data, value=c.form.filtered_value.data) self._save_filter(fitem) elif request.POST and not c.form.validate(): success = False key = c.form.errors.keys() errors = dict(field=key[0], msg=', '.join(c.form.errors[key[0]])) if success: self.invalidate = True if format == 'json': response.headers['Content-Type'] = JSON_HEADER jsondata = self._get_data(format, success, errors) return json.dumps(jsondata) data, count, filters, saved_filters = self._get_data() c.data = data c.count = count c.active_filters = filters c.saved_filters = saved_filters c.FILTER_BY = FILTER_BY c.FILTER_ITEMS = FILTER_ITEMS return render('/reports/index.html')
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 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 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 archive(self, page=1, direction='dsc', order_by='timestamp', format=None): "messages archive" filters = session.get('filter_by', None) num_items = session.get('msgs_num_items', 50) if direction == 'dsc': sort = desc(order_by) else: sort = order_by messages = self._get_archived().order_by(sort) msgcount = self._get_msg_count(True) query = UserFilter(Session, c.user, messages, True) countquery = UserFilter(Session, c.user, msgcount, True) messages = query.filter() msgcount = countquery.filter() if filters: dynq = DynaQuery(Archive, messages, filters) dynmsgq = DynaQuery(Archive, msgcount, filters) messages = dynq.generate() msgcount = dynmsgq.generate() c.order_by = order_by c.direction = direction msgcount = msgcount.count() pages = paginate.Page(messages, page=int(page), items_per_page=num_items, item_count=msgcount) if format == 'json': response.headers['Content-Type'] = 'application/json' data = convert_to_json(pages, direction=direction, order_by=order_by, section=None) return data c.page = pages return render('/messages/archive.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 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 detail(self, domainid): "Domain details" domain = self._get_domain(domainid) if not domain: abort(404) c.domain = domain return render('/domains/detail.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 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 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 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 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 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 detail(self, domainid): "Domain details" domain = self._get_domain(domainid) if not domain: abort(404) c.domain = domain return render("/domains/detail.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 login(self): "login" if request.remote_addr in session: if session[request.remote_addr] > now(): abort(409, _('You have been banned after' ' several failed logins')) else: del session[request.remote_addr] session.save() identity = request.environ.get('repoze.who.identity') came_from = unquote(str(request.GET.get('came_from', ''))) if not came_from or ' ' in came_from: came_from = url('home') if '://' in came_from: from_url = urlparse(came_from) came_from = from_url[2] if identity: redirect(url(came_from)) else: c.came_from = came_from c.login_counter = request.environ['repoze.who.logins'] if c.login_counter >= 3: ban_until = now() + timedelta(minutes=5) if request.remote_addr not in session: session[request.remote_addr] = ban_until session.save() else: if now() > session[request.remote_addr]: del session[request.remote_addr] session.save() c.form = ResetPwForm(request.POST, csrf_context=session) return render('/accounts/login.html')
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 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 audit(self, page=1, format=None): "Audit log" total_found = 0 search_time = 0 num_items = session.get('auditlog_num_items', 50) q = request.GET.get('q', None) kwds = {} if q: conn = SphinxClient() conn.SetMatchMode(SPH_MATCH_EXTENDED2) if page == 1: conn.SetLimits(0, num_items, 500) else: page = int(page) offset = (page - 1) * num_items conn.SetLimits(offset, num_items, 500) q = clean_sphinx_q(q) results = conn.Query(q, 'auditlog, auditlog_rt') q = restore_sphinx_q(q) if results and results['matches']: ids = [hit['id'] for hit in results['matches']] query = Session.query(AuditLog)\ .filter(AuditLog.id.in_(ids))\ .order_by(desc('timestamp'))\ .all() total_found = results['total_found'] search_time = results['time'] logcount = total_found kwds['presliced_list'] = True else: query = [] lcount = 0 logcount = 0 else: query = Session.query(AuditLog)\ .order_by(desc('timestamp')) lcount = Session.query(AuditLog)\ .order_by(desc('timestamp')) if not 'logcount' in locals(): logcount = lcount.count() items = paginate.Page(query, page=int(page), items_per_page=num_items, item_count=logcount, **kwds) if format == 'json': response.headers['Content-Type'] = 'application/json' jdict = convert_settings_to_json(items) if q: encoded = json.loads(jdict) encoded['q'] = q jdict = json.dumps(encoded) return jdict c.page = items c.q = q c.total_found = total_found c.search_time = search_time return render('/status/audit.html')
def relayed_via(self, id, archive=None): "return relayed via hosts used by ajax calls" message = self._get_msg(id, archive) if not message: abort(404) c.msg = message return render('/messages/includes/relayedvia.html')
def rulesets(self, domainid): "Scanner rulesets" domain = self._get_domain(domainid) if not domain: abort(404) c.domainid = domain.id c.domainname = domain.name return render('/domains/rulesets.html')