common/Ui/GenesisToolBox/Infrastructure/LDAPUser.cs
2026-04-23 17:50:07 +02:00

126 lines
5.7 KiB
C#

namespace Xylem.Common.Ui.GenesisToolBox.Infrastructure
{
using System;
using System.Collections;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
internal class LDAPUser
{
public LDAPUser()
=> this.InitializeLDAPUser();
public int 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 bool 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 int employeeId))
{
this.EmployeeId = employeeId;
}
}
}
}
else if (property.Equals("givenname", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is string firstName)
{
this.FirstName = firstName;
}
}
}
else if (property.Equals("sn", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is string lastName)
{
this.LastName = lastName;
}
}
}
else if (property.Equals("mail", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is string email)
{
this.Email = email;
}
}
}
else if (property.Equals("telephonenumber", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is string phone)
{
this.Phone = phone;
}
}
}
else if (property.Equals("samaccountname", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is string username)
{
this.DomainName = username.ToLower();
this.Username = this.DomainName;
}
}
}
this.Found = this.EmployeeId > 0;
}
}
}
}
}
catch (Exception)
{
}
}
}
}