Fix false removal of critical files

This commit is contained in:
Rick Falkvinge
2018-03-03 15:09:25 +01:00
parent 572e4c1842
commit 42c46f8e2d
5 changed files with 995 additions and 0 deletions
+431
View File
@@ -0,0 +1,431 @@
using System;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Web;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
namespace Swarmops.Frontend
{
/// <summary>
/// Summary description for CommonV5
/// </summary>
public class CommonV5
{
public static void CulturePreInit (HttpRequest request)
{
// Localization
// Set default culture (English, United States)
string preferredCulture = "en-US";
// ----------- SET CULTURE ------------
// Does the user have a culture preference?
if (request.Cookies["PreferredCulture"] != null)
{
// Yes, set it
preferredCulture = request.Cookies["PreferredCulture"].Value;
}
else
{
// No, determine from browser
string browserPreference = "en-US";
if (request.UserLanguages != null && request.UserLanguages.Length > 0)
{
browserPreference = request.UserLanguages[0];
preferredCulture = browserPreference;
}
/*
string[] languages = (string[])Application["Cultures"];
for (int index = 0; index < languages.Length; index++)
{
if (languages[index].StartsWith(browserPreference))
{
preferredCulture = languages[index];
}
}*/
}
GregorianCalendar normalizedCalendar = new GregorianCalendar();
normalizedCalendar.CalendarType = GregorianCalendarTypes.USEnglish;
// avoids problems with Arabic, etc, calendars and bookkeeping in localization
try
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture (preferredCulture);
}
catch (Exception) // if we can't set the culture, what do we do? ("We send the Marines.")
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
// throw new Exception("Could not set culture \"" + preferredCulture + "\"", exception);
// Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
}
// Set the calendar to GregorianCalendar.USEnglish. This sometimes fails on Windows but works on Mono. If it fails on Windows, no biggie b/c
// this is supposed to be the default anyway.
try
{
Thread.CurrentThread.CurrentCulture.DateTimeFormat.Calendar = normalizedCalendar;
Thread.CurrentThread.CurrentUICulture.DateTimeFormat.Calendar = normalizedCalendar;
}
catch (Exception)
{
// meh
}
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}
public static AuthenticationData GetAuthenticationDataAndCulture (HttpContext suppliedContext)
{
// This function is called from all the V5 base classes to have a common
// authentication point for every derived master, page, and control.
// This function is also called from static page methods in AJAX calls to get
// the current set of authentication data. Static page methods cannot access
// the instance data of PageV5Base.
AuthenticationData result =
AuthenticationData.FromAuthority (Authority.FromEncryptedXml (suppliedContext.User.Identity.Name));
CulturePreInit (HttpContext.Current.Request);
return result;
}
public static Authority InitAuthority()
{
try
{
Authority authority = CommonV5.GetAuthenticationDataAndCulture(HttpContext.Current).Authority;
return authority;
}
catch (Exception)
{
// if this fails FOR WHATEVER REASON then we're not authenticated
System.Web.Security.FormsAuthentication.SignOut();
if (!HttpContext.Current.Request.Path.ToLowerInvariant().StartsWith("/security/login"))
{
// If we're not already on the login page, put us on the login page leading to Dashboard
HttpContext.Current.Response.Redirect("/");
}
return null;
}
}
public static string JavascriptEscape (string input)
{
if (String.IsNullOrEmpty (input))
{
return String.Empty;
}
return System.Uri.EscapeDataString (input).Replace ("'", "%27").Replace ("\"", "%22");
// makes it safe to embed in single/double quotes client-side
}
/* COLOR SCHEME
#A2BEFF #476EC7 #1C397E #C8D9FF #E4ECFF -- blue (hue 240)
#FFBC37 #C78B15 #7F5500 #FFD580 #FFEDC8 -- orange (hue 60)
base dark xdark light xlight
S36L100 S64-L78 S78-L49 S22B100 S11L100 -- blue (hue 222)
S78L100 S89-L78 S100L50 S50L100 S22L100 -- orange (hue 40)
*/
public static string GetColor (ColorType type, ColorVariant variant, ColorShift shift = ColorShift.None)
{
int hue = (type == ColorType.Base ? 222 : 40);
int saturation = 0;
int luminosity = 0;
switch (variant)
{
case ColorVariant.Base:
saturation = 100;
luminosity = 80;
break;
case ColorVariant.Dark:
saturation = 50;
luminosity = 50;
break;
case ColorVariant.XDark:
saturation = 65;
luminosity = 30;
break;
case ColorVariant.Light:
saturation = 100;
luminosity = 90;
break;
case ColorVariant.XLight:
saturation = 100;
luminosity = 95;
break;
default:
throw new NotImplementedException();
}
if (type == ColorType.Accent)
{
saturation *= 2;
if (saturation > 100)
{
saturation = 100;
}
}
switch (shift)
{
case ColorShift.SlightlyDarker:
luminosity -= 2;
break;
case ColorShift.SlightlyLighter:
luminosity += 2;
break;
default:
// do nothing
break;
}
Color color = ColorFromAhsb (100, hue, saturation/100.0, luminosity/100.0);
return String.Format ("#{0:x2}{1:x2}{2:x2}", color.R, color.G, color.B);
}
public static Color ColorFromAhsb (int a, double h, double s, double b)
{
if (s < 0.001)
{
return Color.FromArgb (a, Convert.ToInt32 (b*255),
Convert.ToInt32 (b*255), Convert.ToInt32 (b*255));
}
double fMax, fMid, fMin;
int iSextant, iMax, iMid, iMin;
if (0.5 < b)
{
fMax = b - (b*s) + s;
fMin = b + (b*s) - s;
}
else
{
fMax = b + (b*s);
fMin = b - (b*s);
}
iSextant = (int) Math.Floor (h/60f);
if (300f <= h)
{
h -= 360f;
}
h /= 60f;
h -= 2f*(float) Math.Floor (((iSextant + 1f)%6f)/2f);
if (0 == iSextant%2)
{
fMid = h*(fMax - fMin) + fMin;
}
else
{
fMid = fMin - h*(fMax - fMin);
}
iMax = Convert.ToInt32 (fMax*255);
iMid = Convert.ToInt32 (fMid*255);
iMin = Convert.ToInt32 (fMin*255);
switch (iSextant)
{
case 1:
return Color.FromArgb (a, iMid, iMax, iMin);
case 2:
return Color.FromArgb (a, iMin, iMax, iMid);
case 3:
return Color.FromArgb (a, iMin, iMid, iMax);
case 4:
return Color.FromArgb (a, iMid, iMin, iMax);
case 5:
return Color.FromArgb (a, iMax, iMin, iMid);
default:
return Color.FromArgb (a, iMax, iMid, iMin);
}
}
protected static string HslToWebColor (int hue, int saturation, int luminosity) // 0-359, 0-100, 0-100
{
// This code is adapted from Wikipedia. Believed to be in the public domain or at the very least
// completely unencumbered.
double h = hue/360.0;
double s = saturation/100.0;
double l = luminosity/100.0;
double r, g, b;
if (s < 0.0001) // zero
{
r = g = b = l; // achromatic
}
else
{
double q = l < 0.5 ? l*(1 + s) : l + s - l*s;
double p = 2*l - q;
r = Hue2Rgb (p, q, h + 1/3);
g = Hue2Rgb (p, q, h);
b = Hue2Rgb (p, q, h - 1/3);
}
return String.Format ("#{0:x2}{1:x2}{2:x2}", (int) (r*255), (int) (g*255), (int) (b*255));
}
private static double Hue2Rgb (double p, double q, double t)
{
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p)*6*t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p)*(2/3 - t)*6;
return p;
}
}
public class AuthenticationData
{
public static AuthenticationData FromAuthority (Authority authority)
{
return new AuthenticationData {Authority = authority};
}
public Authority Authority { get; private set; }
public Organization CurrentOrganization
{
get { return Authority.Organization; }
}
public Person CurrentUser
{
get { return Authority.Person; }
}
}
[Serializable]
public class AjaxCallResult
{
public bool Success { get; set; }
public string DisplayMessage { get; set; }
}
[Serializable]
public class AjaxInputCallResult : AjaxCallResult
{
/// <summary>
/// This reflects the object Id sent for editing, to deal with async situations
/// </summary>
public int ObjectIdentity { get; set; }
/// <summary>
/// Must always be set if Success is true, and contain canonically formatted new value
/// </summary>
public string NewValue { get; set; }
/// <summary>
/// When Success is false, valid FailReason values are "AccessDenied", "ServerError" and "InvalidFormat"
/// </summary>
public string FailReason { get; set; }
public const string ErrorAccessDenied = "AccessDenied";
public const string ErrorServerError = "ServerError";
public const string ErrorInvalidFormat = "InvalidFormat";
}
public enum ColorType
{
Unkown = 0,
Base,
Accent
}
public enum ColorVariant
{
Unknown = 0,
Base,
Light,
XLight,
Dark,
XDark
}
public enum ColorShift
{
Unknown = 0,
None,
SlightlyLighter,
SlightlyDarker
}
[Flags]
// ReSharper disable once InconsistentNaming
public enum EasyUIControl
{
Unknown = 0,
Accordion = 0x0000001,
Calendar = 0x0000002,
Combo = 0x0000004,
ComboBox = 0x0000008,
DataGrid = 0x0000010,
DateBox = 0x0000020,
Dialog = 0x0000040,
FileBox = 0x0000080,
Layout = 0x0000100,
LinkButton = 0x0000200,
Menu = 0x0000400,
MenuButton = 0x0000800,
Messager = 0x0001000,
NumberBox = 0x0002000,
Pagination = 0x0004000,
Panel = 0x0008000,
ProgressBar = 0x0010000,
PropertyGrid = 0x0020000,
SearchBox = 0x0040000,
Slider = 0x0080000,
Spinner = 0x0100000,
SplitButton = 0x0200000,
Tabs = 0x0400000,
TextBox = 0x0800000,
ToolTip = 0x1000000,
Tree = 0x2000000,
ValidateBox = 0x4000000,
Window = 0x8000000
};
[Flags]
public enum IncludedControl
{
Unknown = 0,
FileUpload = 0x00000001,
SwitchButton = 0x00000002,
JsonParameters = 0x00000004
};
}
+75
View File
@@ -0,0 +1,75 @@
using System;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using Swarmops.Logic.Cache;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
namespace Swarmops.Frontend
{
/// <summary>
/// Summary description for ControlV5Base
/// </summary>
public class ControlV5Base : UserControl
{
private Authority _authority;
protected Organization CurrentOrganization
{
get { return _authority.Organization; }
}
protected Person CurrentUser
{
get { return _authority.Person; }
}
protected Authority CurrentAuthority
{
get { return this._authority; }
}
protected override void OnInit (EventArgs e)
{
this._authority = CommonV5.InitAuthority();
base.OnInit (e);
}
protected string JavascriptEscape (string input)
{
return CommonV5.JavascriptEscape (input);
}
// ReSharper disable InconsistentNaming
public string Localized_AjaxCallException
{
get { return JavascriptEscape (Resources.Global.Error_AjaxCallException); }
}
public string Localized_AjaxGeneralErrorSettingValue
{
get { return JavascriptEscape (Resources.Global.Error_UnspecifiedAjaxSetValue); }
}
public string Localized_ConfirmDialog_Ok
{
get { return JavascriptEscape(Resources.Global.Global_Ok); }
}
public string Localized_ConfirmDialog_Proceed
{
get { return JavascriptEscape(Resources.Global.Global_Proceed); }
}
public string Localized_ConfirmDialog_Cancel
{
get { return JavascriptEscape(Resources.Global.Global_Cancel); }
}
}
}
+206
View File
@@ -0,0 +1,206 @@
using System;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using Swarmops.Common.Enums;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
namespace Swarmops.Frontend
{
/// <summary>
/// Summary description for PageV5Base
/// Base class to use for all pages that uses the Swarmops-v5 master page
/// </summary>
public class DataV5Base : Page
{
public Access PageAccessRequired = null; // v5 mechanism
protected Person CurrentUser
{
get
{
if (CurrentAuthority != null)
{
return CurrentAuthority.Person;
}
return null;
}
}
protected Organization CurrentOrganization
{
get
{
if (CurrentAuthority != null)
{
return CurrentAuthority.Organization;
}
return null;
}
}
protected Authority CurrentAuthority { get; private set; }
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
protected override void OnInitComplete (EventArgs e)
{
base.OnInitComplete (e);
string identity = HttpContext.Current.User.Identity.Name;
if (!string.IsNullOrEmpty (identity))
{
try
{
CurrentAuthority = CommonV5.GetAuthenticationDataAndCulture (HttpContext.Current).Authority;
}
catch (Exception)
{
// if this fails FOR WHATEVER REASON then we're not authenticated
this.CurrentAuthority = null;
FormsAuthentication.SignOut();
}
}
else
{
CurrentAuthority = null; // unauthenticated!
}
// Regardless of auth data and culture, set Gregorian calendar
// (avoids problems with Arabic, etc, calendars and bookkeeping in localization)
GregorianCalendar normalizedCalendar = new GregorianCalendar();
normalizedCalendar.CalendarType = GregorianCalendarTypes.USEnglish;
// Set the calendar to GregorianCalendar.USEnglish. This sometimes fails on Windows but works
// on Mono. If it fails on Windows, no biggie b/c this is supposed to be the default anyway.
try
{
Thread.CurrentThread.CurrentCulture.DateTimeFormat.Calendar = normalizedCalendar;
Thread.CurrentThread.CurrentUICulture.DateTimeFormat.Calendar = normalizedCalendar;
}
catch (Exception)
{
// meh
}
}
protected override void OnPreInit (EventArgs e)
{
CommonV5.CulturePreInit (Request);
base.OnPreInit (e);
}
protected override void OnPreRender (EventArgs e)
{
// Check security of page against users's credentials
if (this.PageAccessRequired != null)
{
if (!this.CurrentAuthority.HasAccess (this.PageAccessRequired))
{
Response.Redirect ("/Pages/v5/Security/AccessDenied.aspx");
}
}
base.OnPreRender (e);
}
protected string LocalizeCount (string resourceString, int count)
{
return LocalizeCount (resourceString, count, false);
}
protected string LocalizeCount (string resourceString, int count, bool capitalize)
{
string result;
string[] parts = resourceString.Split ('|');
switch (count)
{
case 0:
result = parts[0];
break;
case 1:
result = parts[1];
break;
default:
result = String.Format (parts[2], count);
break;
}
if (capitalize)
{
result = Char.ToUpperInvariant (result[0]) + result.Substring (1);
}
return result;
}
protected string TryLocalize (string input)
{
if (!input.StartsWith ("[Loc]"))
{
return input;
}
string[] inputParts = input.Split ('|');
string resourceKey = inputParts[0].Substring (5);
object translatedResource = GetGlobalResourceObject ("Global", resourceKey);
if (translatedResource == null)
{
throw new NotImplementedException ("Unimplemented localization resource key: \"" + resourceKey + "\"");
}
if (inputParts.Length == 1)
{
return translatedResource.ToString();
}
object argument = null;
if (inputParts[1].StartsWith ("[Date]"))
{
argument = DateTime.Parse (inputParts[1].Substring (6), CultureInfo.InvariantCulture);
}
else
{
argument = inputParts[1];
}
return String.Format (translatedResource.ToString(), argument);
}
protected static AuthenticationData GetAuthenticationDataAndCulture()
{
return CommonV5.GetAuthenticationDataAndCulture (HttpContext.Current);
}
protected static string JsonSanitize (string input)
{
return input.Replace ("\"", "\\\"").Replace (" ", " ").Trim();
}
public static string JavascriptEscape (string input)
{
return CommonV5.JavascriptEscape (input);
}
public string Localize_GenericAjaxError
{
get { return JavascriptEscape(Resources.Global.Error_AjaxCallException); }
}
}
}
+71
View File
@@ -0,0 +1,71 @@
using System;
using System.Web.UI;
using Swarmops.Common;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Swarm;
namespace Swarmops.Frontend
{
/// <summary>
/// Summary description for MasterV4Base
/// </summary>
public class MasterV5Base : MasterPage
{
public bool CurrentPageAllowed = false;
public string CurrentPageIcon = string.Empty;
public string CurrentPageInfoBoxLiteral = string.Empty;
public bool CurrentPageProhibited = false;
public string CurrentPageTitle = string.Empty;
// ReSharper disable InconsistentNaming
protected Authority _authority = null; // This is set in Master-v5.master.cs
public EasyUIControl EasyUIControlsUsed { get; set; }
// these are set by each page, and called by Master to render in ExternalScripts control
public IncludedControl IncludedControlsUsed { get; set; } // as above with IncludedScripts control
// ReSharper restore InconsistentNaming
public MasterV5Base()
{
IncludedControlsUsed = IncludedControl.JsonParameters; // Include this by default to reduce errors
}
public DateTime PermissionCacheTimestamp
{
get
{
if (Session["MainMenu-v5_Enabling_TimeStamp"] != null)
{
return new DateTime ((long) Session["MainMenu-v5_Enabling_TimeStamp"]);
}
return Constants.DateTimeLow;
}
set { Session["MainMenu-v5_Enabling_TimeStamp"] = value.Ticks; }
}
public Person CurrentUser
{
get { return this._authority.Person; }
}
public Organization CurrentOrganization
{
get { return this._authority.Organization; }
}
public Authority CurrentAuthority
{
get { return this._authority; }
}
}
}
+212
View File
@@ -0,0 +1,212 @@
using System;
using System.Security;
using System.Web;
using System.Web.UI;
using Swarmops.Common.Enums;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
namespace Swarmops.Frontend
{
/// <summary>
/// Base class to use for all data generators (JSON, etc). It supplies identification and localization.
/// </summary>
public class PageV5Base : Page
{
public int DbVersionRequired = 0; // v5 mechanism
public Access PageAccessRequired = null; // v5 mechanism
public bool IsDashboard = false; // if true, master doesn't box in
protected new MasterV5Base Master
{
get { return (MasterV5Base) base.Master; }
}
protected string PageTitle
{
get { return Master.CurrentPageTitle; }
set { Master.CurrentPageTitle = value; }
}
protected string PageIcon
{
get { return Master.CurrentPageIcon; }
set { Master.CurrentPageIcon = value; }
}
protected string InfoBoxLiteral
{
get { return Master.CurrentPageInfoBoxLiteral; }
set { Master.CurrentPageInfoBoxLiteral = value; }
}
// ReSharper disable once InconsistentNaming
private EasyUIControl EasyUIControlsUsed
{
get { return Master.EasyUIControlsUsed; }
set { Master.EasyUIControlsUsed = value; }
}
private IncludedControl IncludedControlsUsed
{
get { return Master.IncludedControlsUsed; }
set { Master.IncludedControlsUsed = value; }
}
protected Person CurrentUser
{
get { return Master.CurrentUser; }
}
protected Organization CurrentOrganization
{
get { return Master.CurrentOrganization; }
}
protected Authority CurrentAuthority
{
get { return Master.CurrentAuthority; }
}
/// <summary>
/// This is used to identify special cases for pilot installations. It is also used as an installation-unique
/// encryption key salt in addition to record-specific salting.
/// </summary>
protected string InstallationId
{
get { return SystemSettings.InstallationId; }
}
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
protected override void OnInitComplete (EventArgs e)
{
base.OnInitComplete (e);
}
protected override void OnPreInit (EventArgs e)
{
CommonV5.CulturePreInit (Request);
base.OnPreInit (e);
}
protected override void OnPreRender (EventArgs e)
{
// Check that the page has security defined
if (this.PageAccessRequired == null && !this.GetType().FullName.ToLowerInvariant().Contains ("accessdenied"))
{
throw new SecurityException ("Page security is undefined at " + this.GetType().FullName +
". This is not permitted: minimum security must be defined for every page.");
}
// Check security of page against users's credentials
if (!this.CurrentAuthority.HasAccess (this.PageAccessRequired))
{
Response.Redirect ("/Pages/v5/Security/AccessDenied.aspx");
}
// Check necessary database revision
if (this.DbVersionRequired > SupportFunctions.DatabaseSchemaVersion)
{
Response.Redirect ("/Pages/v5/Security/DatabaseUpgradeRequired.aspx");
}
base.OnPreRender (e);
}
protected string LocalizeCount (string resourceString, int count)
{
return LocalizeCount (resourceString, count, false);
}
protected string LocalizeCount (string resourceString, int count, bool capitalize)
{
string result;
string[] parts = resourceString.Split ('|');
switch (count)
{
case 0:
result = parts[0];
break;
case 1:
result = parts[1];
break;
default:
result = String.Format (parts[2], count);
break;
}
if (capitalize)
{
result = Char.ToUpperInvariant (result[0]) + result.Substring (1);
}
return result;
}
protected static AuthenticationData GetAuthenticationDataAndCulture()
{
// This function is called from static page methods in AJAX calls to get
// the current set of authentication data. Static page methods cannot access
// the instance data of PageV5Base.
return CommonV5.GetAuthenticationDataAndCulture (HttpContext.Current);
}
public void RegisterControl (EasyUIControl control) // public for use by child controls
{
this.EasyUIControlsUsed |= control;
}
public void RegisterControl (IncludedControl control) // public for use by child controls
{
this.IncludedControlsUsed |= control;
}
public string JavascriptEscape (string input)
{
return CommonV5.JavascriptEscape (input);
}
// Common localizations
// ReSharper disable InconsistentNaming
public string Localized_SwitchLabelOn_Upper
{
get { return JavascriptEscape(Resources.Global.Global_On.ToUpperInvariant()); }
}
public string Localized_SwitchLabelOff_Upper
{
get { return JavascriptEscape(Resources.Global.Global_Off.ToUpperInvariant()); }
}
public string Localized_ConfirmDialog_Ok
{
get { return JavascriptEscape(Resources.Global.Global_Ok); }
}
public string Localized_ConfirmDialog_Proceed
{
get { return JavascriptEscape(Resources.Global.Global_Proceed); }
}
public string Localized_ConfirmDialog_Cancel
{
get { return JavascriptEscape(Resources.Global.Global_Cancel); }
}
public bool SuppressStatisticHeaders { get; set; } // defaults to false
}
}