common/Utils/UserAccessCtrl/LDAPUser.cs
2026-04-23 17:50:07 +02:00

126 lines
5.6 KiB
C#

using System;
using System.Collections;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
namespace Xylem.Common.Utils.UserAccessCtrl
{
public class LDAPUser
{
public LDAPUser()
=> InitializeLDAPUser();
public Int32 EmployeeId { get; private set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Phone { get; set; }
public String Email { get; set; }
public String Username { get; set; }
public String DomainName { get; private set; }
public String Password { get; set; }
public String ConfirmPassword { get; set; }
public Boolean Found { get; private set; }
private void InitializeLDAPUser()
{
try
{
var currentUser = UserPrincipal.Current;
using (var directoryEntry = new DirectoryEntry($"LDAP://{currentUser.DistinguishedName}"))
{
using (var directorySearcher = new DirectorySearcher(directoryEntry))
{
var searchResult = directorySearcher.FindOne();
foreach (DictionaryEntry dictionaryEntry in searchResult.Properties)
{
if (dictionaryEntry.Key is String property)
{
if (property.Equals("employeeid", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String value)
{
if (int.TryParse(value, out Int32 employeeId))
{
EmployeeId = employeeId;
}
}
}
}
else if (property.Equals("givenname", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String firstName)
{
FirstName = firstName;
}
}
}
else if (property.Equals("sn", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String lastName)
{
LastName = lastName;
}
}
}
else if (property.Equals("mail", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String email)
{
Email = email;
}
}
}
else if (property.Equals("telephonenumber", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String phone)
{
Phone = phone;
}
}
}
else if (property.Equals("samaccountname", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String username)
{
DomainName = username.ToLower();
Username = DomainName;
}
}
}
Found = EmployeeId > 0;
}
}
}
}
}
catch (Exception)
{
}
}
}
}