Checkpoint commit for ListFindPeople; need Mono test

This commit is contained in:
Rick Falkvinge
2014-10-02 15:10:39 +02:00
parent 4eabc04e1e
commit 57c477d9ec
13 changed files with 266 additions and 57 deletions
+19
View File
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Security;
using System.Text;
using MySql.Data;
@@ -227,5 +228,23 @@ namespace Swarmops.Database
{
return d.ToString("yyyyMMddHHmmss");
}
private string SqlSanitize(string input)
{
string[] forbiddenArray = {"\\", "--", ";", "/*", "*/", "select ", "drop ", "update ", "delete ", "insert ", "="};
string output = input.Replace("'", "''"); // the typical case
string inputLower = input.ToLowerInvariant();
foreach (string forbidden in forbiddenArray)
{
if (inputLower.Contains(forbidden))
{
throw new SecurityException("Attempt at SQL injection: parameter passed to SELECT was '" + input + "'");
}
}
return output;
}
}
}
+66 -3
View File
@@ -64,7 +64,7 @@ namespace Swarmops.Database
DbCommand command =
GetDbCommand(
"SELECT " + personFieldSequence + " WHERE Name like '" + namePattern.Replace("'", "''") + "'",
"SELECT " + personFieldSequence + " WHERE Name like '" + GetSqlPatternFromNamePattern(namePattern).Replace("'", "''") + "'",
connection);
command.CommandTimeout = 120;
@@ -80,6 +80,31 @@ namespace Swarmops.Database
return result.ToArray();
}
private string GetSqlPatternFromNamePattern(string namePattern)
{
// Remove any injection codes
namePattern = SqlSanitize(namePattern).Replace("%", String.Empty).Trim();
while (namePattern.Contains(" "))
{
namePattern = namePattern.Replace(" ", " ");
}
if (namePattern.Length > 0)
{
namePattern = namePattern.Replace(" ", "% ") + "%";
if (!namePattern.Contains(" "))
{
namePattern = "%" + namePattern;
}
return namePattern;
}
return string.Empty; // If no valid search string was supplied
}
public BasicPerson[] GetPeopleFromBirthdate (DateTime fromdate, DateTime todate)
{
// Is this really valid for MySQL? Yes .net connector makes @parameter substitutions
@@ -405,7 +430,7 @@ namespace Swarmops.Database
}
public BasicPerson[] GetPeopleInGeographies (int[] geographyIds)
public BasicPerson[] GetPeopleInGeographies(int[] geographyIds)
{
if (geographyIds.Length == 0)
{
@@ -435,7 +460,45 @@ namespace Swarmops.Database
public void SetPersonName (int personId, string name)
public BasicPerson[] GetPeopleInGeographiesWithPattern (int[] geographyIds, string pattern)
{
if (geographyIds.Length == 0)
{
return new BasicPerson[0];
}
pattern = pattern.Trim();
if (pattern.Length == 0)
{
return GetPeopleInGeographies(geographyIds); // no pattern => fall back to just geography
}
string sqlPattern = GetSqlPatternFromNamePattern(pattern);
List<BasicPerson> result = new List<BasicPerson>();
using (DbConnection connection = GetMySqlDbConnection())
{
connection.Open();
DbCommand command =
GetDbCommand("SELECT " + personFieldSequence + " WHERE GeographyId IN (" + JoinIds(geographyIds) + ") AND (Name like '" + sqlPattern + "' OR Email like '" + sqlPattern + "')",
connection);
using (DbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
result.Add(ReadPersonFromDataReader(reader));
}
return result.ToArray();
}
}
}
public void SetPersonName(int personId, string name)
{
this.SetPersonBasicStringValue(personId, "Name", name);
}
+41 -23
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using Swarmops.Basic.Enums;
using Swarmops.Basic.Interfaces;
using Swarmops.Basic.Types;
using Swarmops.Database;
using Swarmops.Logic.Security;
@@ -68,27 +69,12 @@ namespace Swarmops.Logic.Swarm
public static People FromNamePattern (string namePattern)
{
// Remove any injection codes
namePattern = namePattern.Replace("%", String.Empty).Trim();
while (namePattern.Contains(" "))
if (namePattern.Trim().Length < 3)
{
namePattern = namePattern.Replace(" ", " ");
return new People();
}
if (namePattern.Length > 0)
{
namePattern = namePattern.Replace(" ", "% ") + "%";
if (!namePattern.Contains(" "))
{
namePattern = "%" + namePattern;
}
return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromNamePattern(namePattern));
}
return null; // If no valid search string was supplied
return People.FromArray(SwarmDb.GetDatabaseForReading().GetPeopleFromNamePattern(namePattern));
}
public static People FromBirthDatePattern (DateTime fromdate, DateTime todate)
@@ -269,9 +255,34 @@ namespace Swarmops.Logic.Swarm
return retlist;
}
public static People FromOrganizationAndGeography (int organizationId, int geographyId)
public static People FromOrganizationAndGeographyWithPattern(Organization organization, Geography geography,
string pattern)
{
Geographies geoTree = Geography.FromIdentity(geographyId).GetTree();
Geographies geoTree = geography.GetTree();
pattern = pattern.Trim();
if (pattern.Length == 0)
{
return FromOrganizationAndGeography(organization, geography);
}
else if (pattern.Length < 3)
{
// too short pattern! Return empty set.
return new People();
}
// First, get list of people in the geography, then filter on memberships
BasicPerson[] candidates = SwarmDb.GetDatabaseForReading().GetPeopleInGeographiesWithPattern(geoTree.Identities, pattern);
return FilterByMembership(candidates, organization);
}
public static People FromOrganizationAndGeography(Organization organization, Geography geography)
{
Geographies geoTree = geography.GetTree();
// First, get list of people in the geography, then filter on memberships
@@ -279,9 +290,16 @@ namespace Swarmops.Logic.Swarm
// Filter on memberships
return FilterByMembership(people, organization);
}
private static People FilterByMembership(BasicPerson[] candidates, Organization organization)
{
// Get the organization tree
Organizations orgTree = Organization.FromIdentity(organizationId).GetTree();
Organizations orgTree = organization.GetTree();
// Build a lookup table of this organization tree. For each person in 'people'
// that has at least one membership in an organization in the lookup table,
@@ -297,11 +315,11 @@ namespace Swarmops.Logic.Swarm
// Get the list of all memberships
Dictionary<int, List<BasicMembership>> memberships =
SwarmDb.GetDatabaseForReading().GetMembershipsForPeople(LogicServices.ObjectsToIdentifiers(people));
SwarmDb.GetDatabaseForReading().GetMembershipsForPeople(LogicServices.ObjectsToIdentifiers(candidates));
var result = new People();
foreach (BasicPerson basicPerson in people)
foreach (BasicPerson basicPerson in candidates)
{
bool memberOfOrganization = false;
+5 -1
View File
@@ -392,7 +392,7 @@
<value>Revenue</value>
</data>
<data name="Global_SelectOne" xml:space="preserve">
<value>- - Select one - -</value>
<value>-- Select one --</value>
<comment>Shown in dropdowns when selection required</comment>
</data>
<data name="Global_Missing" xml:space="preserve">
@@ -471,4 +471,8 @@
<value>Non-profit</value>
<comment>Non-profit (activist, political parties)</comment>
</data>
<data name="Global_Geography" xml:space="preserve">
<value>Geography</value>
<comment>As in "location" - on any scale and anywhere from "World" to a named city</comment>
</data>
</root>
+13 -3
View File
@@ -117,10 +117,20 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="FindListPeople_Info" xml:space="preserve">
<data name="ListFindPeople_Info" xml:space="preserve">
<value>Find people in the organization (write more here)</value>
</data>
<data name="FindListPeople_Title" xml:space="preserve">
<value>Find, List People</value>
<data name="ListFindPeople_MatchingPeopleInX" xml:space="preserve">
<value>Matching People in {0}</value>
<comment>The {0} parameter is the organization name.</comment>
</data>
<data name="ListFindPeople_NamePattern" xml:space="preserve">
<value>Name Pattern</value>
</data>
<data name="ListFindPeople_Title" xml:space="preserve">
<value>List and Find People</value>
</data>
<data name="ListFindPeople_TooManyHits" xml:space="preserve">
<value>Over 1,000 matches. Please refine search.</value>
</data>
</root>
@@ -66,7 +66,7 @@ namespace Swarmops.Frontend.Automation
int renderRootNodeId = rootGeography.ParentGeographyId; // This works as rootGeography will be the only present child in the collection; other children won't be there
accountsJson = RecurseTreeMap(treeMap, renderRootNodeId);
accountsJson = RecurseTreeMap(treeMap, renderRootNodeId, true);
Cache.Insert(cacheKey, accountsJson, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero);
// cache lasts for five minutes, no sliding expiration
@@ -75,7 +75,7 @@ namespace Swarmops.Frontend.Automation
Response.End();
}
private string RecurseTreeMap(Dictionary<int, List<Geography>> treeMap, int node)
private string RecurseTreeMap(Dictionary<int, List<Geography>> treeMap, int node, bool expanded)
{
List<string> elements = new List<string>();
@@ -86,7 +86,7 @@ namespace Swarmops.Frontend.Automation
if (treeMap.ContainsKey(geography.Identity))
{
element += ",\"state\":\"closed\",\"children\":" + RecurseTreeMap(treeMap, geography.Identity);
element += ",\"state\":\"" + (expanded? "open":"closed") + "\",\"children\":" + RecurseTreeMap(treeMap, geography.Identity, false);
}
elements.Add("{" + element + "}");
+2 -2
View File
@@ -11,8 +11,8 @@
if (!String.IsNullOrEmpty(this.OnClientLoaded))
{
Response.Write(this.OnClientLoaded + "(); ");
}
Response.Write("}");
}%>
}<%
if (!String.IsNullOrEmpty(this.OnClientSelect))
{
Response.Write(", onSelect: function(account) { " + this.OnClientSelect + "(account.id); }");
+1 -1
View File
@@ -17,7 +17,7 @@
<UserLevel>2</UserLevel>
<Permissions />
<ImageUrl />
<NavigateUrl>/Pages/v5/People/ListFindPeople.aspx</NavigateUrl>
<NavigateUrl>/Pages/v5/Swarm/ListFindPeople.aspx</NavigateUrl>
<Type>Link</Type>
<Children />
</MainMenuItem>
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Json-ListFindPeople.aspx.cs" Inherits="Swarmops.Frontend.Pages.Swarm.Json_ListFindPeople" %>
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Swarmops.Logic.Financial;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Swarm;
namespace Swarmops.Frontend.Pages.Swarm
{
public partial class Json_ListFindPeople : DataV5Base
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json";
string pattern = HttpUtility.UrlDecode(Request.QueryString["Pattern"]);
string geographyString = Request.QueryString["GeographyId"];
int geographyId = int.Parse(geographyString);
Geography geography = Geography.FromIdentity(geographyId);
People matches = People.FromOrganizationAndGeographyWithPattern(this.CurrentOrganization, geography, pattern);
// matches = Authorization.FilterPeopleToMatchAuthority(matches, CurrentUser.GetAuthority());
if (matches == null)
{
matches = new People();
}
if (matches.Count > 1000)
{
matches.RemoveRange(1000, matches.Count - 1000);
}
List<string> jsonPeople = new List<string>();
foreach (Person person in matches)
{
string onePerson = '{' + String.Format("\"id\":\"{0}\",\"name\":\"{1}\",\"avatar16Url\":\"{2}\",\"geographyName\":\"{3}\"",
person.Identity,
JsonSanitize(person.Canonical),
person.GetSecureAvatarLink(16),
JsonSanitize(person.Geography.Name)) + '}';
jsonPeople.Add(onePerson);
}
string result = '[' + String.Join(",", jsonPeople.ToArray()) + ']';
Response.Output.WriteLine(result);
Response.End();
}
}
}
@@ -1,4 +1,4 @@
<%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="ListFindPeople.aspx.cs" Inherits="Swarmops.Frontend.Pages.People.ListFindPeople" %>
<%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="ListFindPeople.aspx.cs" Inherits="Swarmops.Frontend.Pages.Swarm.ListFindPeople" %>
<%@ Register src="~/Controls/v5/UI/ExternalScripts.ascx" tagname="ExternalScripts" tagprefix="Swarmops5" %>
<%@ Register src="~/Controls/v5/Base/ComboGeographies.ascx" tagname="ComboGeographies" tagprefix="Swarmops5" %>
@@ -25,7 +25,28 @@
]);
$(document).ready(function () {
$('#TablePayableCosts').datagrid(
$('#<%=this.TextNamePattern.ClientID%>').on('fieldchange', function () {
var newNamePattern = $('#<%=this.TextNamePattern.ClientID%>').val();
if (newNamePattern != lastNamePattern && newNamePattern.length >= 3) {
lastNamePattern = newNamePattern;
$('#TableSearchResults').datagrid({ url: 'Json-ListFindPeople.aspx?Pattern=' + escape(newNamePattern) + '&GeographyId=' + selectedGeographyId });
}
});
$('#<%=this.TextNamePattern.ClientID%>').on('input', function () {
clearTimeout(this.delayer);
var context = this;
this.delayer = setTimeout(function () {
$(context).trigger('fieldchange');
}, 1000);
});
var count = 0;
$('#TableSearchResults').datagrid(
{
onLoadSuccess: function () {
$(".LocalIconApproval").attr("src", "/Images/Icons/iconshock-balloon-yes-16px.png");
@@ -117,6 +138,16 @@
);
});
function onGeographyChange(newGeographyId) {
if (newGeographyId != selectedGeographyId) {
selectedGeographyId = newGeographyId;
$('#TableSearchResults').datagrid({ url: 'Json-ListFindPeople.aspx?Pattern=' + escape(lastNamePattern) + '&GeographyId=' + selectedGeographyId });
}
}
var lastNamePattern = '';
var selectedGeographyId = 1;
</script>
<style type="text/css">
@@ -126,23 +157,22 @@
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PlaceHolderMain" Runat="Server">
<h2><asp:Label runat="server" ID="LabelPayOutMoneyHeader" Text="Find / List People XYZ" /></h2>
<div class="entryFields">
<Swarmops5:ComboGeographies ID="ComboGeographies" runat="server" />&thinsp;<br/>
<asp:TextBox runat="server" ID="NamePattern" />
<div class="entryFields" style="padding-top:4px">
<Swarmops5:ComboGeographies ID="ComboGeographies" runat="server" OnClientSelect="onGeographyChange" />&thinsp;<br/>
<asp:TextBox runat="server" ID="TextNamePattern" />
</div>
<div class="entryLabels">
Geography<br/>
Name pattern<br/>
<div class="entryLabels" style="padding-top:10px">
<asp:Label ID="LabelGeography" runat="server" /><br/>
<asp:Label ID="LabelNamePattern" runat="server" /><br/>
</div>
<h2>Matching people</h2>
<table id="TablePayableCosts" class="easyui-datagrid" style="width:680px;height:500px"
data-options="rownumbers:false,singleSelect:false,nowrap:false,fit:false,loading:false,selectOnCheck:true,checkOnSelect:true,url:'Json-PayableCosts.aspx'"
<h2 style="padding-top:15px"><asp:Label ID="LabelMatchingPeopleInX" runat="server" /></h2>
<table id="TableSearchResults" class="easyui-datagrid" style="width:680px;height:500px"
data-options="rownumbers:false,singleSelect:false,nowrap:false,fit:false,loading:false,selectOnCheck:true,checkOnSelect:true,url:''"
idField="itemId">
<thead>
<tr>
<th data-options="field:'due',width:70"><asp:Label ID="LabelGridHeaderDue" runat="server" Text="XYZ Due"/></th>
<th data-options="field:'recipient',width:150,sortable:true"><asp:Label ID="LabelGridHeaderRecipient" runat="server" Text="XYZ Beneficiary" /></th>
<thead>
<tr>
<th data-options="field:'name',width:70"><asp:Label ID="LabelGridHeaderDue" runat="server" Text="XYZ Due"/></th>
<th data-options="field:'geographyName',width:150,sortable:true"><asp:Label ID="LabelGridHeaderRecipient" runat="server" Text="XYZ Beneficiary" /></th>
<th data-options="field:'bank',width:70"><asp:Label ID="LabelGridHeaderBank" runat="server" Text="XYZ Bank" /></th>
<th data-options="field:'account',width:120,sortable:true"><asp:Label ID="LabelGridHeaderAccount" runat="server" Text="XYZ Account" /></th>
<th data-options="field:'reference',width:140,sortable:true,order:'asc'"><asp:Label ID="LabelGridHeaderReference" runat="server" Text="XYZ Reference" /></th>
@@ -11,7 +11,7 @@ using Swarmops.Database;
using Swarmops.Logic.Financial;
using Swarmops.Logic.Security;
namespace Swarmops.Frontend.Pages.People
namespace Swarmops.Frontend.Pages.Swarm
{
public partial class ListFindPeople : PageV5Base
{
@@ -29,9 +29,13 @@ namespace Swarmops.Frontend.Pages.People
private void Localize()
{
this.PageTitle = Resources.Pages.Financial.PayOutMoney_PageTitle;
this.InfoBoxLiteral = Resources.Pages.Financial.PayOutMoney_Info;
this.LabelPayOutMoneyHeader.Text = Resources.Pages.Financial.PayOutMoney_Header;
this.PageTitle = Resources.Pages.People.ListFindPeople_Title;
this.InfoBoxLiteral = Resources.Pages.People.ListFindPeople_Info;
this.LabelGeography.Text = Resources.Global.Global_Geography;
this.LabelNamePattern.Text = Resources.Pages.People.ListFindPeople_NamePattern;
this.LabelMatchingPeopleInX.Text = String.Format(Resources.Pages.People.ListFindPeople_MatchingPeopleInX,
this.CurrentOrganization.Name);
this.LabelGridHeaderAccount.Text = Resources.Pages.Financial.PayOutMoney_GridHeader_BankAccount;
this.LabelGridHeaderAmount.Text = Resources.Pages.Financial.PayOutMoney_GridHeader_Amount;
this.LabelGridHeaderBank.Text = Resources.Pages.Financial.PayOutMoney_GridHeader_BankName;
+1 -1
View File
@@ -36,7 +36,7 @@ namespace Swarmops.Utility.BotCode
case (int)TypedMailTemplate.TemplateType.MemberMail:
// All members at this org and geography
People people = People.FromOrganizationAndGeography(mail.OrganizationId, mail.GeographyId);
People people = People.FromOrganizationAndGeography(mail.Organization, mail.Geography);
downwardCount = people.Count;
foreach (Person person in people)
{