877 lines
36 KiB
C#
877 lines
36 KiB
C#
using System;
|
|
using System.Data;
|
|
using System.IO;
|
|
using System.Text;
|
|
using System.DirectoryServices;
|
|
using System.Security.Cryptography;
|
|
/****************************************************************************/
|
|
using System.Text.RegularExpressions;
|
|
using System.Collections;
|
|
/****************************************************************************/
|
|
using AyABL.AUT.FiltroBuscador;
|
|
using AyABL.AUT.Login;
|
|
using AyABL.AUT.PropiedadesAyuda;
|
|
|
|
|
|
namespace AyABL.AUT.Autenticacion
|
|
{
|
|
public class AutenticacionBL
|
|
{
|
|
private static string passPhrase = "P@SzFr@c3"; // puede ser cualquier string
|
|
private static string saltValue = "S@7tV@763"; // puede ser cualquier string
|
|
private static string hashAlgorithm = "MD5"; // puede ser "SHA1"
|
|
private static int passwordIterations = 3; // puede ser cualquier number
|
|
private static string initVector = "@1B2c3D4e5F6g7H8"; // debe ser 16 bytes
|
|
private static int keySize = 256; // puede ser 192 o 128
|
|
/****************************************************************************/
|
|
private string _adPassword = string.Empty;
|
|
private string _adPath = string.Empty;
|
|
private string _adLogin = string.Empty;
|
|
private DirectoryEntry _dirEntry = null;
|
|
/****************************************************************************/
|
|
|
|
/// <summary>
|
|
/// Metodo constructor
|
|
/// </summary>
|
|
|
|
public AutenticacionBL()
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// Metodo constructor
|
|
/// </summary>
|
|
/// <param name="de"></param>
|
|
|
|
public AutenticacionBL(DirectoryEntry de)
|
|
{
|
|
_dirEntry = de;
|
|
}
|
|
|
|
private Char Chr(int i)
|
|
{
|
|
//Return the character of the given character value
|
|
//Devuelve el caracter del codigo ascii que se le pasa ejemplo Convert.ToChar(162) = ó
|
|
return Convert.ToChar(i);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Metodo que se utiliza para validar contra el Active Directory(AD)
|
|
/// </summary>
|
|
/// <param name="userName"></param>
|
|
/// <param name="password"></param>
|
|
/// <param name="domain"></param>
|
|
/// <returns></returns>
|
|
|
|
public bool Autenticar(string userName, string password, string domain)
|
|
{
|
|
bool authentic = false;
|
|
|
|
try
|
|
{
|
|
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, password);
|
|
|
|
object nativeObject = entry.NativeObject;
|
|
|
|
DirectorySearcher Buscar = new DirectorySearcher(entry);
|
|
|
|
Buscar.Filter = "(SAMAcciountName=" + userName + ")";
|
|
Buscar.PropertiesToLoad.Add("cn");
|
|
|
|
SearchResult Resultado = Buscar.FindOne();
|
|
|
|
authentic = true;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
|
|
}
|
|
return authentic;
|
|
}
|
|
|
|
//Busca usuarios en el ActiveDirectory
|
|
|
|
public enum objectClass
|
|
{
|
|
usuario, grupo, estacion,
|
|
user, group, computer
|
|
}
|
|
|
|
public enum returnType
|
|
{
|
|
distinguishedName, ObjectGUID
|
|
}
|
|
|
|
public string GetADLogin(objectClass objectCls, returnType returnValue, string objectName, string LdapDomain)
|
|
{
|
|
string[] strLoginsArray;
|
|
string distinguishedName = string.Empty;
|
|
string connectionPrefix = "LDAP://" + LdapDomain;
|
|
DirectoryEntry entry = new DirectoryEntry(connectionPrefix);
|
|
DirectorySearcher mySearcher = new DirectorySearcher(entry);
|
|
|
|
try
|
|
{
|
|
switch (objectCls)
|
|
{
|
|
case objectClass.usuario:
|
|
mySearcher.Filter = "(&(objectClass=user) (|(cn=" + objectName + ")(sAMAccountName=" + objectName + ")))";
|
|
break;
|
|
case objectClass.grupo:
|
|
mySearcher.Filter = "(&(objectClass=group) (|(cn=" + objectName + ")(dn=" + objectName + ")))";
|
|
break;
|
|
case objectClass.estacion:
|
|
mySearcher.Filter = "(&(objectClass=computer) (|(cn=" + objectName + ")(dn=" + objectName + ")))";
|
|
break;
|
|
}
|
|
SearchResult result = mySearcher.FindOne();
|
|
|
|
if (result == null)
|
|
{
|
|
throw new NullReferenceException
|
|
("unable to locate the distinguishedName for the object " +
|
|
objectName + " in the " + LdapDomain + " domain");
|
|
}
|
|
DirectoryEntry directoryObject = result.GetDirectoryEntry();
|
|
if (returnValue.Equals(returnType.distinguishedName))
|
|
{
|
|
distinguishedName = "LDAP://" + directoryObject.Properties
|
|
["distinguishedName"].Value;
|
|
}
|
|
if (returnValue.Equals(returnType.ObjectGUID))
|
|
{
|
|
distinguishedName = directoryObject.Guid.ToString();
|
|
}
|
|
entry.Close();
|
|
entry.Dispose();
|
|
mySearcher.Dispose();
|
|
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
|
|
}
|
|
|
|
return distinguishedName;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Metodo que se utiliza para identificar los servidores en los que se encuentra el Active Directory(AD)
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
|
|
private DirectoryEntry GetDirectoryObject()
|
|
{
|
|
DirectoryEntry oDE, oDE2;
|
|
oDE = new DirectoryEntry("LDAP://aya-srv-0111/DC=intranet,DC=aya,DC=go,DC=cr", /*"administrator", "password",*/"","", AuthenticationTypes.Secure);
|
|
oDE2 = new DirectoryEntry("LDAP://aya-vsrv-0112/DC=intranet,DC=aya,DC=go,DC=cr", /*"administrator", "password",*/"", "", AuthenticationTypes.Secure);
|
|
return oDE;
|
|
}
|
|
|
|
public DirectoryEntry GetAllLoginBLs()
|
|
{
|
|
DirectoryEntry de = GetDirectoryObject();
|
|
DirectorySearcher deSearch = new DirectorySearcher();
|
|
deSearch.SearchRoot = de;
|
|
|
|
deSearch.Filter = "(&(objectClass=user))";
|
|
deSearch.SearchScope = SearchScope.Subtree;
|
|
SearchResult results = deSearch.FindOne();
|
|
|
|
if (!(results == null))
|
|
{
|
|
de = new DirectoryEntry(results.Path, "","",/*"administrator", "password",*/ AuthenticationTypes.Secure);
|
|
return de;
|
|
}
|
|
else
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public string Decrypt(string cipherText)
|
|
{
|
|
// Convert strings defining encryption key characteristics into byte
|
|
// arrays. Let us assume that strings only contain ASCII codes.
|
|
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
|
|
// encoding.
|
|
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
|
|
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
|
|
|
|
// Convert our ciphertext into a byte array.
|
|
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
|
|
|
|
// First, we must create a password, from which the key will be
|
|
// derived. This password will be generated from the specified
|
|
// passphrase and salt value. The password will be created using
|
|
// the specified hash algorithm. Password creation can be done in
|
|
// several iterations.
|
|
PasswordDeriveBytes password = new PasswordDeriveBytes(
|
|
passPhrase,
|
|
saltValueBytes,
|
|
hashAlgorithm,
|
|
passwordIterations);
|
|
|
|
// Use the password to generate pseudo-random bytes for the encryption
|
|
// key. Specify the size of the key in bytes (instead of bits).
|
|
byte[] keyBytes = password.GetBytes(keySize / 8);
|
|
|
|
// Create uninitialized Rijndael encryption object.
|
|
RijndaelManaged symmetricKey = new RijndaelManaged();
|
|
|
|
// It is reasonable to set encryption mode to Cipher Block Chaining
|
|
// (CBC). Use default options for other symmetric key parameters.
|
|
symmetricKey.Mode = CipherMode.CBC;
|
|
|
|
// Generate decryptor from the existing key bytes and initialization
|
|
// vector. Key size will be defined based on the number of the key
|
|
// bytes.
|
|
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
|
|
keyBytes,
|
|
initVectorBytes);
|
|
|
|
// Define memory stream which will be used to hold encrypted data.
|
|
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
|
|
|
|
// Define cryptographic stream (always use Read mode for encryption).
|
|
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 ciphertext;
|
|
// plaintext is never longer than ciphertext.
|
|
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
|
|
|
|
// Start decrypting.
|
|
int decryptedByteCount = cryptoStream.Read(plainTextBytes,
|
|
0,
|
|
plainTextBytes.Length);
|
|
|
|
// Close both streams.
|
|
memoryStream.Close();
|
|
cryptoStream.Close();
|
|
|
|
// Convert decrypted data into a string.
|
|
// Let us assume that the original plaintext string was UTF8-encoded.
|
|
string plainText = Encoding.UTF8.GetString(plainTextBytes,
|
|
0,
|
|
decryptedByteCount);
|
|
|
|
// Return decrypted string.
|
|
return plainText;
|
|
}
|
|
|
|
public string Encrypt(string plainText)
|
|
{
|
|
// Convert strings into byte arrays.
|
|
// Let us assume that strings only contain ASCII codes.
|
|
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
|
|
// encoding.
|
|
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
|
|
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
|
|
|
|
// Convert our plaintext into a byte array.
|
|
// Let us assume that plaintext contains UTF8-encoded characters.
|
|
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
|
|
|
|
// First, we must create a password, from which the key will be derived.
|
|
// This password will be generated from the specified passphrase and
|
|
// salt value. The password will be created using the specified hash
|
|
// algorithm. Password creation can be done in several iterations.
|
|
PasswordDeriveBytes password = new PasswordDeriveBytes(
|
|
passPhrase,
|
|
saltValueBytes,
|
|
hashAlgorithm,
|
|
passwordIterations);
|
|
|
|
// Use the password to generate pseudo-random bytes for the encryption
|
|
// key. Specify the size of the key in bytes (instead of bits).
|
|
byte[] keyBytes = password.GetBytes(keySize / 8);
|
|
|
|
// Create uninitialized Rijndael encryption object.
|
|
RijndaelManaged symmetricKey = new RijndaelManaged();
|
|
|
|
// It is reasonable to set encryption mode to Cipher Block Chaining
|
|
// (CBC). Use default options for other symmetric key parameters.
|
|
symmetricKey.Mode = CipherMode.CBC;
|
|
|
|
// Generate encryptor from the existing key bytes and initialization
|
|
// vector. Key size will be defined based on the number of the key
|
|
// bytes.
|
|
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
|
|
keyBytes,
|
|
initVectorBytes);
|
|
|
|
// Define memory stream which will be used to hold encrypted data.
|
|
MemoryStream memoryStream = new MemoryStream();
|
|
|
|
// Define cryptographic stream (always use Write mode for encryption).
|
|
CryptoStream cryptoStream = new CryptoStream(memoryStream,
|
|
encryptor,
|
|
CryptoStreamMode.Write);
|
|
// Start encrypting.
|
|
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
|
|
|
|
// Finish encrypting.
|
|
cryptoStream.FlushFinalBlock();
|
|
|
|
// Convert our encrypted data from a memory stream into a byte array.
|
|
byte[] cipherTextBytes = memoryStream.ToArray();
|
|
|
|
// Close both streams.
|
|
memoryStream.Close();
|
|
cryptoStream.Close();
|
|
|
|
// Convert encrypted data into a base64-encoded string.
|
|
string cipherText = Convert.ToBase64String(cipherTextBytes);
|
|
|
|
// Return encrypted string.
|
|
return cipherText;
|
|
}
|
|
|
|
/****************************************************************************/
|
|
public void Connect(string adPath, string adLogin, string adPassword)
|
|
{
|
|
_adPath = adPath;
|
|
_adLogin = adLogin;
|
|
_adPassword = adPassword;
|
|
if (string.Empty == _adLogin || null == _adLogin)
|
|
{
|
|
_adLogin = null;
|
|
_adPassword = null;
|
|
}
|
|
_dirEntry = new DirectoryEntry(_adPath, _adLogin, _adPassword, AuthenticationTypes.Secure);
|
|
}
|
|
|
|
public void Connect(string adPath)
|
|
{
|
|
_adPath = adPath;
|
|
_dirEntry = new DirectoryEntry(_adPath);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Conecta con el servidor de active directory con las credenciales sumistradas.
|
|
/// El servidor de AD esta en ServerLdapPath.
|
|
/// </summary>
|
|
/// <param name="Login">Login de usuario de AD.</param>
|
|
/// <param name="Clave">Clave del usuario de AD</param>
|
|
/// <returns>Objeto del helper de AD.</returns>
|
|
private static AutenticacionBL GetConnection(string Login, string Clave)
|
|
{
|
|
|
|
AutenticacionBL helper = new AutenticacionBL();
|
|
//helper.Connect(System.Configuration.ConfigurationSettings.AppSettings["ServerLdapPath"], Login, Clave);
|
|
try
|
|
{
|
|
helper.Connect(System.Configuration.ConfigurationSettings.AppSettings["ServerLdapPath"]);
|
|
}
|
|
catch (Exception ex)
|
|
{ throw ex; }
|
|
return helper;
|
|
}
|
|
/// <summary>
|
|
/// Metodo utilizado para autenticarde contra el Active Directory.
|
|
/// Si el no se puede autenticar devuelve un error que sera manejado en otras capas.
|
|
/// </summary>
|
|
/// <param name="Login">Login de Usuario de AD.</param>
|
|
/// <param name="Clave">Clave del usuario de AD.</param>
|
|
public void Autenticar(string Login, string Clave)
|
|
{
|
|
try
|
|
{
|
|
Object c = GetConnection(Login, Clave)._dirEntry.NativeObject;
|
|
}
|
|
catch (DirectoryServicesCOMException ex)
|
|
{ throw ex; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Metodo Utilizado para buscar usuarios del AD.
|
|
/// Es utilizados en busquedas tanto por nombre como por login de usuario.
|
|
/// </summary>
|
|
/// <param name="userName">Texto que se desea buscar en la infomacion del usuario.</param>
|
|
/// <param name="Login">Login para porder conectarde al AD.</param>
|
|
/// <param name="Clave">Clave para porder conectarde al AD.</param>
|
|
/// <returns>Tabla con la infomacion acerca de los usuarios encontrados.</returns>
|
|
|
|
public DataSet BuscarLoginUsuario(string userName, string Login, string Clave)
|
|
{
|
|
AutenticacionBL helper = GetConnection(Login, Clave);
|
|
string customFilter = string.Format("(&(objectClass=user)(|(givenName={0}*)(sn={0}*)(SamAccountName={0}*)))", userName);
|
|
FiltroBuscadorBL usersFilter = new FiltroBuscadorBL(customFilter);
|
|
DataSet resultDs = new DataSet();
|
|
DataTable resultDt = new DataTable("LoginBLs");
|
|
try
|
|
{
|
|
//ArrayList users = helper.FindObjects(usersFilter, "CN=cn,FirstName=givenName,LastName=sn,LogonName=sAMAccountName,Groups=memberOf");
|
|
ArrayList users = helper.FindObjects(usersFilter, "CN=cn,Display FirstName=givenName,LastName=sn,LogonName=sAMAccountName,Groups=memberOf,P.O.Box=postOfficeBox");
|
|
|
|
|
|
resultDs.Tables.Add(resultDt);
|
|
resultDt.Columns.Add("Login", typeof(String));
|
|
resultDt.Columns.Add("Nombre", typeof(String));
|
|
//resultDt.Columns.Add("Apellidos", typeof(String));
|
|
resultDt.Columns.Add("Cedula", typeof(String));
|
|
|
|
foreach (Hashtable userProperties in users) //convert the array list to dataset table
|
|
{
|
|
LoginBL resultLoginBL = new LoginBL();
|
|
PropiedadesAyudaBL.FillObject(resultLoginBL, userProperties);
|
|
DataRow row = resultDt.NewRow();
|
|
//row["Login"] = resultLoginBL.LogonName;
|
|
row["Login"] = userProperties["LogonName"].ToString();
|
|
//row["Nombre"] = Convert.ToString(resultLoginBL.CN);
|
|
row["Nombre"] = userProperties["CN"].ToString();
|
|
//row["Apellidos"] = Convert.ToString(resultLoginBL.LastName);
|
|
row["Cedula"] = userProperties["P.O.Box"] == null ? " " : userProperties["P.O.Box"].ToString();
|
|
resultDt.Rows.Add(row);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
throw ex;
|
|
}
|
|
return resultDs;
|
|
}
|
|
|
|
public DataSet BuscarGruposUsuario(string userName, string Login, string Clave)
|
|
{
|
|
AutenticacionBL helper = GetConnection(Login, Clave);
|
|
string customFilter = string.Format("(&(objectClass=user)(|(givenName={0}*)(sn={0}*)(SamAccountName={0}*)))", userName);
|
|
FiltroBuscadorBL usersFilter = new FiltroBuscadorBL(customFilter);
|
|
ArrayList arlUsuarios = helper.FindObjects(usersFilter, "Groups=memberOf");
|
|
DataSet dsGrupos = new DataSet();
|
|
DataTable dtGrupos = new DataTable("Grupos");
|
|
|
|
dsGrupos.Tables.Add(dtGrupos);
|
|
dtGrupos.Columns.Add("Grupos", typeof(String));
|
|
|
|
foreach (Hashtable userProperties in arlUsuarios) //convert the array list to dataset table
|
|
{
|
|
LoginBL resultLoginBL = new LoginBL();
|
|
PropiedadesAyudaBL.FillObject(resultLoginBL, userProperties);
|
|
foreach (string strGrupos in resultLoginBL.Groups)
|
|
{
|
|
|
|
DataRow row = dtGrupos.NewRow();
|
|
row["Grupos"] = strGrupos;
|
|
dtGrupos.Rows.Add(row);
|
|
}
|
|
}
|
|
return dsGrupos;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Metodo para buscar un usuario espesifico.
|
|
/// </summary>
|
|
/// <param name="Login">Login del usuario que se busca. Tambien se autentica con este Usuario.</param>
|
|
/// <param name="Clave">Clave del usuario para autenticarse con el AD.</param>
|
|
/// <returns></returns>
|
|
|
|
public LoginBL BuscarUnLoginUsuario(string Login, string Clave)
|
|
{
|
|
AutenticacionBL helper = GetConnection(Login, Clave);
|
|
string customFilter = string.Format("(&(objectClass=user)(|(givenName={0}*)(sn={0}*)(SamAccountName={0}*)))", Login);
|
|
FiltroBuscadorBL usersFilter = new FiltroBuscadorBL(customFilter);
|
|
ArrayList users = helper.FindObjects(usersFilter, "CN=cn,FirstName=givenName,LastName=sn,LogonName=sAMAccountName,Groups=memberOf");
|
|
LoginBL resultLoginBL = new LoginBL();
|
|
foreach (Hashtable userProperties in users) //Convierte el array list en un dataset table
|
|
{
|
|
PropiedadesAyudaBL.FillObject(resultLoginBL, userProperties);
|
|
}
|
|
return resultLoginBL;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Metodo para buscar un usuario espesifico.
|
|
/// </summary>
|
|
/// <param name="Login">Login del usuario que se busca. Tambien se autentica con este Usuario.</param>
|
|
/// <param name="Clave">Clave del usuario para autenticarse con el AD.</param>
|
|
/// <returns></returns>
|
|
|
|
//public DataSet BuscarUnGrupoUsuario(string Login, string Clave)
|
|
//{
|
|
// DataSet dsUsuarios = new DataSet();
|
|
|
|
// AutenticacionBL helper = GetConnection(Login, Clave);
|
|
// string customFilter = string.Format("(&(objectClass=user)(|(givenName={0}*)(sn={0}*)(SamAccountName={0}*)))", Login);
|
|
// FiltroBuscadorBL usersFilter = new FiltroBuscadorBL(customFilter);
|
|
// dsUsuarios = helper.FindObjects(usersFilter, "CN=cn,FirstName=givenName,LastName=sn,LogonName=sAMAccountName,Groups=memberOf");
|
|
// DataSet dsUsuarios = users;
|
|
// LoginBL resultLoginBL = new LoginBL();
|
|
// foreach (Hashtable userProperties in users) //Convierte el array list en un dataset table
|
|
// {
|
|
// PropiedadesAyudaBL.FillObject(resultLoginBL, userProperties);
|
|
// }
|
|
// return resultLoginBL;
|
|
//}
|
|
|
|
/// <summary>
|
|
/// Copia las entidades del AD.
|
|
/// </summary>
|
|
/// <param name="configInfo"></param>
|
|
/// <param name="de"></param>
|
|
/// <param name="propertyValues"></param>
|
|
private void CopyEntryToProperties(string configInfo, DirectoryEntry de, Hashtable propertyValues)
|
|
{
|
|
foreach (string property in configInfo.Split(','))
|
|
{
|
|
string[] propertyValue = property.Split('=');
|
|
if (propertyValue.Length == 2)
|
|
{
|
|
propertyValues[propertyValue[0]] = this.GetProperty(de, propertyValue[1]);
|
|
}
|
|
}
|
|
propertyValues.Add("LdapPath", de.Path);
|
|
propertyValues.Add("LdapObjectClass", de.Properties["objectClass"][de.Properties["objectClass"].Count - 1]);
|
|
propertyValues.Add("ParentLdapPath", de.Parent.Path);
|
|
}
|
|
/// <summary>
|
|
/// Obtiene una propidade de una entidad del AD.
|
|
/// </summary>
|
|
/// <param name="de">Entidad de AD.</param>
|
|
/// <param name="PropertyName">Propiedad que se busca en el entidad.</param>
|
|
/// <returns></returns>
|
|
private object GetProperty(DirectoryEntry de, string PropertyName)
|
|
{
|
|
if (de.Properties.Contains(PropertyName))
|
|
{
|
|
if (de.Properties[PropertyName].Count == 1)
|
|
{
|
|
return de.Properties[PropertyName].Value;
|
|
}
|
|
else
|
|
{
|
|
IList values = new ArrayList();
|
|
foreach (object item in de.Properties[PropertyName])
|
|
{
|
|
values.Add(item);
|
|
}
|
|
return values;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Copia las propiedades a una entidad.
|
|
/// </summary>
|
|
/// <param name="configInfo"></param>
|
|
/// <param name="propertyValues"></param>
|
|
/// <param name="de"></param>
|
|
private void CopyPropertiesToEntry(string configInfo, Hashtable propertyValues, DirectoryEntry de)
|
|
{
|
|
foreach (string property in configInfo.Split(','))
|
|
{
|
|
string[] propertyValue = property.Split('=');
|
|
if (propertyValue.Length == 2)
|
|
{
|
|
object value = propertyValues[propertyValue[0]];
|
|
if (value != null)
|
|
{
|
|
this.SetProperty(de, propertyValue[1], propertyValues[propertyValue[0]]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Escribe el valor de una propiedad en la entidad recivida.
|
|
/// </summary>
|
|
/// <param name="de">Entidad del Ad.</param>
|
|
/// <param name="propertyName">Nombre de la propidad.</param>
|
|
/// <param name="propertyValue">Valor de la propidad.</param>
|
|
|
|
private void SetProperty(DirectoryEntry de, string propertyName, object propertyValue)
|
|
{
|
|
if (propertyValue != null)
|
|
{
|
|
IList values = propertyValue as ArrayList;
|
|
bool isArray = (values != null);
|
|
if (de.Properties.Contains(propertyName))
|
|
{
|
|
if (!isArray)
|
|
{
|
|
if (propertyValue.ToString() != string.Empty)
|
|
{
|
|
de.Properties[propertyName].Value = propertyValue;
|
|
}
|
|
else
|
|
{
|
|
de.Properties[propertyName].Clear();
|
|
}
|
|
}
|
|
else
|
|
{
|
|
try
|
|
{
|
|
de.Properties[propertyName].Clear();
|
|
foreach (object value in values)
|
|
{
|
|
// En en .NET 1.1 SP3 y Windows 2000 levanta una excepcion en este punto
|
|
de.Properties[propertyName].Add(value);
|
|
}
|
|
|
|
}
|
|
catch
|
|
{
|
|
// begin - HACK para que funcione en .NET 1.1 SP3 y Windows 2000
|
|
de.CommitChanges();
|
|
foreach (object value in values)
|
|
{
|
|
de.Properties[propertyName].Add(value);
|
|
}
|
|
// end - HACK para que funcione en .NET 1.1 SP3 y Windows 2000
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (!isArray)
|
|
{
|
|
if (propertyValue.ToString() != string.Empty)
|
|
{
|
|
de.Properties[propertyName].Add(propertyValue);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
foreach (object value in values)
|
|
{
|
|
de.Properties[propertyName].Add(value);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Crea un objeto del una entidad padre a una nueva entidad y devuelve el path
|
|
/// </summary>
|
|
/// <param name="parentObject"></param>
|
|
/// <param name="createString"></param>
|
|
/// <param name="objectClass"></param>
|
|
/// <param name="properties"></param>
|
|
/// <param name="propertyInfo"></param>
|
|
/// <returns></returns>
|
|
|
|
public string CreateObject(FiltroBuscadorBL parentObject, string createString, string objectClass, Hashtable properties, string propertyInfo)
|
|
{
|
|
DirectoryEntry parentEntry = this.FindEntry(parentObject);
|
|
DirectoryEntry newEntry = parentEntry.Children.Add(createString, objectClass);
|
|
newEntry = this.SetLoginBLToDirEntry(newEntry);
|
|
this.CopyPropertiesToEntry(propertyInfo, properties, newEntry);
|
|
newEntry.CommitChanges();
|
|
return newEntry.Path;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Crea un objeto del una entidad padre a una nueva entidad y devuelve el path
|
|
/// </summary>
|
|
/// <param name="parentObjectPath"></param>
|
|
/// <param name="createString"></param>
|
|
/// <param name="objectClass"></param>
|
|
/// <param name="properties"></param>
|
|
/// <param name="propertyInfo"></param>
|
|
/// <returns></returns>
|
|
|
|
public string CreateObject(string parentObjectPath, string createString, string objectClass, Hashtable properties, string propertyInfo)
|
|
{
|
|
DirectoryEntry parentEntry = this.FindEntry(parentObjectPath);
|
|
DirectoryEntry newEntry = parentEntry.Children.Add(createString, objectClass);
|
|
newEntry = this.SetLoginBLToDirEntry(newEntry);
|
|
this.CopyPropertiesToEntry(propertyInfo, properties, newEntry);
|
|
newEntry.CommitChanges();
|
|
return newEntry.Path;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Busca en objeto de AD y devuelve las propiedades de este.
|
|
/// </summary>
|
|
/// <param name="sf">Filtro de buscador</param>
|
|
/// <param name="propertyInfo">Informacion de las propiedades.</param>
|
|
/// <returns>Tabla de propiedades.</returns>
|
|
|
|
public Hashtable FindObject(FiltroBuscadorBL sf, string propertyInfo)
|
|
{
|
|
DirectoryEntry entry = this.FindEntry(sf);
|
|
if (entry == null)
|
|
{
|
|
return null;
|
|
}
|
|
else
|
|
{
|
|
Hashtable properties = new Hashtable();
|
|
this.CopyEntryToProperties(propertyInfo, entry, properties);
|
|
return properties;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="ldapPath"></param>
|
|
/// <param name="propertyInfo"></param>
|
|
/// <returns></returns>
|
|
public Hashtable FindObject(string ldapPath, string propertyInfo)
|
|
{
|
|
DirectoryEntry entry = this.FindEntry(ldapPath);
|
|
if (entry == null)
|
|
{
|
|
return null;
|
|
}
|
|
else
|
|
{
|
|
Hashtable properties = new Hashtable();
|
|
this.CopyEntryToProperties(propertyInfo, entry, properties);
|
|
return properties;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Buscar objetos del active directory y debuelve un lista con estos objetos.
|
|
/// </summary>
|
|
/// <param name="sf">Filtro de la busqueda.</param>
|
|
/// <param name="propertyInfo">Informacion de las propiedades.</param>
|
|
/// <returns></returns>
|
|
|
|
public ArrayList FindObjects(FiltroBuscadorBL sf, string propertyInfo)
|
|
{
|
|
ArrayList objects = new ArrayList();
|
|
SearchResultCollection results = this.FindAll(sf.Filter);
|
|
foreach (SearchResult result in results)
|
|
{
|
|
Hashtable properties = new Hashtable();
|
|
this.CopyEntryToProperties(propertyInfo, this.SetLoginBLToDirEntry(result.GetDirectoryEntry()), properties);
|
|
objects.Add(properties);
|
|
|
|
}
|
|
return objects;
|
|
}
|
|
|
|
/// <summary>
|
|
/// borra el objeto segun el path
|
|
/// </summary>
|
|
/// <param name="ldapPath">path que se desea borrar.</param>
|
|
|
|
public void RemoveObject(string ldapPath)
|
|
{
|
|
DirectoryEntry entry = this.FindEntry(ldapPath);
|
|
DirectoryEntry parentEntry = SetLoginBLToDirEntry(entry.Parent);
|
|
parentEntry.Children.Remove(entry);
|
|
parentEntry.CommitChanges();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Actualiza el objeto con las propiedades resividas.
|
|
/// </summary>
|
|
/// <param name="ldapPath"></param>
|
|
/// <param name="properties"></param>
|
|
/// <param name="propertyInfo"></param>
|
|
|
|
public void UpdateObject(string ldapPath, Hashtable properties, string propertyInfo)
|
|
{
|
|
DirectoryEntry entry = this.FindEntry(ldapPath);
|
|
this.CopyPropertiesToEntry(propertyInfo, properties, entry);
|
|
entry.CommitChanges();
|
|
}
|
|
/// <summary>
|
|
/// Buscar todas las entidades.
|
|
/// </summary>
|
|
/// <param name="filter">Filtro para la busqueda.</param>
|
|
/// <returns>Collecion de resultados de la busqueda.</returns>
|
|
private SearchResultCollection FindAll(string filter)
|
|
{
|
|
DirectorySearcher searcher = new DirectorySearcher();
|
|
searcher.SearchRoot = this._dirEntry;
|
|
searcher.Filter = filter;
|
|
searcher.SearchScope = SearchScope.Subtree;
|
|
return searcher.FindAll();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Encuetra entidades dependiendo del filtro.
|
|
/// </summary>
|
|
/// <param name="sf"></param>
|
|
/// <returns></returns>
|
|
private ArrayList FindEntries(FiltroBuscadorBL sf)
|
|
{
|
|
ArrayList entries = new ArrayList();
|
|
SearchResultCollection results = this.FindAll(sf.Filter);
|
|
|
|
foreach (SearchResult result in results)
|
|
{
|
|
entries.Add(result.GetDirectoryEntry());
|
|
}
|
|
return entries;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Obtiene una entidad con el usuario de la propiedad actual.
|
|
/// </summary>
|
|
/// <param name="de"></param>
|
|
/// <returns></returns>
|
|
private DirectoryEntry SetLoginBLToDirEntry(DirectoryEntry de)
|
|
{
|
|
de.Username = this._dirEntry.Username;
|
|
//de.Password = this._dirEntry.Password;
|
|
de.AuthenticationType = this._dirEntry.AuthenticationType;
|
|
return de;
|
|
}
|
|
/// <summary>
|
|
/// Busca una enditdad dependiendo del path.
|
|
/// </summary>
|
|
/// <param name="ldapPath"></param>
|
|
/// <returns></returns>
|
|
public DirectoryEntry FindEntry(string ldapPath)
|
|
{
|
|
string ldap = ldapPath;
|
|
const string regularExpresion = "LDAP://.*/";
|
|
if (ldapPath.ToUpper().IndexOf("LDAP://") == -1)
|
|
{
|
|
Match m = Regex.Match(_dirEntry.Path, regularExpresion);
|
|
if (m.Length > 0)
|
|
{
|
|
string server = m.Value;
|
|
ldap = server + ldap;
|
|
}
|
|
}
|
|
return new DirectoryEntry(ldap, this._dirEntry.Username, "" /*this._dirEntry.Password*/);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Busca una entidad dependiendo del filtro.
|
|
/// </summary>
|
|
/// <param name="sf"></param>
|
|
/// <returns></returns>
|
|
public DirectoryEntry FindEntry(FiltroBuscadorBL sf)
|
|
{
|
|
SearchResult result = this.FindOne(sf.Filter);
|
|
if (result == null)
|
|
{
|
|
return null;
|
|
}
|
|
else
|
|
{
|
|
return this.SetLoginBLToDirEntry(result.GetDirectoryEntry());
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Busca una entidad dependiendo del filtro.
|
|
/// </summary>
|
|
/// <param name="sf"></param>
|
|
/// <returns></returns>
|
|
private SearchResult FindOne(string filter)
|
|
{
|
|
DirectorySearcher searcher = new DirectorySearcher();
|
|
searcher.SearchRoot = this._dirEntry;
|
|
searcher.Filter = filter;
|
|
searcher.SearchScope = SearchScope.Subtree;
|
|
return searcher.FindOne();
|
|
}
|
|
}
|
|
}
|