refactor: Projektdateien migriert. Cloud-NuGet-Pakete durch lokale NuGet-Projekte ersetzt.
This commit is contained in:
9
HRD.LDAPService/Ldap/EN_LdapRoleListFilter.cs
Normal file
9
HRD.LDAPService/Ldap/EN_LdapRoleListFilter.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace HRD.LDAPService
|
||||
{
|
||||
public enum EN_LdapRoleListFilter
|
||||
{
|
||||
All = 1,
|
||||
OnlyRoleList = 2,
|
||||
OnlyWebAppRoleList = 3
|
||||
}
|
||||
}
|
||||
213
HRD.LDAPService/Ldap/LdapAuthenticationService.cs
Normal file
213
HRD.LDAPService/Ldap/LdapAuthenticationService.cs
Normal file
@@ -0,0 +1,213 @@
|
||||
using HRD.LDAPService.JWT;
|
||||
using System;
|
||||
using System.DirectoryServices.AccountManagement;
|
||||
using System.Linq;
|
||||
|
||||
namespace HRD.LDAPService
|
||||
{
|
||||
public static class LdapAuthenticationService
|
||||
{
|
||||
private const string LDAP_DOMAIN = "dhr.local";
|
||||
|
||||
private static UserPrincipal GetUserPrincipal(string loginName, PrincipalContext principalContext)
|
||||
{
|
||||
try
|
||||
{
|
||||
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, loginName);
|
||||
if (userPrincipal == null)
|
||||
{
|
||||
userPrincipal = UserPrincipal.FindByIdentity(principalContext, loginName);
|
||||
if (userPrincipal == null)
|
||||
{
|
||||
throw new Exception($"Can't find an user by name: '{loginName}'");
|
||||
}
|
||||
}
|
||||
|
||||
return userPrincipal;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Login failed wrong user credentials '{loginName}'", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a User without LDAP user authentication
|
||||
/// </summary>
|
||||
/// <param name="ldapUser"></param>
|
||||
/// <returns></returns>
|
||||
public static LdapUser RenewIdentity(string token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token)) { throw new ArgumentNullException("Token is empty!"); }
|
||||
|
||||
try
|
||||
{
|
||||
LdapUser ldapUserFromToken = JwtManager.DecryptTokenAsLdapUser(token);
|
||||
if (ldapUserFromToken == default)
|
||||
{
|
||||
throw new Exception($"Wrong token");
|
||||
}
|
||||
|
||||
using PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, LDAP_DOMAIN);
|
||||
ldapUserFromToken.IsValidatCredentials = true;
|
||||
UpdateLdapUserFromPrincipalContext(ref ldapUserFromToken, principalContext);
|
||||
return ldapUserFromToken;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Renew failed", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a User without LDAP user authentication
|
||||
/// </summary>
|
||||
/// <param name="ldapUser"></param>
|
||||
/// <returns></returns>
|
||||
public static LdapUser RenewIdentity(LdapUser ldapUser)
|
||||
{
|
||||
if (ldapUser == default) { return default; }
|
||||
try
|
||||
{
|
||||
if (String.IsNullOrEmpty(ldapUser.LoginName))
|
||||
{
|
||||
throw new Exception($"Renew Login failed empty user Loginname");
|
||||
}
|
||||
|
||||
LdapUser ldapUserFromToken = JwtManager.DecryptTokenAsLdapUser(ldapUser.Token);
|
||||
if (ldapUserFromToken == default)
|
||||
{
|
||||
throw new Exception($"Wrong token");
|
||||
}
|
||||
|
||||
if (!string.Equals(ldapUserFromToken.LoginName, ldapUser.LoginName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new Exception($"Loginname and Token-Loginname are not the same");
|
||||
}
|
||||
|
||||
if (ldapUser.IsRealLDAPUser)
|
||||
{
|
||||
ldapUserFromToken.IsRealLDAPUser = ldapUser.IsRealLDAPUser;
|
||||
using PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, LDAP_DOMAIN);
|
||||
ldapUser.IsValidatCredentials = true;
|
||||
UpdateLdapUserFromPrincipalContext(ref ldapUserFromToken, principalContext);
|
||||
}
|
||||
else
|
||||
{
|
||||
ldapUserFromToken.IsRealLDAPUser = false;
|
||||
ldapUserFromToken.AddPasswordHash(ldapUser.PasswordHash);
|
||||
|
||||
if (!string.Equals(ldapUserFromToken.PasswordHashShort, ldapUser.PasswordHashShort, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new Exception($"PasswordHashShort and Token-PasswordHashShortare not the same");
|
||||
}
|
||||
|
||||
ldapUserFromToken.IsValidatCredentials = !string.IsNullOrEmpty(ldapUserFromToken.PasswordHash);
|
||||
ldapUserFromToken.Enabled = ldapUserFromToken.IsValidatCredentials;
|
||||
|
||||
ldapUserFromToken.BadLogonCount = ldapUserFromToken.IsValidatCredentials ? 0 : ldapUserFromToken.BadLogonCount + 1;
|
||||
|
||||
//ldapUserFromToken.IsAccountLockedOut = ;
|
||||
//ldapUserFromToken.LdapName = ;
|
||||
//ldapUserFromToken.LdapSurname = ;
|
||||
//ldapUserFromToken.LdapGuid = ;
|
||||
//ldapUserFromToken.Email = ;
|
||||
//ldapUserFromToken.AccountLockoutTime = ;
|
||||
}
|
||||
return ldapUserFromToken;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Login failed wrong user credentials '{ldapUser.LoginName}'", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a User after LDAP user authentication
|
||||
/// </summary>
|
||||
/// <param name="ldapUser"></param>
|
||||
/// <returns></returns>
|
||||
public static bool CheckAndUpdateIdentityWithPassword(LdapUser ldapUser)
|
||||
{
|
||||
if (ldapUser == default) { return false; }
|
||||
try
|
||||
{
|
||||
if (String.IsNullOrEmpty(ldapUser.LoginName))
|
||||
{
|
||||
throw new Exception($"Login failed wrong user Loginname");
|
||||
}
|
||||
|
||||
if (!JwtTokenConfig.DeaktivateLDAP)
|
||||
{
|
||||
ldapUser.IsRealLDAPUser = true;
|
||||
using var principalContext = new PrincipalContext(ContextType.Domain, LDAP_DOMAIN);
|
||||
//Check PWD
|
||||
ldapUser.IsValidatCredentials = principalContext.ValidateCredentials(ldapUser.LoginName, ldapUser.Password);
|
||||
|
||||
UpdateLdapUserFromPrincipalContext(ref ldapUser, principalContext);
|
||||
}
|
||||
else
|
||||
{
|
||||
ldapUser.IsRealLDAPUser = false;
|
||||
|
||||
//ldapUser.AddPasswordHash(JWTCrypt.GenerateHashPassword(ldapUser.Password));
|
||||
var hash = JWTCrypt.SHA512(ldapUser.Password);
|
||||
ldapUser.AddPasswordHash(hash);
|
||||
ldapUser.IsValidatCredentials = !string.IsNullOrEmpty(ldapUser.PasswordHash);
|
||||
if (ldapUser.IsValidatCredentials)
|
||||
{
|
||||
ldapUser.Enabled = true;
|
||||
ldapUser.BadLogonCount = 0;
|
||||
ldapUser.LastBadPasswordAttempt = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
ldapUser.Enabled = false;
|
||||
ldapUser.BadLogonCount = +1;
|
||||
ldapUser.LastBadPasswordAttempt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
//ldapUser.IsAccountLockedOut = ;
|
||||
//ldapUser.LdapName = ;
|
||||
//ldapUser.LdapSurname = ;
|
||||
//ldapUser.LdapGuid = ;
|
||||
//ldapUser.Email = ;
|
||||
//ldapUser.AccountLockoutTime = ;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ldapUser.IsValidatCredentials = false;
|
||||
throw new Exception($"Login failed wrong user credentials '{ldapUser.LoginName}'", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static void UpdateLdapUserFromPrincipalContext(ref LdapUser ldapUser, PrincipalContext principalContext)
|
||||
{
|
||||
UserPrincipal userPrincipal = GetUserPrincipal(ldapUser.LoginName, principalContext);
|
||||
if (userPrincipal == default)
|
||||
{
|
||||
throw new Exception($"Renew Login failed wrong user credentials '{ldapUser.LoginName}'");
|
||||
}
|
||||
|
||||
ldapUser.IsAccountLockedOut = userPrincipal.IsAccountLockedOut();
|
||||
ldapUser.BadLogonCount = userPrincipal.BadLogonCount;
|
||||
ldapUser.Enabled = userPrincipal.Enabled ?? false;
|
||||
ldapUser.LastBadPasswordAttempt = userPrincipal.LastBadPasswordAttempt;
|
||||
ldapUser.LdapName = userPrincipal.Name;
|
||||
ldapUser.LdapSurname = userPrincipal.Surname;
|
||||
ldapUser.LdapGuid = userPrincipal.Guid;
|
||||
ldapUser.Email = userPrincipal.EmailAddress;
|
||||
ldapUser.AccountLockoutTime = userPrincipal.AccountLockoutTime;
|
||||
|
||||
ldapUser.RoleList = ldapUser.RoleList.Union(JWT.JwtTokenConfig.JwtRoleList).ToList();
|
||||
|
||||
if (ldapUser.RoleList?.Count > 0)
|
||||
{
|
||||
ldapUser = userPrincipal.Context.CheckAndAddGroupMembers(userPrincipal, ldapUser);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
52
HRD.LDAPService/Ldap/LdapExtensions.cs
Normal file
52
HRD.LDAPService/Ldap/LdapExtensions.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
using HRD.LDAPService.JWT;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.DirectoryServices.AccountManagement;
|
||||
using System.Linq;
|
||||
|
||||
namespace HRD.LDAPService
|
||||
{
|
||||
public static class LdapExtensions
|
||||
{
|
||||
public static LdapUser CheckAndAddGroupMembers(this PrincipalContext context, UserPrincipal userPrincipal, LdapUser ldapUser)
|
||||
{
|
||||
if (context == null || userPrincipal == null || ldapUser == null)
|
||||
{
|
||||
throw new Exception($"UserPrincipal failed");
|
||||
}
|
||||
|
||||
if (ldapUser.RoleList?.Count == 0)
|
||||
{
|
||||
ldapUser.RoleList = new List<JwtRole>();
|
||||
return ldapUser;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
List<Principal> userGroupList = userPrincipal.GetGroups().ToList(); // all groups of which the user is a direct member
|
||||
List<JwtRole> jwtRoleList = ldapUser.RoleList; //keep all possible Roles of the user
|
||||
List<JwtRole> fullRoleList = new List<JwtRole>();
|
||||
fullRoleList = fullRoleList.Union(jwtRoleList).ToList(); //add Roles from backend
|
||||
fullRoleList = fullRoleList.Union(JwtTokenConfig.JwtRoleList).ToList(); //add Roles from JwtTokenConfig.JwtRoleList
|
||||
|
||||
ldapUser.RoleList = new List<JwtRole>();
|
||||
|
||||
if (fullRoleList.Count > 0)
|
||||
{
|
||||
foreach (JwtRole jwtRole in jwtRoleList)
|
||||
{
|
||||
if (userGroupList.Exists(userGroup => userGroup.Name == jwtRole.Group))
|
||||
{
|
||||
ldapUser.AddRole(jwtRole.Role);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw ex;
|
||||
}
|
||||
return ldapUser;
|
||||
}
|
||||
}
|
||||
}
|
||||
22
HRD.LDAPService/Ldap/LdapGlobals.cs
Normal file
22
HRD.LDAPService/Ldap/LdapGlobals.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
namespace HRD.LDAPService
|
||||
{
|
||||
public static class LdapGlobals
|
||||
{
|
||||
private static bool _isLive;
|
||||
public static bool LDAP_WebAppGroup_Is_Live { get => _isLive; set => _isLive = value; }
|
||||
|
||||
public const string LDAP_WINDREAM = "Windream_";
|
||||
|
||||
public const string LDAP_DOMAIN = "dhr.local";
|
||||
|
||||
public const string LDAP_PATH_EDM = "OU=DMS,OU=Gruppen,OU=DHDEAB,DC=dhr,DC=local";
|
||||
public const string LDAP_PATH_WEBAPPS = "OU=Web-Apps,OU=Gruppen,OU=DHDEAB,DC=dhr,DC=local";
|
||||
|
||||
public const string LDAP_EDMUser_Prefix = "GG_EDMUser_Group";
|
||||
public const string LDAP_EDMAdmin_Prefix = "GG_EDMAdmin_Group";
|
||||
|
||||
public const string LDAP_EDM_Prefix = "GG_EDM";
|
||||
public const string LDAP_WebAppp_Prefix = "GG_WebApp";
|
||||
public const string LDAP_Prefix_Test = "__Test";
|
||||
}
|
||||
}
|
||||
265
HRD.LDAPService/Ldap/LdapManager.cs
Normal file
265
HRD.LDAPService/Ldap/LdapManager.cs
Normal file
@@ -0,0 +1,265 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.DirectoryServices.AccountManagement;
|
||||
using System.Linq;
|
||||
|
||||
namespace HRD.LDAPService
|
||||
{
|
||||
public static class LdapManager
|
||||
{
|
||||
public static bool AD_AddUserloginToGroup(string userLogin, string group4User)
|
||||
{
|
||||
string groupName = GetFullGroupName(group4User);
|
||||
|
||||
try
|
||||
{
|
||||
using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, LdapGlobals.LDAP_DOMAIN))
|
||||
{
|
||||
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, userLogin);
|
||||
if (userPrincipal == default)
|
||||
{
|
||||
throw new Exception($". Can't find the UserPrincipal by userId:{userLogin}");
|
||||
}
|
||||
List<Principal> userGroupList = userPrincipal.GetGroups().ToList(); // all groups of which the user is a direct member
|
||||
if (userGroupList == default)
|
||||
{
|
||||
throw new Exception($". Can't find the userGroupList; userId:{userLogin}");
|
||||
}
|
||||
|
||||
GroupPrincipal userGroup = userGroupList.Find(x => string.Equals(x.Name, groupName, StringComparison.OrdinalIgnoreCase)) as GroupPrincipal;
|
||||
if (userGroup != default)
|
||||
{
|
||||
return true; //is already here
|
||||
}
|
||||
else
|
||||
{
|
||||
GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, IdentityType.Name, groupName);
|
||||
if (group == default) //try to create a group
|
||||
{
|
||||
if (CreateAdGroup(groupName))
|
||||
{
|
||||
group = GroupPrincipal.FindByIdentity(principalContext, IdentityType.Name, groupName);
|
||||
}
|
||||
}
|
||||
|
||||
if (group == default)
|
||||
{
|
||||
throw new Exception($". Can't create the AD-group: \"{groupName}\"");
|
||||
}
|
||||
group.Members.Add(principalContext, IdentityType.SamAccountName, userLogin);
|
||||
group.Save();
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool CheckAndCreateAdGroup(string adGroupName)
|
||||
{
|
||||
try
|
||||
{
|
||||
// set up domain context and binding to the OU=Web-Apps
|
||||
var adPath = AD_GroupPath(adGroupName);
|
||||
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, LdapGlobals.LDAP_DOMAIN, adPath))
|
||||
{
|
||||
var group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, adGroupName);
|
||||
if (group != null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// create a new group principal, give it a name
|
||||
GroupPrincipal newGroup = new GroupPrincipal(ctx, adGroupName);
|
||||
|
||||
// save the group
|
||||
newGroup.Save();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return false;
|
||||
//throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<string> GetAdUserLoginList4AdGroups(List<string> adGroupNames)
|
||||
{
|
||||
if (adGroupNames == null) { return default; }
|
||||
List<string> result = new List<string>();
|
||||
|
||||
foreach (var adGroupName in adGroupNames)
|
||||
{
|
||||
var list = GetAdUserLoginList4AdGroup(adGroupName);
|
||||
result.AddRange(list);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<string> GetAdUserLoginList4AdGroup(string adGroupName)
|
||||
{
|
||||
try
|
||||
{
|
||||
List<string> result = new List<string>();
|
||||
// set up domain context and binding to the OU=Web-Apps
|
||||
var adPath = AD_GroupPath(adGroupName);
|
||||
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, LdapGlobals.LDAP_DOMAIN, adPath))
|
||||
{
|
||||
var group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, adGroupName);
|
||||
if (group == null)
|
||||
{
|
||||
throw new Exception($". Can't find the AD-group: \"{adGroupName}\"");
|
||||
}
|
||||
|
||||
result = group.Members.Select(x => x.SamAccountName).ToList();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//_logger.LogException(ex, $"An error occurred while getting user for the AD-group {adGroupName}");
|
||||
return default;
|
||||
//throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool CheckAndCreateAdGroups(List<string> adGroupNames)
|
||||
{
|
||||
if (adGroupNames == null) { return false; }
|
||||
|
||||
foreach (var adGroupName in adGroupNames)
|
||||
{
|
||||
if (!CheckAndCreateAdGroup(adGroupName))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool CreateAdGroup(string adGroupName)
|
||||
{
|
||||
try
|
||||
{
|
||||
// set up domain context and binding to the OU=TechWriters organizational unit in your company
|
||||
var adPath = AD_GroupPath(adGroupName);
|
||||
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, LdapGlobals.LDAP_DOMAIN, adPath))
|
||||
{
|
||||
// create a new group principal, give it a name
|
||||
using (GroupPrincipal group = new GroupPrincipal(ctx, adGroupName))
|
||||
{
|
||||
// optionally set additional properties on the newly created group here....
|
||||
|
||||
// save the group
|
||||
group.Save();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
//throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsWindreamADGroup(string adGroupName)
|
||||
{
|
||||
return adGroupName.StartsWith(LdapGlobals.LDAP_EDM_Prefix, StringComparison.InvariantCultureIgnoreCase);
|
||||
}
|
||||
|
||||
public static bool IsWindreamSuffixGroup(string suffixGroupName)
|
||||
{
|
||||
return suffixGroupName.StartsWith(LdapGlobals.LDAP_WINDREAM, StringComparison.InvariantCultureIgnoreCase);
|
||||
}
|
||||
|
||||
public static bool IsWindreamAdminGroup(string suffixGroupName)
|
||||
{
|
||||
return suffixGroupName.StartsWith(LdapGlobals.LDAP_WINDREAM + "Admin", StringComparison.InvariantCultureIgnoreCase);
|
||||
}
|
||||
|
||||
public static bool IsWindreamUserGroup(string suffixGroupName)
|
||||
{
|
||||
return suffixGroupName.StartsWith(LdapGlobals.LDAP_WINDREAM + "User", StringComparison.InvariantCultureIgnoreCase);
|
||||
}
|
||||
|
||||
public static string AD_GroupPath(string adGroupName)
|
||||
{
|
||||
if (IsWindreamADGroup(adGroupName))
|
||||
{
|
||||
return LdapGlobals.LDAP_PATH_EDM;
|
||||
}
|
||||
else
|
||||
{
|
||||
return LdapGlobals.LDAP_PATH_WEBAPPS;
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetFullGroupName(string groupNameSuffix)
|
||||
{
|
||||
//Mapping Windream_User => GG_EDMUser_Group_Live or GG_EDM__Test_User_Group
|
||||
//Mapping Windream_Admin => GG_EDMAdmin_Group or GG_EDM__Test_Admin_Group
|
||||
//Mapping Windream_Technik => GG_EDM_Technik or GG_EDM__Test_Technik
|
||||
|
||||
var testPrefix = !LdapGlobals.LDAP_WebAppGroup_Is_Live ? LdapGlobals.LDAP_Prefix_Test : "";
|
||||
if (IsWindreamAdminGroup(groupNameSuffix))
|
||||
{
|
||||
return LdapGlobals.LDAP_EDMAdmin_Prefix + testPrefix;
|
||||
}
|
||||
else if (IsWindreamUserGroup(groupNameSuffix))
|
||||
{
|
||||
return LdapGlobals.LDAP_EDMUser_Prefix + testPrefix;
|
||||
}
|
||||
else
|
||||
{
|
||||
return (IsWindreamSuffixGroup(groupNameSuffix) ? LdapGlobals.LDAP_EDM_Prefix : LdapGlobals.LDAP_WebAppp_Prefix) + testPrefix + "_" + groupNameSuffix.Replace(LdapGlobals.LDAP_WINDREAM, "");
|
||||
}
|
||||
}
|
||||
|
||||
public static bool AD_RemoveUserFromGroup(string userId, string group4User)
|
||||
{
|
||||
string groupName = GetFullGroupName(group4User);
|
||||
// secure that no windream user or admin can be deleted
|
||||
if (groupName.Equals(LdapGlobals.LDAP_EDMUser_Prefix, StringComparison.CurrentCultureIgnoreCase)
|
||||
|| groupName.Equals(LdapGlobals.LDAP_EDMAdmin_Prefix, StringComparison.CurrentCultureIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
try
|
||||
{
|
||||
using var principalContext = new PrincipalContext(ContextType.Domain, LdapGlobals.LDAP_DOMAIN);
|
||||
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, userId);
|
||||
if (userPrincipal == default)
|
||||
{
|
||||
throw new Exception($". Can't find the UserPrincipal by userId: {userId}");
|
||||
}
|
||||
List<Principal> userGroupList = userPrincipal.GetGroups().ToList(); // all groups of which the user is a direct member
|
||||
if (userGroupList == default)
|
||||
{
|
||||
throw new Exception($". Can't find the userGroupList; userId: {userId}");
|
||||
}
|
||||
|
||||
GroupPrincipal group = userGroupList.Find(x => x.Name == groupName) as GroupPrincipal;
|
||||
if (group == default)
|
||||
{
|
||||
return true; //the user is not in the group - nothing to do more
|
||||
//throw new Exception($". Can't find the AD-group: \"{groupName}\"");
|
||||
}
|
||||
group.Members.Remove(principalContext, IdentityType.SamAccountName, userId);
|
||||
group.Save();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
268
HRD.LDAPService/Ldap/LdapUser.cs
Normal file
268
HRD.LDAPService/Ldap/LdapUser.cs
Normal file
@@ -0,0 +1,268 @@
|
||||
using HRD.LDAPService.JWT;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace HRD.LDAPService
|
||||
{
|
||||
public class LdapUser
|
||||
{
|
||||
private const string PASSWORD_HASH_SHORT = "PasswordHashShort";
|
||||
|
||||
public bool IsRealLDAPUser { get; set; }
|
||||
|
||||
public LdapUser()
|
||||
{
|
||||
}
|
||||
|
||||
public LdapUser(string loginName)
|
||||
{
|
||||
LoginName = loginName;
|
||||
}
|
||||
|
||||
public LdapUser(string loginname, int userId, string password, int departmentId, string extendedDepartmentIdList, List<KeyValuePair<string, string>> extendedAttributesList = null) : base()
|
||||
{
|
||||
LoginName = loginname;
|
||||
UserId = userId;
|
||||
Password = password;
|
||||
DepartmentId = departmentId;
|
||||
ExtendedDepartmentIdList = extendedDepartmentIdList;
|
||||
ExtendedAttributesList = extendedAttributesList == null ? new List<KeyValuePair<string, string>>() : extendedAttributesList;
|
||||
}
|
||||
|
||||
public LdapUser(string loginname, int userId, string password)
|
||||
{
|
||||
LoginName = loginname;
|
||||
UserId = userId;
|
||||
Password = password;
|
||||
}
|
||||
|
||||
#region Ldap Fields
|
||||
|
||||
public Guid? LdapGuid { get; internal set; }
|
||||
public string LdapName { get; set; }
|
||||
public string LdapSurname { get; set; }
|
||||
|
||||
#endregion Ldap Fields
|
||||
|
||||
public int DepartmentId { get; set; }
|
||||
public bool IsValidatCredentials { get; set; }
|
||||
|
||||
public string Email
|
||||
{
|
||||
get; set; // { return $"{LoginName}@hensel-recycling.com"; }
|
||||
}
|
||||
|
||||
public string ExtendedDepartmentIdList { get; set; }
|
||||
public DateTime JwtExpiredOn { get; set; }
|
||||
|
||||
[Required]
|
||||
public string LoginName { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public string Password { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public string PasswordHash { get; set; }
|
||||
|
||||
public List<KeyValuePair<string, string>> ExtendedAttributesList { get; set; } = new List<KeyValuePair<string, string>>();
|
||||
public List<JwtRole> RoleList { get; set; } = new List<JwtRole>();
|
||||
public string Token { get; set; }
|
||||
public int UserId { get; set; }
|
||||
public int BadLogonCount { get; set; }
|
||||
public DateTime? LastBadPasswordAttempt { get; internal set; }
|
||||
|
||||
public string PasswordHashShort
|
||||
{
|
||||
get
|
||||
{
|
||||
if (PasswordHash?.Length <= 10) { return string.Empty; };
|
||||
|
||||
return PasswordHash.Substring(PasswordHash.Length - 10);
|
||||
}
|
||||
}
|
||||
|
||||
public string GetLastBadPasswordAttemptAsLocalTime()
|
||||
{
|
||||
if (LastBadPasswordAttempt == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return ((DateTime)LastBadPasswordAttempt).ToLocalTime().ToLongTimeString();
|
||||
}
|
||||
|
||||
public void AddPasswordHash(string passwordHash)
|
||||
{
|
||||
PasswordHash = passwordHash;
|
||||
|
||||
if (!ExistsExtendedAttributeValue(PASSWORD_HASH_SHORT))
|
||||
{
|
||||
AddExtendedAttribute(PASSWORD_HASH_SHORT, PasswordHashShort);
|
||||
}
|
||||
}
|
||||
|
||||
public string GetExtendedAttributePasswordHash()
|
||||
{
|
||||
return GetExtendedAttributeValue(PASSWORD_HASH_SHORT);
|
||||
}
|
||||
|
||||
public bool ExistsExtendedAttributeValue(string key)
|
||||
{
|
||||
foreach (var item in ExtendedAttributesList)
|
||||
{
|
||||
if (item.Key == key) { return true; }
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public string GetExtendedAttributeValue(string key)
|
||||
{
|
||||
foreach (var item in ExtendedAttributesList)
|
||||
{
|
||||
if (item.Key == key) { return item.Value; }
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
public string GetAccountLockoutTimeAsLocalTime()
|
||||
{
|
||||
if (AccountLockoutTime == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return ((DateTime)AccountLockoutTime).ToLocalTime().ToLongTimeString();
|
||||
}
|
||||
|
||||
public bool IsAccountLockedOut { get; internal set; }
|
||||
public DateTime? AccountLockoutTime { get; internal set; }
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
public static bool IsJwtGlobalsRole(string roleName)
|
||||
{
|
||||
return string.Equals(roleName, JwtGlobals.ROLE_USER, StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(roleName, JwtGlobals.ROLE_DEPARTMENTUSER, StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(roleName, JwtGlobals.ROLE_DEPARTMENTMASTER, StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(roleName, JwtGlobals.ROLE_MASTER, StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(roleName, JwtGlobals.ROLE_ADMIN, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public void AddExtendedAttribute(string key, string value)
|
||||
{
|
||||
ExtendedAttributesList.Add(new KeyValuePair<string, string>(key, value));
|
||||
}
|
||||
|
||||
public void AddRole(JwtRole jwtRole)
|
||||
{
|
||||
if (!RoleList.Exists(x => x.Role == jwtRole.Role && x.Group == jwtRole.Group))
|
||||
{
|
||||
RoleList.Add(jwtRole);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddRole(string role)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(role) && !RoleList.Exists(x => x.Role == role))
|
||||
{
|
||||
RoleList.Add(new JwtRole(role));
|
||||
}
|
||||
}
|
||||
|
||||
public List<int> DepartmentIdListAll()
|
||||
{
|
||||
List<int> list = new List<int>() { DepartmentId };
|
||||
|
||||
if (!string.IsNullOrEmpty(ExtendedDepartmentIdList))
|
||||
{
|
||||
List<int> extendetList = ExtendedDepartmentIdList.Split(',').Select(x => int.Parse(x.Trim())).ToList();
|
||||
|
||||
list = list.Union(extendetList).ToList();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public bool IsAdmin()
|
||||
{
|
||||
return IsExistsRole(JwtGlobals.ROLE_ADMIN);
|
||||
}
|
||||
|
||||
public bool IsDepartmentMaster()
|
||||
{
|
||||
return IsExistsRole(JwtGlobals.ROLE_DEPARTMENTMASTER);
|
||||
}
|
||||
|
||||
public bool IsDepartmentUser()
|
||||
{
|
||||
return IsExistsRole(JwtGlobals.ROLE_DEPARTMENTUSER);
|
||||
}
|
||||
|
||||
public bool IsExistsRole(string role)
|
||||
{
|
||||
return RoleList.Exists(x => String.Equals(x.Role, role, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
public bool IsMaster()
|
||||
{
|
||||
return IsExistsRole(JwtGlobals.ROLE_MASTER);
|
||||
}
|
||||
|
||||
public bool IsUser()
|
||||
{
|
||||
return IsExistsRole(JwtGlobals.ROLE_USER);
|
||||
}
|
||||
|
||||
public bool IsValid()
|
||||
{
|
||||
if (IsRealLDAPUser)
|
||||
{
|
||||
return !string.IsNullOrEmpty(LoginName)
|
||||
//&& RoleList.Count > 0
|
||||
&& (LdapGuid != null)
|
||||
&& Enabled
|
||||
&& IsValidatCredentials;
|
||||
}
|
||||
else
|
||||
{
|
||||
return !string.IsNullOrEmpty(LoginName)
|
||||
&& Enabled
|
||||
&& IsValidatCredentials;
|
||||
}
|
||||
}
|
||||
|
||||
public string RoleListAsString(EN_LdapRoleListFilter filter = EN_LdapRoleListFilter.All)
|
||||
{
|
||||
List<string> resultList = new List<string>();
|
||||
foreach (var item in RoleList)
|
||||
{
|
||||
switch (filter)
|
||||
{
|
||||
case EN_LdapRoleListFilter.All:
|
||||
resultList.Add(item.Role);
|
||||
break;
|
||||
|
||||
case EN_LdapRoleListFilter.OnlyRoleList:
|
||||
if (IsJwtGlobalsRole(item.Role)) { resultList.Add(item.Role); }
|
||||
break;
|
||||
|
||||
case EN_LdapRoleListFilter.OnlyWebAppRoleList:
|
||||
if (!IsJwtGlobalsRole(item.Role)) { resultList.Add(item.Role); }
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return string.Join(",", resultList);
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"{this.LoginName}; Roles: {RoleList.Count}; ExtendedDepartmentIdList: {ExtendedDepartmentIdList}, ExtendedAttributesList: {ExtendedAttributesList} ";
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user