move the scheduler to a windows service
This commit is contained in:
parent
97f09a5683
commit
5e414136b2
115 changed files with 587 additions and 166 deletions
|
@ -0,0 +1,78 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Configuration;
|
||||
using System.Web;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for ConfigSettings.
|
||||
/// </summary>
|
||||
public class ConfigSettings
|
||||
{
|
||||
public static string DataProviderType
|
||||
{
|
||||
get { return ConfigurationManager.AppSettings["WebsitePanel.EnterpriseServer.DataProvider"]; }
|
||||
}
|
||||
|
||||
public static string WebApplicationsPath
|
||||
{
|
||||
get
|
||||
{
|
||||
string path = ConfigurationManager.AppSettings["WebsitePanel.EnterpriseServer.WebApplicationsPath"];
|
||||
if (path.StartsWith("~") && HttpContext.Current != null)
|
||||
path = HttpContext.Current.Server.MapPath(path);
|
||||
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
public static string BackupsPath
|
||||
{
|
||||
get
|
||||
{
|
||||
SystemSettings settings = SystemController.GetSystemSettingsInternal(
|
||||
SystemSettings.BACKUP_SETTINGS,
|
||||
false
|
||||
);
|
||||
|
||||
return settings["BackupsPath"];
|
||||
}
|
||||
}
|
||||
|
||||
#region Communication
|
||||
public static int ServerRequestTimeout
|
||||
{
|
||||
get { return Utils.ParseInt(
|
||||
ConfigurationManager.AppSettings["WebsitePanel.EnterpriseServer.ServerRequestTimeout"], -1); }
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,227 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Security.Cryptography;
|
||||
using System.Configuration;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for CryptoUtils.
|
||||
/// </summary>
|
||||
public class CryptoUtils
|
||||
{
|
||||
static string EnterpriseServerRegistryPath = "SOFTWARE\\WebsitePanel\\EnterpriseServer";
|
||||
|
||||
public static string CryptoKey
|
||||
{
|
||||
get
|
||||
{
|
||||
string Key = ConfigurationManager.AppSettings["WebsitePanel.AltCryptoKey"];
|
||||
string value = string.Empty;
|
||||
|
||||
if (!string.IsNullOrEmpty(Key))
|
||||
{
|
||||
RegistryKey root = Registry.LocalMachine;
|
||||
RegistryKey rk = root.OpenSubKey(EnterpriseServerRegistryPath);
|
||||
if (rk != null)
|
||||
{
|
||||
value = (string)rk.GetValue(Key, null);
|
||||
rk.Close();
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
return value;
|
||||
else
|
||||
return ConfigurationManager.AppSettings["WebsitePanel.CryptoKey"];
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public static bool EncryptionEnabled
|
||||
{
|
||||
get
|
||||
{
|
||||
return (ConfigurationManager.AppSettings["WebsitePanel.EncryptionEnabled"] != null)
|
||||
? Boolean.Parse(ConfigurationManager.AppSettings["WebsitePanel.EncryptionEnabled"]) : true;
|
||||
}
|
||||
}
|
||||
|
||||
public static string Encrypt(string InputText)
|
||||
{
|
||||
string Password = CryptoKey;
|
||||
|
||||
if(!EncryptionEnabled)
|
||||
return InputText;
|
||||
|
||||
if (InputText == null)
|
||||
return InputText;
|
||||
|
||||
// We are now going to create an instance of the
|
||||
// Rihndael class.
|
||||
RijndaelManaged RijndaelCipher = new RijndaelManaged();
|
||||
|
||||
// First we need to turn the input strings into a byte array.
|
||||
byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);
|
||||
|
||||
|
||||
// We are using salt to make it harder to guess our key
|
||||
// using a dictionary attack.
|
||||
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
|
||||
|
||||
|
||||
// The (Secret Key) will be generated from the specified
|
||||
// password and salt.
|
||||
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
|
||||
|
||||
|
||||
// Create a encryptor from the existing SecretKey bytes.
|
||||
// We use 32 bytes for the secret key
|
||||
// (the default Rijndael key length is 256 bit = 32 bytes) and
|
||||
// then 16 bytes for the IV (initialization vector),
|
||||
// (the default Rijndael IV length is 128 bit = 16 bytes)
|
||||
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
|
||||
|
||||
|
||||
// Create a MemoryStream that is going to hold the encrypted bytes
|
||||
MemoryStream memoryStream = new MemoryStream();
|
||||
|
||||
|
||||
// Create a CryptoStream through which we are going to be processing our data.
|
||||
// CryptoStreamMode.Write means that we are going to be writing data
|
||||
// to the stream and the output will be written in the MemoryStream
|
||||
// we have provided. (always use write mode for encryption)
|
||||
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
|
||||
|
||||
// Start the encryption process.
|
||||
cryptoStream.Write(PlainText, 0, PlainText.Length);
|
||||
|
||||
|
||||
// Finish encrypting.
|
||||
cryptoStream.FlushFinalBlock();
|
||||
|
||||
// Convert our encrypted data from a memoryStream into a byte array.
|
||||
byte[] CipherBytes = memoryStream.ToArray();
|
||||
|
||||
|
||||
|
||||
// Close both streams.
|
||||
memoryStream.Close();
|
||||
cryptoStream.Close();
|
||||
|
||||
|
||||
|
||||
// Convert encrypted data into a base64-encoded string.
|
||||
// A common mistake would be to use an Encoding class for that.
|
||||
// It does not work, because not all byte values can be
|
||||
// represented by characters. We are going to be using Base64 encoding
|
||||
// That is designed exactly for what we are trying to do.
|
||||
string EncryptedData = Convert.ToBase64String(CipherBytes);
|
||||
|
||||
|
||||
|
||||
// Return encrypted string.
|
||||
return EncryptedData;
|
||||
}
|
||||
|
||||
|
||||
public static string Decrypt(string InputText)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(!EncryptionEnabled)
|
||||
return InputText;
|
||||
|
||||
if (InputText == null || InputText == "")
|
||||
return InputText;
|
||||
|
||||
string Password = CryptoKey;
|
||||
RijndaelManaged RijndaelCipher = new RijndaelManaged();
|
||||
|
||||
|
||||
byte[] EncryptedData = Convert.FromBase64String(InputText);
|
||||
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
|
||||
|
||||
|
||||
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
|
||||
|
||||
// Create a decryptor from the existing SecretKey bytes.
|
||||
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
|
||||
|
||||
|
||||
MemoryStream memoryStream = new MemoryStream(EncryptedData);
|
||||
|
||||
// Create a CryptoStream. (always use Read mode for decryption).
|
||||
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
|
||||
|
||||
|
||||
// Since at this point we don't know what the size of decrypted data
|
||||
// will be, allocate the buffer long enough to hold EncryptedData;
|
||||
// DecryptedData is never longer than EncryptedData.
|
||||
byte[] PlainText = new byte[EncryptedData.Length];
|
||||
|
||||
// Start decrypting.
|
||||
int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
|
||||
|
||||
|
||||
memoryStream.Close();
|
||||
cryptoStream.Close();
|
||||
|
||||
// Convert decrypted data into a string.
|
||||
string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
|
||||
|
||||
|
||||
// Return decrypted string.
|
||||
return DecryptedData;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static string SHA1(string plainText)
|
||||
{
|
||||
// Convert plain text into a byte array.
|
||||
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
|
||||
|
||||
HashAlgorithm hash = new SHA1Managed();;
|
||||
|
||||
// Compute hash value of our plain text with appended salt.
|
||||
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
|
||||
|
||||
// Return the result.
|
||||
return Convert.ToBase64String(hashBytes);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Security;
|
||||
using System.Security.Principal;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
public class EnterpriseServerIdentity : IIdentity
|
||||
{
|
||||
string name;
|
||||
|
||||
public EnterpriseServerIdentity(string name)
|
||||
{
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
#region IIdentity Members
|
||||
|
||||
public string AuthenticationType
|
||||
{
|
||||
get { return "Enterprise Server"; }
|
||||
}
|
||||
|
||||
public bool IsAuthenticated
|
||||
{
|
||||
get { return true; }
|
||||
}
|
||||
|
||||
public string Name
|
||||
{
|
||||
get { return name; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,100 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Security;
|
||||
using System.Security.Principal;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
public class EnterpriseServerPrincipal : IPrincipal
|
||||
{
|
||||
private int userId;
|
||||
private int ownerId;
|
||||
private bool isPeer;
|
||||
private bool isDemo;
|
||||
private UserStatus status;
|
||||
|
||||
private List<string> roles = new List<string>();
|
||||
private IIdentity identity;
|
||||
|
||||
public EnterpriseServerPrincipal(IIdentity identity, string[] roles)
|
||||
{
|
||||
this.identity = identity;
|
||||
this.roles.AddRange(roles);
|
||||
}
|
||||
|
||||
#region IPrincipal Members
|
||||
|
||||
public IIdentity Identity
|
||||
{
|
||||
get { return identity; }
|
||||
}
|
||||
|
||||
public bool IsInRole(string role)
|
||||
{
|
||||
return roles.Contains(role);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public properties
|
||||
public int UserId
|
||||
{
|
||||
get { return this.userId; }
|
||||
set { this.userId = value; }
|
||||
}
|
||||
|
||||
public int OwnerId
|
||||
{
|
||||
get { return this.ownerId; }
|
||||
set { this.ownerId = value; }
|
||||
}
|
||||
|
||||
public bool IsPeer
|
||||
{
|
||||
get { return this.isPeer; }
|
||||
set { this.isPeer = value; }
|
||||
}
|
||||
|
||||
public bool IsDemo
|
||||
{
|
||||
get { return this.isDemo; }
|
||||
set { this.isDemo = value; }
|
||||
}
|
||||
|
||||
public UserStatus Status
|
||||
{
|
||||
get { return this.status; }
|
||||
set { this.status = value; }
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,121 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Collections.Generic;
|
||||
using Ionic.Zip;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
public class FileUtils
|
||||
{
|
||||
#region Zip/Unzip Methods
|
||||
|
||||
public static void ZipFiles(string zipFile, string rootPath, string[] files)
|
||||
{
|
||||
using (ZipFile zip = new ZipFile())
|
||||
{
|
||||
//use unicode if necessary
|
||||
zip.UseUnicodeAsNecessary = true;
|
||||
//skip locked files
|
||||
zip.ZipErrorAction = ZipErrorAction.Skip;
|
||||
foreach (string file in files)
|
||||
{
|
||||
string fullPath = Path.Combine(rootPath, file);
|
||||
if (Directory.Exists(fullPath))
|
||||
{
|
||||
//add directory with the same directory name
|
||||
zip.AddDirectory(fullPath, file);
|
||||
}
|
||||
else if (File.Exists(fullPath))
|
||||
{
|
||||
//add file to the root folder
|
||||
zip.AddFile(fullPath, "");
|
||||
}
|
||||
}
|
||||
zip.Save(zipFile);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<string> UnzipFiles(string zipFile, string destFolder)
|
||||
{
|
||||
using (ZipFile zip = ZipFile.Read(zipFile))
|
||||
{
|
||||
foreach (ZipEntry e in zip)
|
||||
{
|
||||
e.Extract(destFolder, ExtractExistingFileAction.OverwriteSilently);
|
||||
}
|
||||
}
|
||||
|
||||
// return extracted files names
|
||||
return GetFileNames(destFolder);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Helper Functions
|
||||
|
||||
/// <summary>
|
||||
/// This function enumerates all directories and files of the <paramref name="direcrotyPath"/> specified.
|
||||
/// </summary>
|
||||
/// <param name="direcrotyPath">Path to the directory.</param>
|
||||
/// <returns>
|
||||
/// List of files and directories reside for the <paramref name="direcrotyPath"/> specified.
|
||||
/// Empty, when no files and directories are or path does not exists.
|
||||
/// </returns>
|
||||
public static List<string> GetFileNames(string direcrotyPath)
|
||||
{
|
||||
List<string> items = new List<string>();
|
||||
|
||||
DirectoryInfo root = new DirectoryInfo(direcrotyPath);
|
||||
if (root.Exists)
|
||||
{
|
||||
// list directories
|
||||
foreach (DirectoryInfo dir in root.GetDirectories())
|
||||
{
|
||||
items.Add(
|
||||
System.IO.Path.Combine(direcrotyPath, dir.Name)
|
||||
);
|
||||
}
|
||||
|
||||
// list files
|
||||
foreach (FileInfo file in root.GetFiles())
|
||||
{
|
||||
items.Add(
|
||||
System.IO.Path.Combine(direcrotyPath, file.Name)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,210 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer {
|
||||
|
||||
public struct IPAddress : IComparable {
|
||||
public Int128 Address;
|
||||
public bool V6 { get; private set; }
|
||||
public bool V4 { get { return !V6 || Null; } }
|
||||
public bool IsSubnet { get; private set; }
|
||||
public bool IsMask { get; private set; }
|
||||
public int Cidr { get; private set; }
|
||||
public bool Null { get; private set; }
|
||||
public IPAddress LastSubnetIP { get { return new IPAddress { Address = (Address | (~((Int128)0) >> (V4 ? Cidr + 64 : Cidr))), Cidr = V4 ? 32 : 128, IsSubnet = false, Null = false, V6 = V6 }; } }
|
||||
public IPAddress FirstSubnetIP { get { return new IPAddress { Address = (Address & ~(~((Int128)0) >> (V4 ? Cidr + 64 : Cidr))) + 1, Cidr = V4 ? 32 : 128, IsSubnet = false, Null = false, V6 = V6 }; } }
|
||||
public Int128 Mask { get { return IsSubnet ? Int128.MinValue >> (Cidr-1) : Address; } }
|
||||
|
||||
const int c = 256*256;
|
||||
|
||||
public static IPAddress Parse(string ip)
|
||||
{
|
||||
IPAddress adr = default(IPAddress);
|
||||
adr.V6 = false;
|
||||
|
||||
if (String.IsNullOrEmpty(ip)) {
|
||||
adr.Address = 0; adr.Null = true; adr.Cidr = 32; adr.IsSubnet = false;
|
||||
return adr;
|
||||
}
|
||||
|
||||
if (ip.Contains('/')) {
|
||||
var tokens = ip.Split('/');
|
||||
ip = tokens[0];
|
||||
adr.IsSubnet = true;
|
||||
adr.Cidr = Utils.ParseInt(tokens[1], -1);
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(ip)) {
|
||||
adr.IsMask = true; adr.V6 = true;
|
||||
adr.Address = adr.Mask;
|
||||
} else {
|
||||
|
||||
var ipadr = System.Net.IPAddress.Parse(ip);
|
||||
|
||||
if (adr.V6 = ipadr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) {
|
||||
byte[] bytes = ipadr.GetAddressBytes();
|
||||
Int128 a = 0;
|
||||
for (int i = 0; i < 16; i++) {
|
||||
a = a * 256 + bytes[i];
|
||||
}
|
||||
adr.Address = a;
|
||||
} else {
|
||||
string[] parts = ip.Split('.');
|
||||
adr.Address = (Int128)(Int32.Parse(parts[3]) +
|
||||
(Int32.Parse(parts[2]) << 8) +
|
||||
(Int32.Parse(parts[1]) << 16) +
|
||||
(Int32.Parse(parts[0]) << 24));
|
||||
}
|
||||
}
|
||||
if (adr.V4 && (adr.Cidr > 32 || 0 > adr.Cidr)) throw new ArgumentOutOfRangeException("Cidr must not be greater than 32 for IPv4 Addresses.");
|
||||
if (adr.V6 && (adr.Cidr > 128 || 0 > adr.Cidr)) throw new ArgumentOutOfRangeException("Cidr must not be greater than 128 for IPv6 Addresses.");
|
||||
return adr;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
if (Null)
|
||||
return "";
|
||||
var s = new System.Text.StringBuilder();
|
||||
if (!V6)
|
||||
{
|
||||
var ipl = Address;
|
||||
if (IsMask)
|
||||
{
|
||||
int digits = 32 - Cidr;
|
||||
ipl = (Int128.MaxValue << 1) | 0x1; // remove left sign bit
|
||||
ipl = ipl << digits;
|
||||
}
|
||||
s.Append(String.Format("{0}.{1}.{2}.{3}", (ipl >> 24) & 0xFFL, (ipl >> 16) & 0xFFL, (ipl >> 8) & 0xFFL, (ipl & 0xFFL)));
|
||||
}
|
||||
else if (!IsMask)
|
||||
{
|
||||
|
||||
var vals = new List<int>();
|
||||
int i;
|
||||
Int128 a = Address;
|
||||
for (i = 0; i < 8; i++) {
|
||||
vals.Add((int)(a % c));
|
||||
a = a / c;
|
||||
}
|
||||
|
||||
int index = -1, n = 0, m = 0;
|
||||
for (i = 7; i >= 0; i--) {
|
||||
if (vals[i] == 0) {
|
||||
n++;
|
||||
if (n > m) {
|
||||
index = i;
|
||||
m = n;
|
||||
}
|
||||
}
|
||||
}
|
||||
index += m-1;
|
||||
|
||||
i = 7;
|
||||
while (i >= 0) {
|
||||
if (i == index) {
|
||||
if (m == 8) s.Append("::");
|
||||
else s.Append(":");
|
||||
i -= m;
|
||||
}
|
||||
if (i >= 0) {
|
||||
if (i < 7) s.Append(":");
|
||||
s.Append(vals[i].ToString("x"));
|
||||
}
|
||||
i--;
|
||||
}
|
||||
}
|
||||
if (IsSubnet && !(IsMask && V4)) {
|
||||
s.Append('/'); s.Append(Cidr.ToString());
|
||||
}
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
public string ToV4MaskString() {
|
||||
V6 = false;
|
||||
IsMask = true;
|
||||
return ToString();
|
||||
}
|
||||
|
||||
public static bool operator ==(IPAddress a, IPAddress b) { return a.Address == b.Address && a.Null == b.Null && (a.Null || !(a.IsSubnet && b.IsSubnet || a.IsMask && b.IsMask) || a.Cidr == b.Cidr); }
|
||||
public static bool operator ==(IPAddress a, long b) { return a.Address == b; }
|
||||
public static bool operator !=(IPAddress a, IPAddress b) { return !(a == b); }
|
||||
public static bool operator !=(IPAddress a, long b) { return a.Address != b; }
|
||||
public static bool operator <(IPAddress a, IPAddress b) { return a.Address < b.Address; }
|
||||
public static bool operator >(IPAddress a, IPAddress b) { return a.Address > b.Address; }
|
||||
public static bool operator <=(IPAddress a, IPAddress b) { return a.Address <= b.Address; }
|
||||
public static bool operator >=(IPAddress a, IPAddress b) { return a.Address >= b.Address; }
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
if (obj is IPAddress)
|
||||
{
|
||||
var b = (IPAddress)obj;
|
||||
return this.Address == b.Address && this.Null == b.Null && (this.Null || !(this.IsSubnet && b.IsSubnet || this.IsMask && b.IsMask) || this.Cidr == b.Cidr);
|
||||
}
|
||||
else if (obj is long)
|
||||
{
|
||||
var b = (long)obj;
|
||||
return this.Address == b;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return this.Address.GetHashCode();
|
||||
}
|
||||
|
||||
/*
|
||||
public static IPAddress operator +(IPAddress a, IPAddress b) {
|
||||
if (a.IsSubnet || b.IsSubnet || a.V6 != b.V6) throw new ArgumentException("Arithmetic with subnets or mixed v4 & v6 addresses not supported.");
|
||||
return new IPAddress { Address = a.Address + b.Address, Null = a.Null && b.Null, Cidr = 0, V6 = a.V6 };
|
||||
}*/
|
||||
|
||||
public static Int128 operator -(IPAddress a, IPAddress b) {
|
||||
if (a.IsSubnet || b.IsSubnet || a.V6 != b.V6) throw new ArgumentException("Arithmetic with subnets or mixed v4 & v6 addresses not supported.");
|
||||
return a.Address - b.Address;
|
||||
}
|
||||
public static IPAddress operator +(IPAddress a, Int128 b) {
|
||||
return new IPAddress { Address = a.Address + b, Null = a.Null, Cidr = a.V4 ? 32 : 128, V6 = a.V6 };
|
||||
}
|
||||
public static IPAddress operator -(IPAddress a, Int128 b) {
|
||||
return new IPAddress { Address = a.Address - b, Null = a.Null, Cidr = a.V4 ? 32 : 128, V6 = a.V6 };
|
||||
}
|
||||
public static IPAddress operator |(IPAddress a, IPAddress b) {
|
||||
if (a.V6 != b.V6) throw new ArgumentException("Arithmetic with mixed v4 & v6 addresses not supported.");
|
||||
return new IPAddress { Address = a.Address | b.Address, Cidr = a.V4 ? 32 : 128, Null = false, V6 = a.V6, IsSubnet = false };
|
||||
}
|
||||
public static IPAddress operator &(IPAddress a, IPAddress b) {
|
||||
if (a.V6 != b.V6) throw new ArgumentException("Arithmetic with mixed v4 & v6 addresses not supported.");
|
||||
return new IPAddress { Address = a.Address & b.Address, Cidr = a.V4 ? 32 : 128, Null = false, V6 = a.V6, IsSubnet = false };
|
||||
}
|
||||
public static IPAddress operator ~(IPAddress a) {
|
||||
if (a.Null) return new IPAddress { Address = 0, Null = true, Cidr = a.V4 ? 32 : 128, V6 = true, IsSubnet = false };
|
||||
return new IPAddress { Address = ~a.Address, Cidr = a.Cidr , Null = false, V6 = a.V6, IsSubnet = false };
|
||||
}
|
||||
|
||||
public static implicit operator IPAddress(NullIPAddress a) { return new IPAddress { Null = true, Address = 0, Cidr = -1 }; }
|
||||
|
||||
public int CompareTo(object obj)
|
||||
{
|
||||
var a = this.Address;
|
||||
var b = ((IPAddress)obj).Address;
|
||||
|
||||
if (a < b)
|
||||
return 1;
|
||||
else if (a > b)
|
||||
return -1;
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public class NullIPAddress { }
|
||||
|
||||
}
|
File diff suppressed because it is too large
Load diff
|
@ -0,0 +1,143 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Net;
|
||||
using System.Net.Mail;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
public class MailHelper
|
||||
{
|
||||
public static int SendMessage(string from, string to, string subject, string body, bool isHtml)
|
||||
{
|
||||
return SendMessage(from, to, null, subject, body, MailPriority.Normal, isHtml);
|
||||
}
|
||||
|
||||
public static int SendMessage(string from, string to, string bcc, string subject, string body, bool isHtml)
|
||||
{
|
||||
return SendMessage(from, to, bcc, subject, body, MailPriority.Normal, isHtml);
|
||||
}
|
||||
|
||||
public static int SendMessage(string from, string to, string bcc, string subject, string body,
|
||||
MailPriority priority, bool isHtml, Attachment[] attachments)
|
||||
{
|
||||
// Command line argument must the the SMTP host.
|
||||
SmtpClient client = new SmtpClient();
|
||||
|
||||
// load SMTP client settings
|
||||
SystemSettings settings = SystemController.GetSystemSettingsInternal(
|
||||
SystemSettings.SMTP_SETTINGS,
|
||||
true
|
||||
);
|
||||
|
||||
client.Host = settings["SmtpServer"];
|
||||
client.Port = settings.GetInt("SmtpPort");
|
||||
if (!String.IsNullOrEmpty(settings["SmtpUsername"]))
|
||||
{
|
||||
client.Credentials = new NetworkCredential(
|
||||
settings["SmtpUsername"],
|
||||
settings["SmtpPassword"]
|
||||
);
|
||||
}
|
||||
|
||||
if (!String.IsNullOrEmpty(settings["SmtpEnableSsl"]))
|
||||
{
|
||||
client.EnableSsl = Utils.ParseBool(settings["SmtpEnableSsl"], false);
|
||||
}
|
||||
|
||||
// create message
|
||||
MailMessage message = new MailMessage(from, to);
|
||||
message.Body = body;
|
||||
message.BodyEncoding = System.Text.Encoding.UTF8;
|
||||
message.IsBodyHtml = isHtml;
|
||||
message.Subject = subject;
|
||||
message.SubjectEncoding = System.Text.Encoding.UTF8;
|
||||
if (!String.IsNullOrEmpty(bcc))
|
||||
message.Bcc.Add(bcc);
|
||||
message.Priority = priority;
|
||||
|
||||
if (attachments != null)
|
||||
{
|
||||
foreach(Attachment current in attachments)
|
||||
{
|
||||
message.Attachments.Add(current);
|
||||
}
|
||||
}
|
||||
|
||||
// send message
|
||||
try
|
||||
{
|
||||
client.Send(message);
|
||||
|
||||
return 0;
|
||||
}
|
||||
catch (SmtpException ex)
|
||||
{
|
||||
switch (ex.StatusCode)
|
||||
{
|
||||
case SmtpStatusCode.BadCommandSequence: return BusinessErrorCodes.SMTP_BAD_COMMAND_SEQUENCE;
|
||||
case SmtpStatusCode.CannotVerifyUserWillAttemptDelivery: return BusinessErrorCodes.SMTP_CANNOT_VERIFY_USER_WILL_ATTEMPT_DELIVERY;
|
||||
case SmtpStatusCode.ClientNotPermitted: return BusinessErrorCodes.SMTP_CLIENT_NOT_PERMITTED;
|
||||
case SmtpStatusCode.CommandNotImplemented: return BusinessErrorCodes.SMTP_COMMAND_NOT_IMPLEMENTED;
|
||||
case SmtpStatusCode.CommandParameterNotImplemented: return BusinessErrorCodes.SMTP_COMMAND_PARAMETER_NOT_IMPLEMENTED;
|
||||
case SmtpStatusCode.CommandUnrecognized: return BusinessErrorCodes.SMTP_COMMAND_UNRECOGNIZED;
|
||||
case SmtpStatusCode.ExceededStorageAllocation: return BusinessErrorCodes.SMTP_EXCEEDED_STORAGE_ALLOCATION;
|
||||
case SmtpStatusCode.GeneralFailure: return BusinessErrorCodes.SMTP_GENERAL_FAILURE;
|
||||
case SmtpStatusCode.InsufficientStorage: return BusinessErrorCodes.SMTP_INSUFFICIENT_STORAGE;
|
||||
case SmtpStatusCode.LocalErrorInProcessing: return BusinessErrorCodes.SMTP_LOCAL_ERROR_IN_PROCESSING;
|
||||
case SmtpStatusCode.MailboxBusy: return BusinessErrorCodes.SMTP_MAILBOX_BUSY;
|
||||
case SmtpStatusCode.MailboxNameNotAllowed: return BusinessErrorCodes.SMTP_MAILBOX_NAME_NOTALLOWED;
|
||||
case SmtpStatusCode.MailboxUnavailable: return BusinessErrorCodes.SMTP_MAILBOX_UNAVAILABLE;
|
||||
case SmtpStatusCode.MustIssueStartTlsFirst: return BusinessErrorCodes.SMTP_MUST_ISSUE_START_TLS_FIRST;
|
||||
case SmtpStatusCode.ServiceClosingTransmissionChannel: return BusinessErrorCodes.SMTP_SERVICE_CLOSING_TRANSMISSION_CHANNEL;
|
||||
case SmtpStatusCode.ServiceNotAvailable: return BusinessErrorCodes.SMTP_SERVICE_NOT_AVAILABLE;
|
||||
case SmtpStatusCode.SyntaxError: return BusinessErrorCodes.SMTP_SYNTAX_ERROR;
|
||||
case SmtpStatusCode.TransactionFailed: return BusinessErrorCodes.SMTP_TRANSACTION_FAILED;
|
||||
case SmtpStatusCode.UserNotLocalTryAlternatePath: return BusinessErrorCodes.SMTP_USER_NOT_LOCAL_TRY_ALTERNATE_PATH;
|
||||
case SmtpStatusCode.UserNotLocalWillForward: return BusinessErrorCodes.SMTP_USER_NOT_LOCAL_WILL_FORWARD;
|
||||
default: return BusinessErrorCodes.SMTP_UNKNOWN_ERROR;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Clean up.
|
||||
message.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static int SendMessage(string from, string to, string bcc, string subject, string body,
|
||||
MailPriority priority, bool isHtml)
|
||||
{
|
||||
return SendMessage(from, to, bcc, subject, body, priority, isHtml, null);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,659 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Data;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using WebsitePanel.Providers;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for ObjectUtils.
|
||||
/// </summary>
|
||||
public class ObjectUtils
|
||||
{
|
||||
public static DT ConvertObject<ST, DT>(ST so)
|
||||
{
|
||||
Dictionary<string, PropertyInfo> sProps = GetTypePropertiesHash(typeof(ST));
|
||||
Dictionary<string, PropertyInfo> dProps = GetTypePropertiesHash(typeof(DT));
|
||||
|
||||
DT dobj = (DT)Activator.CreateInstance(typeof(DT));
|
||||
|
||||
// copy properties
|
||||
foreach (string propName in sProps.Keys)
|
||||
{
|
||||
if (dProps.ContainsKey(propName) && sProps[propName].Name != "Item")
|
||||
{
|
||||
if (sProps[propName].CanRead)
|
||||
{
|
||||
object val = sProps[propName].GetValue(so, null);
|
||||
if (dProps[propName] != null)
|
||||
{
|
||||
if (val != null && dProps[propName].CanWrite)
|
||||
{
|
||||
dProps[propName].SetValue(dobj, val, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return dobj;
|
||||
}
|
||||
|
||||
private static Hashtable typeProperties = new Hashtable();
|
||||
|
||||
public static Hashtable GetObjectProperties(object obj, bool persistentOnly)
|
||||
{
|
||||
Hashtable hash = new Hashtable();
|
||||
|
||||
Type type = obj.GetType();
|
||||
PropertyInfo[] props = type.GetProperties(BindingFlags.Instance
|
||||
| BindingFlags.Public);
|
||||
foreach (PropertyInfo prop in props)
|
||||
{
|
||||
// check for persistent attribute
|
||||
object[] attrs = prop.GetCustomAttributes(typeof(PersistentAttribute), false);
|
||||
if (!persistentOnly || (persistentOnly && attrs.Length > 0))
|
||||
{
|
||||
object val = prop.GetValue(obj, null);
|
||||
string s = "";
|
||||
if (val != null)
|
||||
{
|
||||
if (prop.PropertyType == typeof(string[]))
|
||||
s = String.Join(";", (string[])val);
|
||||
else if (prop.PropertyType == typeof(int[]))
|
||||
{
|
||||
int[] ivals = (int[])val;
|
||||
string[] svals = new string[ivals.Length];
|
||||
for (int i = 0; i < svals.Length; i++)
|
||||
svals[i] = ivals[i].ToString();
|
||||
s = String.Join(";", svals);
|
||||
}
|
||||
else
|
||||
s = val.ToString();
|
||||
}
|
||||
|
||||
// add property to hash
|
||||
hash.Add(prop.Name, s);
|
||||
}
|
||||
}
|
||||
|
||||
return hash;
|
||||
}
|
||||
|
||||
public static void FillCollectionFromDataSet<T>(List<T> list, DataSet ds)
|
||||
{
|
||||
if(ds.Tables.Count == 0)
|
||||
return;
|
||||
|
||||
FillCollectionFromDataView<T>(list, ds.Tables[0].DefaultView);
|
||||
}
|
||||
|
||||
public static void FillCollectionFromDataView<T>(List<T> list, DataView dv)
|
||||
{
|
||||
Type type = typeof(T);
|
||||
|
||||
PropertyInfo[] props = GetTypeProperties(type);
|
||||
|
||||
foreach(DataRowView dr in dv)
|
||||
{
|
||||
// create an instance
|
||||
T obj = (T)Activator.CreateInstance(type);
|
||||
list.Add(obj);
|
||||
|
||||
// fill properties
|
||||
for(int i = 0; i < props.Length; i++)
|
||||
{
|
||||
string propName = props[i].Name;
|
||||
if(dv.Table.Columns[propName] == null)
|
||||
continue;
|
||||
|
||||
object propVal = dr[propName];
|
||||
if(propVal == DBNull.Value)
|
||||
props[i].SetValue(obj, GetNull(props[i].PropertyType), null);
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
// try implicit type conversion
|
||||
props[i].SetValue(obj, propVal, null);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// convert to string and then set property value
|
||||
try
|
||||
{
|
||||
string strVal = propVal.ToString();
|
||||
props[i].SetValue(obj, Cast(strVal, props[i].PropertyType), null);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// skip property init
|
||||
}
|
||||
}
|
||||
}
|
||||
} // for properties
|
||||
} // for rows
|
||||
}
|
||||
|
||||
public static List<T> CreateListFromDataReader<T>(IDataReader reader)
|
||||
{
|
||||
List<T> list = new List<T>();
|
||||
FillCollectionFromDataReader<T>(list, reader);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<T> CreateListFromDataSet<T>(DataSet ds)
|
||||
{
|
||||
List<T> list = new List<T>();
|
||||
FillCollectionFromDataSet<T>(list, ds);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static void FillCollectionFromDataReader<T>(List<T> list, IDataReader reader)
|
||||
{
|
||||
Type type = typeof(T);
|
||||
|
||||
try
|
||||
{
|
||||
// get type properties
|
||||
PropertyInfo[] props = GetTypeProperties(type);
|
||||
|
||||
// iterate through reader
|
||||
while(reader.Read())
|
||||
{
|
||||
T obj = (T)Activator.CreateInstance(type);
|
||||
list.Add(obj);
|
||||
|
||||
// set properties
|
||||
for(int i = 0; i < props.Length; i++)
|
||||
{
|
||||
string propName = props[i].Name;
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
object propVal = reader[propName];
|
||||
if(propVal == DBNull.Value)
|
||||
props[i].SetValue(obj, GetNull(props[i].PropertyType), null);
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
// try implicit type conversion
|
||||
props[i].SetValue(obj, propVal, null);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// convert to string and then set property value
|
||||
try
|
||||
{
|
||||
string strVal = propVal.ToString();
|
||||
props[i].SetValue(obj, Cast(strVal, props[i].PropertyType), null);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// skip property init
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch{} // just skip
|
||||
} // for properties
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
reader.Close();
|
||||
}
|
||||
}
|
||||
|
||||
public static T FillObjectFromDataView<T>(DataView dv)
|
||||
{
|
||||
Type type = typeof(T);
|
||||
T obj = default(T);
|
||||
|
||||
// get type properties
|
||||
PropertyInfo[] props = GetTypeProperties(type);
|
||||
|
||||
// iterate through reader
|
||||
foreach(DataRowView dr in dv)
|
||||
{
|
||||
obj = (T)Activator.CreateInstance(type);
|
||||
|
||||
// set properties
|
||||
for(int i = 0; i < props.Length; i++)
|
||||
{
|
||||
string propName = props[i].Name;
|
||||
|
||||
try
|
||||
{
|
||||
// verify if there is such a column
|
||||
if (!dr.Row.Table.Columns.Contains(propName.ToLower()))
|
||||
{
|
||||
// if not, we move to another property
|
||||
// because this one we cannot set
|
||||
continue;
|
||||
}
|
||||
|
||||
object propVal = dr[propName];
|
||||
if(propVal == DBNull.Value)
|
||||
props[i].SetValue(obj, GetNull(props[i].PropertyType), null);
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
string strVal = propVal.ToString();
|
||||
|
||||
//convert to DateTime
|
||||
if (props[i].PropertyType.UnderlyingSystemType.FullName == typeof(DateTime).FullName)
|
||||
{
|
||||
DateTime date = DateTime.MinValue;
|
||||
if (DateTime.TryParse(strVal, out date))
|
||||
{
|
||||
props[i].SetValue(obj, date, null);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//Convert generic
|
||||
props[i].SetValue(obj, Cast(strVal, props[i].PropertyType), null);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// skip property init
|
||||
}
|
||||
}
|
||||
}
|
||||
catch{} // just skip
|
||||
} // for properties
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
public static T FillObjectFromDataReader<T>(IDataReader reader)
|
||||
{
|
||||
Type type = typeof(T);
|
||||
|
||||
T obj = default(T);
|
||||
|
||||
try
|
||||
{
|
||||
// get type properties
|
||||
PropertyInfo[] props = GetTypeProperties(type);
|
||||
|
||||
// iterate through reader
|
||||
while(reader.Read())
|
||||
{
|
||||
obj = (T)Activator.CreateInstance(type);
|
||||
|
||||
// set properties
|
||||
for(int i = 0; i < props.Length; i++)
|
||||
{
|
||||
string propName = props[i].Name;
|
||||
|
||||
try
|
||||
{
|
||||
if (!IsColumnExists(propName, reader.GetSchemaTable()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
object propVal = reader[propName];
|
||||
|
||||
if(propVal == DBNull.Value)
|
||||
props[i].SetValue(obj, GetNull(props[i].PropertyType), null);
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
//try string first
|
||||
if (props[i].PropertyType.UnderlyingSystemType.FullName == typeof(String).FullName)
|
||||
{
|
||||
props[i].SetValue(obj, propVal.ToString(), null);
|
||||
}
|
||||
else
|
||||
{
|
||||
// then, try implicit type conversion
|
||||
props[i].SetValue(obj, propVal, null);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// convert to string and then set property value
|
||||
try
|
||||
{
|
||||
string strVal = propVal.ToString();
|
||||
props[i].SetValue(obj, Cast(strVal, props[i].PropertyType), null);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// skip property init
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch{} // just skip
|
||||
} // for properties
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
reader.Close();
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
private static Hashtable propertiesCache = new Hashtable();
|
||||
|
||||
public static object CreateObjectFromDataview(Type type, DataView dv,
|
||||
string nameColumn, string valueColumn, bool persistentOnly)
|
||||
{
|
||||
// create hash of properties from datareader
|
||||
Hashtable propValues = new Hashtable();
|
||||
foreach (DataRowView dr in dv)
|
||||
{
|
||||
if (propValues[dr[nameColumn]] == null)
|
||||
propValues.Add(dr[nameColumn], dr[valueColumn]);
|
||||
}
|
||||
|
||||
return CreateObjectFromHash(type, propValues, persistentOnly);
|
||||
}
|
||||
|
||||
public static object CreateObjectFromDataReader(Type type, IDataReader reader,
|
||||
string nameColumn, string valueColumn, bool persistentOnly)
|
||||
{
|
||||
// create hash of properties from datareader
|
||||
Hashtable propValues = new Hashtable();
|
||||
while (reader.Read())
|
||||
{
|
||||
if (propValues[reader[nameColumn]] == null)
|
||||
propValues.Add(reader[nameColumn], reader[valueColumn]);
|
||||
}
|
||||
reader.Close();
|
||||
|
||||
return CreateObjectFromHash(type, propValues, persistentOnly);
|
||||
}
|
||||
|
||||
public static object CreateObjectFromHash(Type type, Hashtable propValues, bool persistentOnly)
|
||||
{
|
||||
// create object
|
||||
object obj = Activator.CreateInstance(type);
|
||||
|
||||
CreateObjectFromHash(obj, propValues, persistentOnly);
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
public static void CopyPersistentPropertiesFromSource<T>(T source, T target)
|
||||
where T : ServiceProviderItem
|
||||
{
|
||||
//
|
||||
var typeSource = source.GetType();
|
||||
var typeTarget = target.GetType();
|
||||
// get all property infos
|
||||
Hashtable props = null;
|
||||
if (propertiesCache[typeSource.Name] != null)
|
||||
{
|
||||
// load properties from cache
|
||||
props = (Hashtable)propertiesCache[typeSource.Name];
|
||||
}
|
||||
else
|
||||
{
|
||||
// create properties cache
|
||||
props = new Hashtable();
|
||||
//
|
||||
PropertyInfo[] objProps = typeSource.GetProperties(BindingFlags.Instance
|
||||
//| BindingFlags.DeclaredOnly
|
||||
| BindingFlags.Public);
|
||||
foreach (PropertyInfo prop in objProps)
|
||||
{
|
||||
// check for persistent attribute
|
||||
object[] attrs = prop.GetCustomAttributes(typeof(PersistentAttribute), false);
|
||||
// Persistent only
|
||||
if (attrs.Length > 0)
|
||||
{
|
||||
// add property to hash
|
||||
props.Add(prop.Name, prop);
|
||||
}
|
||||
}
|
||||
// add to cache
|
||||
propertiesCache.Add(typeSource.Name, props);
|
||||
}
|
||||
|
||||
// Copy the data
|
||||
foreach (PropertyInfo propertyInfo in props.Values)
|
||||
{
|
||||
propertyInfo.SetValue(target, propertyInfo.GetValue(source, null), null);
|
||||
}
|
||||
}
|
||||
|
||||
public static void CreateObjectFromHash(object obj, Hashtable propValues, bool persistentOnly)
|
||||
{
|
||||
Type type = obj.GetType();
|
||||
|
||||
// get all property infos
|
||||
Hashtable props = null;
|
||||
if (propertiesCache[type.Name] != null)
|
||||
{
|
||||
// load properties from cache
|
||||
props = (Hashtable)propertiesCache[type.Name];
|
||||
}
|
||||
else
|
||||
{
|
||||
// create properties cache
|
||||
props = new Hashtable();
|
||||
PropertyInfo[] objProps = type.GetProperties(BindingFlags.Instance
|
||||
//| BindingFlags.DeclaredOnly
|
||||
| BindingFlags.Public);
|
||||
foreach (PropertyInfo prop in objProps)
|
||||
{
|
||||
// check for persistent attribute
|
||||
object[] attrs = prop.GetCustomAttributes(typeof(PersistentAttribute), false);
|
||||
if (!persistentOnly || (persistentOnly && attrs.Length > 0))
|
||||
{
|
||||
// add property to hash
|
||||
props.Add(prop.Name, prop);
|
||||
}
|
||||
}
|
||||
|
||||
// add to cache
|
||||
propertiesCache.Add(type.Name, props);
|
||||
}
|
||||
|
||||
// fill properties
|
||||
foreach (string propName in propValues.Keys)
|
||||
{
|
||||
// try to locate specified property
|
||||
if (props[propName] != null)
|
||||
{
|
||||
// set property
|
||||
// we support:
|
||||
// String
|
||||
// Int32
|
||||
// Boolean
|
||||
// Float
|
||||
PropertyInfo prop = (PropertyInfo)props[propName];
|
||||
string val = propValues[propName].ToString();
|
||||
if (prop.PropertyType == typeof(String))
|
||||
prop.SetValue(obj, val, null);
|
||||
else if (prop.PropertyType == typeof(Int32))
|
||||
prop.SetValue(obj, Int32.Parse(val), null);
|
||||
else
|
||||
if (prop.PropertyType == typeof(long))
|
||||
prop.SetValue(obj, long.Parse(val), null);
|
||||
else
|
||||
if (prop.PropertyType == typeof(Boolean))
|
||||
prop.SetValue(obj, Boolean.Parse(val), null);
|
||||
else if (prop.PropertyType == typeof(Single))
|
||||
prop.SetValue(obj, Single.Parse(val), null);
|
||||
else if (prop.PropertyType.IsEnum)
|
||||
prop.SetValue(obj, Enum.Parse(prop.PropertyType, val, true), null);
|
||||
else
|
||||
if (prop.PropertyType == typeof(Guid))
|
||||
prop.SetValue(obj, new Guid(val), null);
|
||||
else
|
||||
if (prop.PropertyType == typeof(string[]))
|
||||
{
|
||||
if (val == "")
|
||||
prop.SetValue(obj, new string[0], null);
|
||||
else
|
||||
prop.SetValue(obj, val.Split(';'), null);
|
||||
}
|
||||
else if (prop.PropertyType == typeof(int[]))
|
||||
{
|
||||
string[] svals = val.Split(';');
|
||||
int[] ivals = new int[svals.Length];
|
||||
|
||||
for (int i = 0; i < svals.Length; i++)
|
||||
ivals[i] = Int32.Parse(svals[i]);
|
||||
|
||||
if (val == "")
|
||||
ivals = new int[0];
|
||||
|
||||
prop.SetValue(obj, ivals, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, PropertyInfo> GetTypePropertiesHash(Type type)
|
||||
{
|
||||
Dictionary<string, PropertyInfo> hash = new Dictionary<string, PropertyInfo>();
|
||||
PropertyInfo[] props = GetTypeProperties(type);
|
||||
foreach (PropertyInfo prop in props)
|
||||
hash.Add(prop.Name, prop);
|
||||
return hash;
|
||||
}
|
||||
|
||||
private static PropertyInfo[] GetTypeProperties(Type type)
|
||||
{
|
||||
string typeName = type.AssemblyQualifiedName;
|
||||
if(typeProperties[typeName] != null)
|
||||
return (PropertyInfo[])typeProperties[typeName];
|
||||
|
||||
PropertyInfo[] props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
|
||||
typeProperties[typeName] = props;
|
||||
return props;
|
||||
}
|
||||
|
||||
public static object GetNull(Type type)
|
||||
{
|
||||
if(type == typeof(string))
|
||||
return null;
|
||||
if(type == typeof(Int32))
|
||||
return 0;
|
||||
if(type == typeof(Int64))
|
||||
return 0;
|
||||
if(type == typeof(Boolean))
|
||||
return false;
|
||||
if(type == typeof(Decimal))
|
||||
return 0M;
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
public static object Cast(string val, Type type)
|
||||
{
|
||||
if(type == typeof(string))
|
||||
return val;
|
||||
if(type == typeof(Int32))
|
||||
return Int32.Parse(val);
|
||||
if(type == typeof(Int64))
|
||||
return Int64.Parse(val);
|
||||
if(type == typeof(Boolean))
|
||||
return Boolean.Parse(val);
|
||||
if(type == typeof(Decimal))
|
||||
return Decimal.Parse(val);
|
||||
if(type == typeof(string[]) && val != null)
|
||||
{
|
||||
return val.Split(';');
|
||||
}
|
||||
if (type.IsEnum)
|
||||
return Enum.Parse(type, val, true);
|
||||
|
||||
if (type == typeof(int[]) && val != null)
|
||||
{
|
||||
string[] sarr = val.Split(';');
|
||||
int[] iarr = new int[sarr.Length];
|
||||
for (int i = 0; i < sarr.Length; i++)
|
||||
iarr[i] = Int32.Parse(sarr[i]);
|
||||
return iarr;
|
||||
}
|
||||
else
|
||||
return val;
|
||||
}
|
||||
|
||||
public static string GetTypeFullName(Type type)
|
||||
{
|
||||
return type.FullName + ", " + type.Assembly.GetName().Name;
|
||||
}
|
||||
|
||||
|
||||
#region Helper Functions
|
||||
|
||||
/// <summary>
|
||||
/// This function is used to determine whether IDataReader contains a Column.
|
||||
/// </summary>
|
||||
/// <param name="columnName">Name of the column.</param>
|
||||
/// <param name="schemaTable">The schema <see cref="DataTable"/> that decribes result-set <see cref="IDataReader"/> contains.</param>
|
||||
/// <returns>True, when required column exists in the <paramref name="schemaTable"/>. Otherwise, false.</returns>
|
||||
/// <remark>
|
||||
/// The followin example shows how to look for the "Role" column in the <see cref="IDataReader"/>.
|
||||
/// <example>
|
||||
/// IDataReader reader = ....
|
||||
/// if (!IsColumnExists("Role", reader.GetSchemaTable())
|
||||
/// {
|
||||
/// continue;
|
||||
/// }
|
||||
///
|
||||
/// object roleValue = reader["Role"];
|
||||
/// </example>
|
||||
/// </remark>
|
||||
static bool IsColumnExists(string columnName, DataTable schemaTable)
|
||||
{
|
||||
foreach (DataRow row in schemaTable.Rows)
|
||||
{
|
||||
if (String.Compare(row[0].ToString(), columnName, StringComparison.OrdinalIgnoreCase) == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,249 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Diagnostics;
|
||||
using System.Security;
|
||||
using System.Security.Principal;
|
||||
using System.Web;
|
||||
using WebsitePanel.Providers.Common;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides security utilities.
|
||||
/// </summary>
|
||||
public class SecurityContext
|
||||
{
|
||||
public const string ROLE_ADMINISTRATOR = "Administrator";
|
||||
public const string ROLE_RESELLER = "Reseller";
|
||||
public const string ROLE_USER = "User";
|
||||
public const string ROLE_PLATFORMCSR = "PlatformCSR";
|
||||
public const string ROLE_PLATFORMHELPDESK = "PlatformHelpdesk";
|
||||
public const string ROLE_RESELLERCSR = "ResellerCSR";
|
||||
public const string ROLE_RESELLERHELPDESK = "ResellerHelpdesk";
|
||||
|
||||
public const string CONTEXT_USER_INFO = "CONTEXT_USER_INFO";
|
||||
|
||||
public static void SetThreadPrincipal(int userId)
|
||||
{
|
||||
UserInfo user = UserController.GetUserInternally(userId);
|
||||
if (user == null)
|
||||
throw new Exception(String.Format("User '{0}' can not be loaded", userId));
|
||||
|
||||
SetThreadPrincipal(user);
|
||||
}
|
||||
|
||||
public static void SetThreadPrincipal(UserInfo user)
|
||||
{
|
||||
// set roles array
|
||||
List<string> roles = new List<string>();
|
||||
roles.Add(SecurityContext.ROLE_USER);
|
||||
|
||||
if (user.Role == UserRole.Reseller || user.Role == UserRole.Administrator ||
|
||||
user.Role == UserRole.PlatformHelpdesk || user.Role == UserRole.ResellerHelpdesk)
|
||||
roles.Add(SecurityContext.ROLE_RESELLERHELPDESK);
|
||||
|
||||
if (user.Role == UserRole.Reseller || user.Role == UserRole.Administrator ||
|
||||
user.Role == UserRole.PlatformCSR || user.Role == UserRole.ResellerCSR)
|
||||
roles.Add(SecurityContext.ROLE_RESELLERCSR);
|
||||
|
||||
if (user.Role == UserRole.Reseller || user.Role == UserRole.Administrator ||
|
||||
user.Role == UserRole.PlatformHelpdesk)
|
||||
roles.Add(SecurityContext.ROLE_PLATFORMHELPDESK);
|
||||
|
||||
if (user.Role == UserRole.Reseller || user.Role == UserRole.Administrator ||
|
||||
user.Role == UserRole.PlatformCSR)
|
||||
roles.Add(SecurityContext.ROLE_PLATFORMCSR);
|
||||
|
||||
if (user.Role == UserRole.Reseller || user.Role == UserRole.Administrator)
|
||||
roles.Add(SecurityContext.ROLE_RESELLER);
|
||||
|
||||
if (user.Role == UserRole.Administrator)
|
||||
roles.Add(SecurityContext.ROLE_ADMINISTRATOR);
|
||||
|
||||
// create a new generic principal/identity and place them to context
|
||||
EnterpriseServerIdentity identity = new EnterpriseServerIdentity(user.UserId.ToString());
|
||||
EnterpriseServerPrincipal principal = new EnterpriseServerPrincipal(identity, roles.ToArray());
|
||||
|
||||
principal.UserId = user.UserId;
|
||||
principal.OwnerId = user.OwnerId;
|
||||
principal.IsPeer = user.IsPeer;
|
||||
principal.IsDemo = user.IsDemo;
|
||||
principal.Status = user.Status;
|
||||
|
||||
Thread.CurrentPrincipal = principal;
|
||||
}
|
||||
|
||||
public static void SetThreadSupervisorPrincipal()
|
||||
{
|
||||
UserInfo user = new UserInfo();
|
||||
user.UserId = -1;
|
||||
user.OwnerId = 0;
|
||||
user.IsPeer = false;
|
||||
user.IsDemo = false;
|
||||
user.Status = UserStatus.Active;
|
||||
user.Role = UserRole.Administrator;
|
||||
|
||||
SetThreadPrincipal(user);
|
||||
}
|
||||
|
||||
public static EnterpriseServerPrincipal User
|
||||
{
|
||||
get
|
||||
{
|
||||
EnterpriseServerPrincipal principal = Thread.CurrentPrincipal as EnterpriseServerPrincipal;
|
||||
if(principal != null)
|
||||
return principal;
|
||||
|
||||
// Username Token Manager was unable to set principal
|
||||
// or authentication is disabled
|
||||
// create supervisor principal
|
||||
SetThreadSupervisorPrincipal();
|
||||
|
||||
return (EnterpriseServerPrincipal)Thread.CurrentPrincipal;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool CheckAccount(ResultObject res, DemandAccount demand)
|
||||
{
|
||||
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
|
||||
if (accountCheck < 0)
|
||||
{
|
||||
res.ErrorCodes.Add(BusinessErrorCodes.ToText(accountCheck));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int CheckAccount(DemandAccount demand)
|
||||
{
|
||||
if ((demand & DemandAccount.NotDemo) == DemandAccount.NotDemo)
|
||||
{
|
||||
// should make a check if the account is not in demo mode
|
||||
if (User.IsDemo)
|
||||
return BusinessErrorCodes.ERROR_USER_ACCOUNT_DEMO;
|
||||
}
|
||||
|
||||
if ((demand & DemandAccount.IsActive) == DemandAccount.IsActive)
|
||||
{
|
||||
// check is the account is active
|
||||
if (User.Status == UserStatus.Pending)
|
||||
return BusinessErrorCodes.ERROR_USER_ACCOUNT_PENDING;
|
||||
else if (User.Status == UserStatus.Suspended)
|
||||
return BusinessErrorCodes.ERROR_USER_ACCOUNT_SUSPENDED;
|
||||
else if (User.Status == UserStatus.Cancelled)
|
||||
return BusinessErrorCodes.ERROR_USER_ACCOUNT_CANCELLED;
|
||||
}
|
||||
|
||||
if ((demand & DemandAccount.IsAdmin) == DemandAccount.IsAdmin)
|
||||
{
|
||||
// should make a check if the account has Admin role
|
||||
if (!User.IsInRole(ROLE_ADMINISTRATOR))
|
||||
return BusinessErrorCodes.ERROR_USER_ACCOUNT_SHOULD_BE_ADMINISTRATOR;
|
||||
}
|
||||
|
||||
if ((demand & DemandAccount.IsReseller) == DemandAccount.IsReseller)
|
||||
{
|
||||
// should make a check if the account has Admin role
|
||||
if (!User.IsInRole(ROLE_RESELLER))
|
||||
return BusinessErrorCodes.ERROR_USER_ACCOUNT_NOT_ENOUGH_PERMISSIONS;
|
||||
}
|
||||
|
||||
if ((demand & DemandAccount.IsPlatformCSR) == DemandAccount.IsPlatformCSR)
|
||||
{
|
||||
// should make a check if the account has Admin role
|
||||
if (!User.IsInRole(ROLE_PLATFORMCSR))
|
||||
return BusinessErrorCodes.ERROR_USER_ACCOUNT_NOT_ENOUGH_PERMISSIONS;
|
||||
}
|
||||
|
||||
if ((demand & DemandAccount.IsPlatformHelpdesk) == DemandAccount.IsPlatformHelpdesk)
|
||||
{
|
||||
// should make a check if the account has Admin role
|
||||
if (!User.IsInRole(ROLE_PLATFORMHELPDESK))
|
||||
return BusinessErrorCodes.ERROR_USER_ACCOUNT_NOT_ENOUGH_PERMISSIONS;
|
||||
}
|
||||
|
||||
|
||||
if ((demand & DemandAccount.IsResellerHelpdesk) == DemandAccount.IsResellerHelpdesk)
|
||||
{
|
||||
// should make a check if the account has Admin role
|
||||
if (!User.IsInRole(ROLE_RESELLERHELPDESK))
|
||||
return BusinessErrorCodes.ERROR_USER_ACCOUNT_NOT_ENOUGH_PERMISSIONS;
|
||||
}
|
||||
|
||||
|
||||
if ((demand & DemandAccount.IsResellerCSR) == DemandAccount.IsResellerCSR)
|
||||
{
|
||||
// should make a check if the account has Admin role
|
||||
if (!User.IsInRole(ROLE_RESELLERCSR))
|
||||
return BusinessErrorCodes.ERROR_USER_ACCOUNT_NOT_ENOUGH_PERMISSIONS;
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static bool CheckPackage(ResultObject res, int packageId, DemandPackage demand)
|
||||
{
|
||||
int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
|
||||
if (packageCheck < 0)
|
||||
{
|
||||
res.ErrorCodes.Add(BusinessErrorCodes.ToText(packageCheck));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int CheckPackage(int packageId, DemandPackage demand)
|
||||
{
|
||||
// load package
|
||||
PackageInfo package = PackageController.GetPackage(packageId);
|
||||
if (package == null)
|
||||
return BusinessErrorCodes.ERROR_PACKAGE_NOT_FOUND;
|
||||
|
||||
return CheckPackage(package, demand);
|
||||
}
|
||||
|
||||
public static int CheckPackage(PackageInfo package, DemandPackage demand)
|
||||
{
|
||||
if ((demand & DemandPackage.IsActive) == DemandPackage.IsActive)
|
||||
{
|
||||
// should make a check if the package is active
|
||||
if (package.StatusId == (int)PackageStatus.Cancelled)
|
||||
return BusinessErrorCodes.ERROR_PACKAGE_CANCELLED;
|
||||
else if (package.StatusId == (int)PackageStatus.Suspended)
|
||||
return BusinessErrorCodes.ERROR_PACKAGE_SUSPENDED;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,119 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.DirectoryServices;
|
||||
using System.Collections;
|
||||
using System.Collections.Specialized;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
using Microsoft.Web.Services3;
|
||||
using WebsitePanel.Server.Client;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
public class ServiceProviderProxy
|
||||
{
|
||||
public static WebServicesClientProtocol Init(WebServicesClientProtocol proxy, int serviceId)
|
||||
{
|
||||
ServerProxyConfigurator cnfg = new ServerProxyConfigurator();
|
||||
|
||||
// get service
|
||||
ServiceInfo service = ServerController.GetServiceInfo(serviceId);
|
||||
|
||||
if (service == null)
|
||||
throw new Exception(String.Format("Service with ID {0} was not found", serviceId));
|
||||
|
||||
// set service settings
|
||||
StringDictionary serviceSettings = ServerController.GetServiceSettings(serviceId);
|
||||
foreach (string key in serviceSettings.Keys)
|
||||
cnfg.ProviderSettings.Settings[key] = serviceSettings[key];
|
||||
|
||||
// get provider
|
||||
ProviderInfo provider = ServerController.GetProvider(service.ProviderId);
|
||||
cnfg.ProviderSettings.ProviderGroupID = provider.GroupId;
|
||||
cnfg.ProviderSettings.ProviderCode = provider.ProviderName;
|
||||
cnfg.ProviderSettings.ProviderName = provider.DisplayName;
|
||||
cnfg.ProviderSettings.ProviderType = provider.ProviderType;
|
||||
|
||||
// init service on the server level
|
||||
return ServerInit(proxy, cnfg, service.ServerId);
|
||||
}
|
||||
|
||||
public static WebServicesClientProtocol ServerInit(WebServicesClientProtocol proxy, ServerProxyConfigurator cnfg, int serverId)
|
||||
{
|
||||
// get server info
|
||||
ServerInfo server = ServerController.GetServerByIdInternal(serverId);
|
||||
|
||||
if (server == null)
|
||||
throw new Exception(String.Format("Server with ID {0} was not found", serverId));
|
||||
|
||||
// set AD integration settings
|
||||
cnfg.ServerSettings.ADEnabled = server.ADEnabled;
|
||||
cnfg.ServerSettings.ADAuthenticationType = AuthenticationTypes.Secure;
|
||||
try
|
||||
{
|
||||
cnfg.ServerSettings.ADAuthenticationType = (AuthenticationTypes)Enum.Parse(typeof(AuthenticationTypes), server.ADAuthenticationType, true);
|
||||
}
|
||||
catch { /* ignore */ }
|
||||
cnfg.ServerSettings.ADRootDomain = server.ADRootDomain;
|
||||
cnfg.ServerSettings.ADUsername = server.ADUsername;
|
||||
cnfg.ServerSettings.ADPassword = server.ADPassword;
|
||||
|
||||
// set timeout
|
||||
cnfg.Timeout = ConfigSettings.ServerRequestTimeout;
|
||||
|
||||
return ServerInit(proxy, cnfg, server.ServerUrl, server.Password);
|
||||
}
|
||||
|
||||
private static WebServicesClientProtocol ServerInit(WebServicesClientProtocol proxy,
|
||||
ServerProxyConfigurator cnfg, string serverUrl, string serverPassword)
|
||||
{
|
||||
// set URL & password
|
||||
cnfg.ServerUrl = serverUrl;
|
||||
cnfg.ServerPassword = serverPassword;
|
||||
|
||||
// configure proxy!
|
||||
cnfg.Configure(proxy);
|
||||
|
||||
return proxy;
|
||||
}
|
||||
|
||||
public static WebServicesClientProtocol ServerInit(WebServicesClientProtocol proxy,
|
||||
string serverUrl, string serverPassword)
|
||||
{
|
||||
return ServerInit(proxy, new ServerProxyConfigurator(), serverUrl, serverPassword);
|
||||
}
|
||||
|
||||
public static WebServicesClientProtocol ServerInit(WebServicesClientProtocol proxy, int serverId)
|
||||
{
|
||||
return ServerInit(proxy, new ServerProxyConfigurator(), serverId);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,81 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Web;
|
||||
using System.Xml;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Principal;
|
||||
using System.Security.Permissions;
|
||||
|
||||
using Microsoft.Web.Services3.Security;
|
||||
using Microsoft.Web.Services3.Security.Tokens;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for UsernameTokenManager.
|
||||
/// </summary>
|
||||
public class ServiceUsernameTokenManager : UsernameTokenManager
|
||||
{
|
||||
/// <summary>
|
||||
/// Constructs an instance of this security token manager.
|
||||
/// </summary>
|
||||
public ServiceUsernameTokenManager()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs an instance of this security token manager.
|
||||
/// </summary>
|
||||
/// <param name="nodes">An XmlNodeList containing XML elements from a configuration file.</param>
|
||||
public ServiceUsernameTokenManager(XmlNodeList nodes)
|
||||
: base(nodes)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the password or password equivalent for the username provided.
|
||||
/// </summary>
|
||||
/// <param name="token">The username token</param>
|
||||
/// <returns>The password (or password equivalent) for the username</returns>
|
||||
protected override string AuthenticateToken(UsernameToken token)
|
||||
{
|
||||
// try to load user account
|
||||
UserInfo user = UserController.GetUserInternally(token.Username);
|
||||
if (user == null)
|
||||
return null;
|
||||
|
||||
SecurityContext.SetThreadPrincipal(user);
|
||||
|
||||
return user.Password;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,407 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Configuration;
|
||||
using System.Xml;
|
||||
using System.Diagnostics;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Web;
|
||||
|
||||
using WSE = Microsoft.Web.Services3.Security;
|
||||
using Microsoft.Web.Services3;
|
||||
using Microsoft.Web.Services3.Design;
|
||||
using Microsoft.Web.Services3.Security;
|
||||
using Microsoft.Web.Services3.Security.Tokens;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
public class UsernameAssertion : SecurityPolicyAssertion
|
||||
{
|
||||
#region Public properties
|
||||
private bool signRequest = true;
|
||||
public bool SignRequest
|
||||
{
|
||||
get { return signRequest; }
|
||||
set { signRequest = value; }
|
||||
}
|
||||
|
||||
private bool encryptRequest = true;
|
||||
public bool EncryptRequest
|
||||
{
|
||||
get { return encryptRequest; }
|
||||
set { encryptRequest = value; }
|
||||
}
|
||||
|
||||
private int serverId = 0;
|
||||
public int ServerId
|
||||
{
|
||||
get { return serverId; }
|
||||
set { serverId = value; }
|
||||
}
|
||||
|
||||
private string password;
|
||||
public string Password
|
||||
{
|
||||
get { return password; }
|
||||
set { password = value; }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public UsernameAssertion()
|
||||
{
|
||||
}
|
||||
|
||||
public UsernameAssertion(int serverId, string password)
|
||||
{
|
||||
this.serverId = serverId;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public override SoapFilter CreateServiceInputFilter(FilterCreationContext context)
|
||||
{
|
||||
return new ServiceInputFilter(this, context);
|
||||
}
|
||||
|
||||
public override SoapFilter CreateServiceOutputFilter(FilterCreationContext context)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public override SoapFilter CreateClientInputFilter(FilterCreationContext context)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public override SoapFilter CreateClientOutputFilter(FilterCreationContext context)
|
||||
{
|
||||
return new ClientOutputFilter(this, context);
|
||||
}
|
||||
|
||||
public override void ReadXml(XmlReader reader, IDictionary<string, Type> extensions)
|
||||
{
|
||||
if (reader == null)
|
||||
throw new ArgumentNullException("reader");
|
||||
if (extensions == null)
|
||||
throw new ArgumentNullException("extensions");
|
||||
|
||||
// find the current extension
|
||||
string tagName = null;
|
||||
foreach (string extName in extensions.Keys)
|
||||
{
|
||||
if (extensions[extName] == typeof(UsernameAssertion))
|
||||
{
|
||||
tagName = extName;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// read the first element (maybe empty)
|
||||
reader.ReadStartElement(tagName);
|
||||
}
|
||||
|
||||
public override void WriteXml(XmlWriter writer)
|
||||
{
|
||||
// Typically this is not needed for custom policies
|
||||
}
|
||||
|
||||
#region ServiceInputFilter
|
||||
public class ServiceInputFilter : ReceiveSecurityFilter
|
||||
{
|
||||
UsernameAssertion parentAssertion;
|
||||
FilterCreationContext filterContext;
|
||||
|
||||
public ServiceInputFilter(UsernameAssertion parentAssertion, FilterCreationContext filterContext)
|
||||
: base(parentAssertion.ServiceActor, false, parentAssertion.ClientActor)
|
||||
{
|
||||
this.parentAssertion = parentAssertion;
|
||||
this.filterContext = filterContext;
|
||||
}
|
||||
|
||||
public override void ValidateMessageSecurity(SoapEnvelope envelope, WSE.Security security)
|
||||
{
|
||||
if (security != null)
|
||||
ProcessWSERequest(envelope, security);
|
||||
//else if (envelope.Header != null)
|
||||
// ProcessSoapRequest(envelope);
|
||||
else// if (HttpContext.Current.Request.Headers["Authorization"] != null)
|
||||
ProcessBasicAuthRequest();
|
||||
}
|
||||
|
||||
private void ProcessBasicAuthRequest()
|
||||
{
|
||||
string authStr = HttpContext.Current.Request.Headers["Authorization"];
|
||||
|
||||
if (authStr == null || authStr.Length == 0)
|
||||
{
|
||||
// No credentials; anonymous request
|
||||
DenyAccess();
|
||||
return;
|
||||
}
|
||||
|
||||
authStr = authStr.Trim();
|
||||
if (authStr.IndexOf("Basic", 0) != 0)
|
||||
{
|
||||
// Don't understand this header...we'll pass it along and
|
||||
// assume someone else will handle it
|
||||
DenyAccess();
|
||||
return;
|
||||
}
|
||||
|
||||
string encodedCredentials = authStr.Substring(6);
|
||||
|
||||
byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
|
||||
string s = new ASCIIEncoding().GetString(decodedBytes);
|
||||
|
||||
string[] userPass = s.Split(new char[] { ':' });
|
||||
string username = userPass[0];
|
||||
string password = userPass[1];
|
||||
|
||||
UserInfo user = UserController.GetUserByUsernamePassword(
|
||||
username, password, System.Web.HttpContext.Current.Request.UserHostAddress);
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
// Invalid credentials; deny access
|
||||
DenyAccess();
|
||||
return;
|
||||
|
||||
//throw new Exception("Wrong BASIC credentials have been supplied");
|
||||
}
|
||||
|
||||
SecurityContext.SetThreadPrincipal(user);
|
||||
}
|
||||
|
||||
private void DenyAccess()
|
||||
{
|
||||
HttpResponse response = HttpContext.Current.Response;
|
||||
response.Clear();
|
||||
response.StatusCode = 401;
|
||||
response.StatusDescription = "Access Denied";
|
||||
response.Write("401 Access Denied");
|
||||
string realm = "WebsitePanel Enterprise Server";
|
||||
string val = String.Format("Basic Realm=\"{0}\"", realm);
|
||||
response.AppendHeader("WWW-Authenticate", val);
|
||||
response.End();
|
||||
}
|
||||
|
||||
private void ProcessSoapRequest(SoapEnvelope envelope)
|
||||
{
|
||||
XmlNode authNode = envelope.Header.SelectSingleNode("Authentication");
|
||||
|
||||
if (authNode == null)
|
||||
throw new Exception("Couldn't find authentication token specified");
|
||||
|
||||
XmlNode userNode = authNode.SelectSingleNode("Username");
|
||||
XmlNode passwordNode = authNode.SelectSingleNode("Password");
|
||||
|
||||
if (userNode == null || passwordNode == null)
|
||||
throw new Exception("Authentication token is invalid or broken");
|
||||
|
||||
UserInfo user = UserController.GetUserByUsernamePassword(
|
||||
userNode.InnerText,
|
||||
passwordNode.InnerText,
|
||||
System.Web.HttpContext.Current.Request.UserHostAddress
|
||||
);
|
||||
|
||||
if (user == null)
|
||||
throw new Exception("Authentication token is invalid or broken");
|
||||
|
||||
SecurityContext.SetThreadPrincipal(user);
|
||||
}
|
||||
|
||||
private void ProcessWSERequest(SoapEnvelope envelope, WSE.Security security)
|
||||
{
|
||||
// by default we consider that SOAP messages is not signed
|
||||
bool IsSigned = false;
|
||||
|
||||
// if security element is null
|
||||
// the call is made not from WSE-enabled client
|
||||
if (security != null)
|
||||
{
|
||||
foreach (ISecurityElement element in security.Elements)
|
||||
{
|
||||
if (element is MessageSignature)
|
||||
{
|
||||
// The given context contains a Signature element.
|
||||
MessageSignature sign = element as MessageSignature;
|
||||
|
||||
if (CheckSignature(envelope, security, sign))
|
||||
{
|
||||
// The SOAP message is signed.
|
||||
if (sign.SigningToken is UsernameToken)
|
||||
{
|
||||
UsernameToken token = sign.SigningToken as UsernameToken;
|
||||
|
||||
// The SOAP message is signed
|
||||
// with a UsernameToken.
|
||||
IsSigned = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// throw an exception if the message did not pass all the tests
|
||||
if (!IsSigned)
|
||||
throw new SecurityFault("SOAP response should be signed.");
|
||||
|
||||
// check encryption
|
||||
bool IsEncrypted = false;
|
||||
foreach (ISecurityElement element in security.Elements)
|
||||
{
|
||||
if (element is EncryptedData)
|
||||
{
|
||||
EncryptedData encryptedData = element as EncryptedData;
|
||||
System.Xml.XmlElement targetElement = encryptedData.TargetElement;
|
||||
|
||||
if (SoapHelper.IsBodyElement(targetElement))
|
||||
{
|
||||
// The given SOAP message has the Body element Encrypted.
|
||||
IsEncrypted = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!IsEncrypted)
|
||||
throw new SecurityFault("SOAP response should be encrypted.");
|
||||
}
|
||||
|
||||
private bool CheckSignature(SoapEnvelope envelope, WSE.Security security, MessageSignature signature)
|
||||
{
|
||||
//
|
||||
// Now verify which parts of the message were actually signed.
|
||||
//
|
||||
SignatureOptions actualOptions = signature.SignatureOptions;
|
||||
SignatureOptions expectedOptions = SignatureOptions.IncludeSoapBody;
|
||||
|
||||
if (security != null && security.Timestamp != null)
|
||||
expectedOptions |= SignatureOptions.IncludeTimestamp;
|
||||
|
||||
//
|
||||
// The <Action> and <To> are required addressing elements.
|
||||
//
|
||||
expectedOptions |= SignatureOptions.IncludeAction;
|
||||
expectedOptions |= SignatureOptions.IncludeTo;
|
||||
|
||||
if (envelope.Context.Addressing.FaultTo != null && envelope.Context.Addressing.FaultTo.TargetElement != null)
|
||||
expectedOptions |= SignatureOptions.IncludeFaultTo;
|
||||
|
||||
if (envelope.Context.Addressing.From != null && envelope.Context.Addressing.From.TargetElement != null)
|
||||
expectedOptions |= SignatureOptions.IncludeFrom;
|
||||
|
||||
if (envelope.Context.Addressing.MessageID != null && envelope.Context.Addressing.MessageID.TargetElement != null)
|
||||
expectedOptions |= SignatureOptions.IncludeMessageId;
|
||||
|
||||
if (envelope.Context.Addressing.RelatesTo != null && envelope.Context.Addressing.RelatesTo.TargetElement != null)
|
||||
expectedOptions |= SignatureOptions.IncludeRelatesTo;
|
||||
|
||||
if (envelope.Context.Addressing.ReplyTo != null && envelope.Context.Addressing.ReplyTo.TargetElement != null)
|
||||
expectedOptions |= SignatureOptions.IncludeReplyTo;
|
||||
//
|
||||
// Check if the all the expected options are the present.
|
||||
//
|
||||
return ((expectedOptions & actualOptions) == expectedOptions);
|
||||
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ClientOutputFilter
|
||||
public class ClientOutputFilter : SendSecurityFilter
|
||||
{
|
||||
UsernameAssertion parentAssertion;
|
||||
FilterCreationContext filterContext;
|
||||
|
||||
public ClientOutputFilter(UsernameAssertion parentAssertion, FilterCreationContext filterContext)
|
||||
: base(parentAssertion.ServiceActor, false, parentAssertion.ClientActor)
|
||||
{
|
||||
this.parentAssertion = parentAssertion;
|
||||
this.filterContext = filterContext;
|
||||
}
|
||||
|
||||
public override void SecureMessage(SoapEnvelope envelope, WSE.Security security)
|
||||
{
|
||||
// get server password from database
|
||||
string password = parentAssertion.Password;
|
||||
|
||||
if (password == null)
|
||||
return;
|
||||
|
||||
// hash password
|
||||
password = CryptoUtils.SHA1(password);
|
||||
|
||||
// create username token
|
||||
UsernameToken userToken = new UsernameToken(parentAssertion.ServerId.ToString(), password,
|
||||
PasswordOption.SendNone);
|
||||
|
||||
if (parentAssertion.signRequest || parentAssertion.encryptRequest)
|
||||
{
|
||||
// Add the token to the SOAP header.
|
||||
security.Tokens.Add(userToken);
|
||||
}
|
||||
|
||||
if (parentAssertion.signRequest)
|
||||
{
|
||||
// Sign the SOAP message by using the UsernameToken.
|
||||
MessageSignature sig = new MessageSignature(userToken);
|
||||
security.Elements.Add(sig);
|
||||
}
|
||||
|
||||
if (parentAssertion.encryptRequest)
|
||||
{
|
||||
// we don't return any custom SOAP headers
|
||||
// so, just encrypt a message Body
|
||||
EncryptedData data = new EncryptedData(userToken);
|
||||
|
||||
// encrypt custom headers
|
||||
for (int index = 0; index < envelope.Header.ChildNodes.Count; index++)
|
||||
{
|
||||
XmlElement child = envelope.Header.ChildNodes[index] as XmlElement;
|
||||
|
||||
// find all SecureSoapHeader headers marked with a special attribute
|
||||
if (child != null && child.NamespaceURI == "http://com/websitepanel/server/")
|
||||
{
|
||||
// create ID attribute for referencing purposes
|
||||
string id = Guid.NewGuid().ToString();
|
||||
child.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", id);
|
||||
|
||||
// Create an encryption reference for the custom SOAP header.
|
||||
data.AddReference(new EncryptionReference("#" + id));
|
||||
}
|
||||
}
|
||||
|
||||
security.Elements.Add(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,173 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Data;
|
||||
using System.Collections;
|
||||
using System.Web;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace WebsitePanel.EnterpriseServer
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for Utils.
|
||||
/// </summary>
|
||||
public class Utils
|
||||
{
|
||||
public static int ParseInt(string val, int defaultValue)
|
||||
{
|
||||
int result = defaultValue;
|
||||
try { result = Int32.Parse(val); }
|
||||
catch { /* do nothing */ }
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public static bool ParseBool(object val, bool defaultValue)
|
||||
{
|
||||
bool result = defaultValue;
|
||||
try { result = Boolean.Parse(val.ToString()); }
|
||||
catch { /* do nothing */ }
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public static bool ParseBool(string val, bool defaultValue)
|
||||
{
|
||||
bool result = defaultValue;
|
||||
try { result = Boolean.Parse(val); }
|
||||
catch { /* do nothing */ }
|
||||
return result;
|
||||
}
|
||||
|
||||
public static decimal ParseDecimal(string val, decimal defaultValue)
|
||||
{
|
||||
decimal result = defaultValue;
|
||||
try { result = Decimal.Parse(val); }
|
||||
catch { /* do nothing */ }
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string[] ParseDelimitedString(string str, params char[] delimiter)
|
||||
{
|
||||
if (String.IsNullOrEmpty(str))
|
||||
return new string[] { };
|
||||
|
||||
string[] parts = str.Split(delimiter);
|
||||
ArrayList list = new ArrayList();
|
||||
foreach (string part in parts)
|
||||
if (part.Trim() != "" && !list.Contains(part.Trim()))
|
||||
list.Add(part);
|
||||
return (string[])list.ToArray(typeof(string));
|
||||
}
|
||||
|
||||
|
||||
public static string ReplaceStringVariable(string str, string variable, string value)
|
||||
{
|
||||
return ReplaceStringVariable(str, variable, value, false);
|
||||
}
|
||||
|
||||
public static string ReplaceStringVariable(string str, string variable, string value, bool allowEmptyValue)
|
||||
{
|
||||
if (allowEmptyValue)
|
||||
{
|
||||
if (String.IsNullOrEmpty(str)) return str;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (String.IsNullOrEmpty(str) || String.IsNullOrEmpty(value))
|
||||
return str;
|
||||
}
|
||||
|
||||
Regex re = new Regex("\\[" + variable + "\\]+", RegexOptions.IgnoreCase);
|
||||
return re.Replace(str, value);
|
||||
}
|
||||
|
||||
public static string CleanIdentifier(string str)
|
||||
{
|
||||
if (String.IsNullOrEmpty(str))
|
||||
return str;
|
||||
|
||||
return Regex.Replace(str, "\\W", "_");
|
||||
}
|
||||
|
||||
public static string GetRandomHexString(int length)
|
||||
{
|
||||
byte[] buf = new byte[length];
|
||||
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
|
||||
rng.GetBytes(buf);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for(int i = 0; i < length; i++)
|
||||
sb.AppendFormat("{0:X2}", buf[i]);
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static string GetRandomString(int length)
|
||||
{
|
||||
string ptrn = "abcdefghjklmnpqrstwxyzABCDEFGHJKLMNPQRSTWXYZ0123456789";
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
byte[] randomBytes = new byte[4];
|
||||
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
|
||||
rng.GetBytes(randomBytes);
|
||||
|
||||
// Convert 4 bytes into a 32-bit integer value.
|
||||
int seed = (randomBytes[0] & 0x7f) << 24 |
|
||||
randomBytes[1] << 16 |
|
||||
randomBytes[2] << 8 |
|
||||
randomBytes[3];
|
||||
|
||||
|
||||
Random rnd = new Random(seed);
|
||||
|
||||
for (int i = 0; i < length; i++)
|
||||
sb.Append(ptrn[rnd.Next(ptrn.Length - 1)]);
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static DateTime ParseDate(object value)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (DateTime) value;
|
||||
}
|
||||
catch(Exception )
|
||||
{
|
||||
return DateTime.MinValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue