refactor: Projektdateien migriert. Cloud-NuGet-Pakete durch lokale NuGet-Projekte ersetzt.

This commit is contained in:
Developer 02 2024-08-01 18:44:39 +02:00
parent 0d82f7af6f
commit 62ddd4873f
206 changed files with 10927 additions and 1 deletions

4
.editorconfig Normal file
View File

@ -0,0 +1,4 @@
[*.cs]
# CA1707: Identifiers should not contain underscores
dotnet_diagnostic.CA1707.severity = silent

14
DAL/DAL.csproj Normal file
View File

@ -0,0 +1,14 @@
 <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Version>2.3.7</Version>
<AssemblyVersion>2.3.7.0</AssemblyVersion>
<FileVersion>2.3.7.0</FileVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\HRD.LDAPService\HRD.LDAPService.csproj" />
<ProjectReference Include="..\HRD.WebApi\HRD.WebApi.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,26 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class AdWebAppToWebAppRole : BaseEntity
{
public int AdWebAppToWebAppRoleId { get; set; }
public int WebAppId { get; set; }
public string AdWebAppName { get; set; }
public string AdWebAppRoleName { get; set; }
public string GetAdGrupSuffix()
{
return $"{AdWebAppName}_{AdWebAppRoleName}";
}
//generic Id
public override int GetEntityId() => AdWebAppToWebAppRoleId;
//generic ToString()
public override string ToString() => $"AdWebAppToWebAppRoleId: {GetEntityId()}; AdWebAppRoleName: {AdWebAppRoleName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,20 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class CostCentre : BaseEntity
{
public int CostCentreId { get; set; }
public string CostCentreName { get; set; }
public int SortOrder { get; set; }
//generic Id
public override int GetEntityId() => CostCentreId;
//generic ToString()
public override string ToString() => $"CostCentreId: {GetEntityId()}; Name: {CostCentreName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,41 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class Department : BaseEntity
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public int CostCentreId { get; set; }
public int DepartmentTypeId { get; set; }
public int? HeadofDepartmentId { get; set; }
public int? ExecutiveDirectorId { get; set; }
public int? ManagingDirectorId { get; set; }
public string DepartmentNameFolder { get; set; }
public string AdGroupDepartmentName { get; set; }
public int? ClientId { get; set; }
public bool IsVirtual { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string CostCentre { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string HeadofDepartment { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string ExecutiveDirector { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string ManagingDirector { get; set; }
//generic Id
public override int GetEntityId() => DepartmentId;
//generic ToString()
public override string ToString() => $"DepartmentId: {GetEntityId()}; Name: {DepartmentName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,25 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class DepartmentToWebAppToEmployeeForWindream : BaseEntity
{
public int DepartmentToWebAppToEmployeeForWindreamId { get; set; }
public int EmployeeId { get; set; }
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public string ShortName { get; set; }
public string LoginName { get; set; }
public int IsMain { get; set; }
public int? ClientId { get; set; }
//generic Id
public override int GetEntityId() => DepartmentToWebAppToEmployeeForWindreamId;
//generic ToString()
public override string ToString() => $"DepartmentToWebAppToEmployeeForWindreamId: {GetEntityId()}; EmployeeId: {EmployeeId}; DepartmentId: {DepartmentId}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,28 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class DocumentArt : BaseEntity
{
public int DocumentArtId { get; set; }
public string Name { get; set; }
public string Shortname { get; set; }
public string RootPath { get; set; }
public string Folder { get; set; }
public string Comment { get; set; }
public int ClientId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DepartmentNamesList { get; set; }
//generic Id
public override int GetEntityId() => DocumentArtId;
//generic ToString()
public override string ToString() => $"DocumentArtId: {GetEntityId()}; Name: {Name}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,32 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class DocumentArtToDepartment : BaseEntity
{
public int DocumentArtToDepartmentId { get; set; }
public int DepartmentId { get; set; }
public int DocumentArtId { get; set; }
public bool IsActive { get; set; }
public bool? UseGlobix { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DocumentArtName { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DocumentArtShortname { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DocumentArtFolder { get; set; }
//generic Id
public override int GetEntityId() => DocumentArtToDepartmentId;
//generic ToString()
public override string ToString() => $"DocumentArtToDepartmentId: {GetEntityId()}; DepartmentId : {DepartmentId}; DocumentArtId : {DocumentArtId}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,58 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class Employee : BaseEntity
{
public int EmployeeId { get; set; }
public string EmployeeNo { get; set; }
public string Salutation { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ShortName { get; set; }
public string Title { get; set; }
public string Position { get; set; }
public string LoginName { get; set; }
public string Email { get; set; }
public int? RangId { get; set; }
public int ClientId { get; set; }
public bool? IsActive { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string MandantCode { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int? MainDepartmentId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DepartmentNamesList { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DepartmentIdList { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WebappNamesList { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WebappIdList { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string AttributeNamesList { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string AttributeIdList { get; set; }
public string MobilePhoneNo { get; set; }
public string PhoneNo { get; set; }
//generic Id
public override int GetEntityId() => EmployeeId;
//generic ToString()
public override string ToString() => $"EmployeeId: {GetEntityId()}; LoginName: {LoginName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,22 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class EmployeeAttribute : BaseEntity
{
public int EmployeeAttributeId { get; set; }
public string Name { get; set; }
public string Shortname { get; set; }
public string RoleList { get; set; }
public int? SeqNo { get; set; }
//generic Id
public override int GetEntityId() => EmployeeAttributeId;
//generic ToString()
public override string ToString() => $"EmployeeAttributeId: {GetEntityId()}; Name: {Name}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,19 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class EmployeeStatus : BaseEntity
{
public int EmployeeStatusId { get; set; }
public string EmployeeStatusName { get; set; }
//generic Id
public override int GetEntityId() => EmployeeStatusId;
//generic ToString()
public override string ToString() => $"EmployeeStatusId: {GetEntityId()}; Name: {EmployeeStatusName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,21 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class EmployeeToAttribute : BaseEntity
{
public int EmployeeToAttributeId { get; set; }
public int EmployeeId { get; set; }
public int EmployeeAttributeId { get; set; }
//generic Id
public override int GetEntityId() => EmployeeToAttributeId;
//generic ToString()
public override string ToString() => $"EmployeeToAttributeId: {GetEntityId()}; EmployeeId: {EmployeeId}; EmployeeAttributeId: {EmployeeAttributeId}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,29 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class EmployeeToDepartment : BaseEntity
{
public int EmployeeToDepartmentId { get; set; }
public int EmployeeId { get; set; }
public int DepartmentId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DepartmentName { get; set; }
public decimal EmployeeBudget { get; set; }
public int? EmployeeStatusId { get; set; }
public int? RangId { get; set; }
//generic Id
public override int GetEntityId() => EmployeeToDepartmentId;
//generic ToString()
public override string ToString() => $"EmployeeToDepartmentId: {GetEntityId()}; EmployeeId: {EmployeeId}; DepartmentId: {DepartmentId}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,45 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class EmployeeToWebApp : BaseEntity
{
public int EmployeeToWebAppId { get; set; }
public int EmployeeId { get; set; }
public int WebAppId { get; set; }
public int WebAppRoleId { get; set; }
public int? DepartmentId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WebAppRoleName { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WebAppName { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DepartmentName { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string ExtendedDepartmentNameList { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string ExtendedDepartmentIdList { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string AdditionalRoleNameList { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string AdditionalRoleIdList { get; set; }
//generic Id
public override int GetEntityId() => EmployeeToWebAppId;
//generic ToString()
public override string ToString() => $"EmployeeToWebAppId: {GetEntityId()}; EmployeeId: {EmployeeId}; WebAppId: {WebAppId}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,19 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class Project : BaseEntity
{
public int ProjectId { get; set; }
public string ProjectName { get; set; }
//generic Id
public override int GetEntityId() => ProjectId;
//generic ToString()
public override string ToString() => $"ProjectId: {GetEntityId()}; Name: {ProjectName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,21 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class Rang : BaseEntity
{
public int RangId { get; set; }
public string RangName { get; set; }
public string RangShortname { get; set; }
public int RangOrder { get; set; }
//generic Id
public override int GetEntityId() => RangId;
//generic ToString()
public override string ToString() => $"RangId: {GetEntityId()}; Name: {RangName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,25 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class Subsidiary : BaseEntity
{
public int SubsidiaryId { get; set; }
public int? ClientId { get; set; }
public string Name { get; set; }
public string SubsidiaryCode { get; set; }
public string Comment { get; set; }
// [NotMapped]
// [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
//generic Id
public override int GetEntityId() => SubsidiaryId;
//generic ToString()
public override string ToString() => $"SubsidiaryId: {GetEntityId()}; Name: {Name}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,23 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class WebApp : BaseEntity
{
public int WebAppId { get; set; }
public string WebAppName { get; set; }
public string WebAppLinkLive { get; set; }
public string WebAppLinkDev { get; set; }
public bool IsActive { get; set; }
public string AdWebAppName { get; set; }
//generic Id
public override int GetEntityId() => WebAppId;
//generic ToString()
public override string ToString() => $"WebAppId: {GetEntityId()}; Name: {WebAppName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,21 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class WebAppAdditionalRole : BaseEntity
{
public int WebAppAdditionalRoleId { get; set; }
public int WebAppId { get; set; }
public string WebAppAdditionalRoleName { get; set; }
public string AdWebAppAdditionalRoleName { get; set; }
//generic Id
public override int GetEntityId() => WebAppAdditionalRoleId;
//generic ToString()
public override string ToString() => $"WebAppAdditionalRoleId: {GetEntityId()}; WebAppId: {WebAppId}; WebAppAdditionalRoleName: {WebAppAdditionalRoleName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,20 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class WebAppRole : BaseEntity
{
public int WebAppRoleId { get; set; }
public string WebAppRoleName { get; set; }
public int WebAppRoleHierarchy { get; set; }
//generic Id
public override int GetEntityId() => WebAppRoleId;
//generic ToString()
public override string ToString() => $"WebAppRoleId: {GetEntityId()}; WebAppRoleName: {WebAppRoleName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,24 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class WebAppToDepartment : BaseEntity
{
public int WebAppToDepartmentId { get; set; }
public int EmployeeToWebAppId { get; set; }
public int DepartmentId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DepartmentName { get; set; }
//generic Id
public override int GetEntityId() => WebAppToDepartmentId;
//generic ToString()
public override string ToString() => $"WebAppToDepartmentId: {GetEntityId()}; EmployeeToWebAppId: {EmployeeToWebAppId}; DepartmentId: {DepartmentId}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,20 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class WebAppToWebAppAdditionalRole : BaseEntity
{
public int WebAppToWebAppAdditionalRoleId { get; set; }
public int WebAppAdditionalRoleId { get; set; }
public int EmployeeToWebAppId { get; set; }
//generic Id
public override int GetEntityId() => WebAppToWebAppAdditionalRoleId;
//generic ToString()
public override string ToString() => $"WebAppToWebAppAdditionalRoleId: {GetEntityId()}; WebAppAdditionalRoleId: {WebAppAdditionalRoleId}; EmployeeToWebAppId: {EmployeeToWebAppId}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,27 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class WebAppToWebAppRole : BaseEntity
{
public int WebAppToWebAppRoleId { get; set; }
public int WebAppId { get; set; }
public int WebAppRoleId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WebAppRoleName { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int WebAppRoleHierarchy { get; set; }
//generic Id
public override int GetEntityId() => WebAppToWebAppRoleId;
//generic ToString()
public override string ToString() => $"WebAppToWebAppRoleId: {GetEntityId()}; WebAppId: {WebAppId}; WebAppRoleId: {WebAppRoleId}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,33 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class WindreamColumnsToDepartment : BaseEntity
{
public int WindreamColumnsToDepartmentId { get; set; }
public int AttributeDwAttrId { get; set; }
public string AttributeSzColumnName { get; set; }
public string Comment { get; set; }
public int AttributeDwAttrType { get; set; }
public int ComumnLength { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string ObjectTypeAttributeSzName { get; set; }
public int ClientId { get; set; }
public string ObjectTypeszDocTypeName { get; set; }
public int DepartmentId { get; set; }
public int Seq { get; set; }
public int WindreamSearchId { get; set; }
//generic Id
public override int GetEntityId() => WindreamColumnsToDepartmentId;
//generic ToString()
public override string ToString() => $"WindreamColumnsToDepartmentId: {GetEntityId()}; AttributeSzColumnName: {AttributeSzColumnName}; DepartmentId: {DepartmentId}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,25 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class WindreamIndex : BaseEntity
{
public int WindreamIndexId { get; set; }
public int AttributeDwAttrId { get; set; }
public string AttributeSzColumnName { get; set; }
public string Comment { get; set; }
public int? ComumnLength { get; set; }
public int? AttributeDwAttrType { get; set; }
public int ClientId { get; set; }
public string ObjectTypeAttributeSzName { get; set; }
//generic Id
public override int GetEntityId() => WindreamIndexId;
//generic ToString()
public override string ToString() => $"WindreamIndexId: {GetEntityId()}; AttributeSzColumnName: {AttributeSzColumnName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,28 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class WindreamIndexToWindreamSearchToDepartment : BaseEntity
{
public int WindreamIndexToWindreamSearchToDepartmentId { get; set; }
public int WindreamSearchToDepartmentId { get; set; }
public int WindreamIndexId { get; set; }
public int Seq { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string AttributeSzColumnName { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string ObjectTypeAttributeSzName { get; set; }
//generic Id
public override int GetEntityId() => WindreamIndexToWindreamSearchToDepartmentId;
//generic ToString()
public override string ToString() => $"WindreamIndexToWindreamSearchToDepartmentId: {GetEntityId()}; WindreamSearchToDepartmentId: {WindreamSearchToDepartmentId}; AttributeSzColumnName: {AttributeSzColumnName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,22 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class WindreamInputFolder : BaseEntity
{
public int WindreamInputFolderId { get; set; }
public string Name { get; set; }
public string XMLPath { get; set; }
public string Comment { get; set; }
public int? ClientId { get; set; }
//generic Id
public override int GetEntityId() => WindreamInputFolderId;
//generic ToString()
public override string ToString() => $"WindreamInputFolderId: {GetEntityId()}; Name: {Name}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,24 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Entities
{
public partial class WindreamSearch : BaseEntity
{
public int WindreamSearchId { get; set; }
public string Name { get; set; }
public string XMLPath { get; set; }
public string Comment { get; set; }
public int ClientId { get; set; }
public int? Color { get; set; }
public int? SearchIndex { get; set; }
//generic Id
public override int GetEntityId() => WindreamSearchId;
//generic ToString()
public override string ToString() => $"WindreamSearchId: {GetEntityId()}; Name: {Name}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,30 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class WindreamSearchItem : BaseEntity
{
public int WindreamSearchItemId { get; set; }
public string Name { get; set; }
public string Comment { get; set; }
public int ClientId { get; set; }
public string Caption { get; set; }
public string PlaceHolder { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string SearchTemplate { get; set; }
public string ConnectedList { get; set; }
public string AlternativeWindreamSearchItemIdList { get; set; }
//generic Id
public override int GetEntityId() => WindreamSearchItemId;
//generic ToString()
public override string ToString() => $"WindreamSearchItemId: {GetEntityId()}; Name: {Name}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,49 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class WindreamSearchItemToWindreamSearchToDepartment : BaseEntity
{
public int WindreamSearchItemToWindreamSearchToDepartmentId { get; set; }
public int WindreamSearchToDepartmentId { get; set; }
public int Seq { get; set; }
public int WindreamSearchItemId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int DepartmentId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WindreamSearchItemName { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WindreamSearchItemCaption { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WindreamSearchItemPlaceHolder { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WindreamSearchItemSearchTemplate { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WindreamSearchItemTemplate { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WindreamSearchItemConnectedList { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WindreamSearchItemComment { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int? WindreamSearchIndexType { get; set; }
//generic Id
public override int GetEntityId() => WindreamSearchItemToWindreamSearchToDepartmentId;
//generic ToString()
public override string ToString() => $"WindreamSearchItemToWindreamSearchToDepartmentId: {GetEntityId()}; WindreamSearchToDepartmentId: {WindreamSearchToDepartmentId}; WindreamSearchItemName: {WindreamSearchItemName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,38 @@
using HRD.WebApi.DAL;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models.Entities
{
public partial class WindreamSearchToDepartment : BaseEntity
{
public int WindreamSearchToDepartmentId { get; set; }
public int DepartmentId { get; set; }
public int WindreamSearchId { get; set; }
public int Seq { get; set; }
public bool IsActive { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string DepartmentName { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WindreamSearchName { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WindreamSearchXMLPath { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WindreamSearchComment { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int? WindreamSearchColor { get; set; }
//generic Id
public override int GetEntityId() => WindreamSearchToDepartmentId;
//generic ToString()
public override string ToString() => $"WindreamSearchToDepartmentId: {GetEntityId()}; DepartmentName: {DepartmentName}; WindreamSearchName: {WindreamSearchName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,9 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Filters
{
public partial class ClientIdFilter : BaseFilter
{
public int? ClientId { get; set; }
}
}

View File

@ -0,0 +1,10 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Filters
{
public partial class DepartmentFilter : BaseFilter
{
public int? DepartmentId { get; set; }
public int? WindreamSearchId { get; set; }
}
}

View File

@ -0,0 +1,9 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Filters
{
public partial class DepartmentFullFilter : BaseFilter
{
public string DepartmentName { get; set; }
}
}

View File

@ -0,0 +1,11 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Filters
{
public partial class EmployeeFilter : BaseFilter
{
public int? EmployeeId { get; set; }
public string LoginName { get; set; }
public string ShortName { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Filters
{
public partial class EmployeeFullFilter : BaseFilter
{
public int? EmployeeId { get; set; }
public string Name { get; set; }
public string ShortName { get; set; }
public string LoginName { get; set; }
public string Email { get; set; }
public int[] WebappIds { get; set; }
public int[] DepartmentIds { get; set; }
public int[] AttributeIds { get; set; }
public int? ClientId { get; set; }
public bool? IsActive { get; set; }
}
}

View File

@ -0,0 +1,9 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Filters
{
public partial class EmployeeToWebAppFilter : BaseFilter
{
public int? EmployeeToWebAppId { get; set; }
}
}

View File

@ -0,0 +1,9 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Filters
{
public partial class WebAppFilter : BaseFilter
{
public int? WebAppId { get; set; }
}
}

View File

@ -0,0 +1,10 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Filters
{
public partial class WindreamInputFolderFilter : BaseFilter
{
public int? WindreamInputFolderId { get; set; }
public int? ClientId { get; set; }
}
}

View File

@ -0,0 +1,10 @@
using HRD.WebApi.DAL;
namespace DAL.Models.Filters
{
public partial class WindreamSearchToDepartmentFilter : BaseFilter
{
public int? WindreamSearchToDepartmentId { get; set; }
public int? DepartmentId { get; set; }
}
}

View File

@ -0,0 +1,12 @@
using DAL.Models.Entities;
using HRD.WebApi.Repositories;
namespace DAL.Repositories
{
public class AdWebAppToWebAppRoleRepository : BaseRepository<AdWebAppToWebAppRole>
{
public AdWebAppToWebAppRoleRepository() : base(new WebApiContext())
{
}
}
}

View File

@ -0,0 +1,12 @@
using DAL.Models.Entities;
using HRD.WebApi.Repositories;
namespace DAL.Repositories
{
public class CostCentreRepository : BaseRepository<CostCentre>
{
public CostCentreRepository() : base(new WebApiContext())
{
}
}
}

View File

@ -0,0 +1,34 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class DepartmentRepository : BaseRepository<Department>
{
public DepartmentRepository() : base(new WebApiContext())
{
}
public async Task<List<Department>> GetDepartmentListAsync(DepartmentFullFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<Department>().AsQueryable();
if (!string.IsNullOrEmpty(filter.DepartmentName))
{
items = items.Where(x => EF.Functions.Like(x.DepartmentName, $"%{filter.DepartmentName}%"));
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
public async Task<bool> ReplaceWindreamTiles(int srcDepartmentId, string trgDepartmentIds)
{
return await ExecStoredProcedureAsync("webapi.sp_TransferWindreamSettings", $"{srcDepartmentId}, null, \"{trgDepartmentIds}\"");
}
}
}

View File

@ -0,0 +1,40 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class DepartmentToWebAppToEmployeeForWindreamRepository : BaseRepository<DepartmentToWebAppToEmployeeForWindream>
{
public DepartmentToWebAppToEmployeeForWindreamRepository() : base(new WebApiContext())
{
}
public async Task<List<DepartmentToWebAppToEmployeeForWindream>> GetListByFilterAsync(EmployeeFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<DepartmentToWebAppToEmployeeForWindream>().AsQueryable();
if (filter.EmployeeId != null && filter.EmployeeId != 0)
{
items = items.Where(x => x.EmployeeId == filter.EmployeeId);
return asNoTracking ? await items.ToListAsync() : await items.ToListAsync();
}
if (!string.IsNullOrEmpty(filter.ShortName))
{
items = items.Where(x => x.ShortName == filter.ShortName);
}
if (!string.IsNullOrEmpty(filter.LoginName))
{
items = items.Where(x => x.LoginName.ToLower() == filter.LoginName.ToLower());
}
return asNoTracking ? await items.OrderBy(x => x.DepartmentName).AsNoTracking().ToListAsync() : await items.OrderBy(x => x.DepartmentName).ToListAsync();
}
}
}

View File

@ -0,0 +1,12 @@
using DAL.Models.Entities;
using HRD.WebApi.Repositories;
namespace DAL.Repositories
{
public class DocumentArtRepository : BaseRepository<DocumentArt>
{
public DocumentArtRepository() : base(new WebApiContext())
{
}
}
}

View File

@ -0,0 +1,29 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class DocumentArtToDepartmentRepository : BaseRepository<DocumentArtToDepartment>
{
public DocumentArtToDepartmentRepository() : base(new WebApiContext())
{
}
public async Task<List<DocumentArtToDepartment>> GetListByFilterAsync(DepartmentFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<DocumentArtToDepartment>().AsQueryable();
if (filter.DepartmentId != null && filter.DepartmentId != 0)
{
items = items.Where(x => x.DepartmentId == filter.DepartmentId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
}
}

View File

@ -0,0 +1,12 @@
using DAL.Models.Entities;
using HRD.WebApi.Repositories;
namespace DAL.Repositories
{
public class EmployeeAttributeRepository : BaseRepository<EmployeeAttribute>
{
public EmployeeAttributeRepository() : base(new WebApiContext())
{
}
}
}

View File

@ -0,0 +1,96 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class EmployeeRepository : BaseRepository<Employee>
{
public EmployeeRepository() : base(new WebApiContext())
{
}
public async Task<List<Employee>> GetListByFilterAsync(EmployeeFullFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<Employee>().AsQueryable();
if (filter.EmployeeId != null && filter.EmployeeId != 0)
{
items = items.Where(x => x.EmployeeId == filter.EmployeeId);
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
if (!string.IsNullOrEmpty(filter.Name))
{
items = items.Where(x => EF.Functions.Like(x.FirstName.ToLower() + ' ' + x.LastName.ToLower(), $"%{filter.Name.ToLower()}%"));
}
if (!string.IsNullOrEmpty(filter.Email))
{
items = items.Where(x => EF.Functions.Like(x.Email.ToLower(), $"%{filter.Email.ToLower()}%"));
}
if (!string.IsNullOrEmpty(filter.ShortName))
{
items = items.Where(x => EF.Functions.Like(x.ShortName.ToLower(), $"%{filter.ShortName.ToLower()}%"));
}
if (!string.IsNullOrEmpty(filter.LoginName))
{
items = items.Where(x => EF.Functions.Like(x.LoginName.ToLower(), $"%{filter.LoginName.ToLower()}%"));
}
if (filter.DepartmentIds != null && filter.DepartmentIds.Length > 0)
{
IQueryable<Employee> itemsTmp = null;
for (int i = 0; i < filter.DepartmentIds.Length; i++)
{
var inx = filter.DepartmentIds[i];
var items_ = items.Where(x => EF.Functions.Like("," + x.DepartmentIdList.Replace(" ", "") + ",", $"%,{inx},%"));
itemsTmp = itemsTmp != null ? itemsTmp.Union(items_) : items_;
}
items = itemsTmp;
}
if (filter.WebappIds != null && filter.WebappIds.Length > 0)
{
IQueryable<Employee> itemsTmp = null;
for (int i = 0; i < filter.WebappIds.Length; i++)
{
var inx = filter.WebappIds[i];
var items_ = items.Where(x => EF.Functions.Like("," + x.WebappIdList.Replace(" ", "") + ",", $"%,{inx},%"));
itemsTmp = (itemsTmp != null) ? itemsTmp.Union(items_) : items_;
}
items = itemsTmp;
}
if (filter.AttributeIds != null && filter.AttributeIds.Length > 0)
{
IQueryable<Employee> itemsTmp = null;
for (int i = 0; i < filter.AttributeIds.Length; i++)
{
var inx = filter.AttributeIds[i];
var items_ = items.Where(x => EF.Functions.Like("," + x.AttributeIdList.Replace(" ", "") + ",", $"%,{inx},%"));
itemsTmp = (itemsTmp != null) ? itemsTmp.Concat(items_) : items_;
}
items = itemsTmp;
}
if (filter.ClientId != null && filter.ClientId != 0)
{
items = items.Where(x => x.ClientId == filter.ClientId);
}
if (filter.IsActive != null)
{
items = items.Where(x => x.IsActive == filter.IsActive);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
}
}

View File

@ -0,0 +1,12 @@
using DAL.Models.Entities;
using HRD.WebApi.Repositories;
namespace DAL.Repositories
{
public class EmployeeStatusRepository : BaseRepository<EmployeeStatus>
{
public EmployeeStatusRepository() : base(new WebApiContext())
{
}
}
}

View File

@ -0,0 +1,29 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class EmployeeToAttributeRepository : BaseRepository<EmployeeToAttribute>
{
public EmployeeToAttributeRepository() : base(new WebApiContext())
{
}
public async Task<List<EmployeeToAttribute>> GetListByFilterAsync(EmployeeFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<EmployeeToAttribute>().AsQueryable();
if (filter.EmployeeId != null && filter.EmployeeId != 0)
{
items = items.Where(x => x.EmployeeId == filter.EmployeeId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
}
}

View File

@ -0,0 +1,29 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class EmployeeToDepartmentRepository : BaseRepository<EmployeeToDepartment>
{
public EmployeeToDepartmentRepository() : base(new WebApiContext())
{
}
public async Task<List<EmployeeToDepartment>> GetListByFilterAsync(EmployeeFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<EmployeeToDepartment>().AsQueryable();
if (filter.EmployeeId != null && filter.EmployeeId != 0)
{
items = items.Where(x => x.EmployeeId == filter.EmployeeId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
}
}

View File

@ -0,0 +1,253 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.LDAPService;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class EmployeeToWebAppRepository : BaseRepository<EmployeeToWebApp>
{
public EmployeeToWebAppRepository() : base(new WebApiContext())
{
}
public async Task<bool> DeleteEmloyeeToWebAppAsync(int webAppId)
{
var list = await GetListByAsync(x => x.WebAppId == webAppId);
foreach (var item in list)
{
if (!await DeleteByIdAsync(item.EmployeeId))
{
throw new Exception($"Couldn't delete the Employee-Id: {item.EmployeeId}");
}
}
return true;
}
public async Task<List<EmployeeToWebApp>> GetListByFilterAsync(EmployeeFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<EmployeeToWebApp>().AsQueryable();
if (filter.EmployeeId != null && filter.EmployeeId != 0)
{
items = items.Where(x => x.EmployeeId == filter.EmployeeId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
private async Task<bool> AddUserToAdGroup(EmployeeToWebApp entity, int webRoleId, int? departementId)
{
return await ProcessGroup(entity, "adding", webRoleId, departementId);
}
private async Task<bool> RemoveUserFromAdGroup(EmployeeToWebApp entity, int webRoleId, int? departementId)
{
return await ProcessGroup(entity, "deleting", webRoleId, departementId);
}
private async Task<bool> ProcessGroup(EmployeeToWebApp entity, string action, int webRoleId, int? departementId)
{
string groupSuffix = null;
if (entity == default) throw new ArgumentNullException(nameof(entity));
if (entity == default) throw new ArgumentNullException(nameof(entity));
var department = await GetDepartmentById(departementId);
var employee = await GetEmployeeById(entity.EmployeeId);
if (employee == default) throw new ArgumentNullException(nameof(employee));
var webapp = await GetWebAppById(entity.WebAppId);
if (webapp == default) throw new ArgumentNullException(nameof(webapp));
bool result = true;
var isAdding = action == "adding";
var webappRole = await GetWebAppRoleById(webRoleId);
try
{
if (department != default && !string.IsNullOrEmpty(department.AdGroupDepartmentName))
{
groupSuffix = $"{webapp.AdWebAppName}_{department.AdGroupDepartmentName}";
if (LdapManager.IsWindreamSuffixGroup(groupSuffix))
{
if (isAdding) result = LdapManager.AD_AddUserloginToGroup(employee.LoginName, groupSuffix);
else result = LdapManager.AD_RemoveUserFromGroup(employee.LoginName, groupSuffix);
}
}
if (webappRole != default)
{
groupSuffix = $"{webapp.AdWebAppName}_{webappRole.WebAppRoleName}";
if (isAdding) result = LdapManager.AD_AddUserloginToGroup(employee.LoginName, groupSuffix);
else result = LdapManager.AD_RemoveUserFromGroup(employee.LoginName, groupSuffix);
if (LdapManager.IsWindreamAdminGroup(groupSuffix))
{
groupSuffix = $"{webapp.AdWebAppName}_User";
if (isAdding) result = LdapManager.AD_AddUserloginToGroup(employee.LoginName, groupSuffix);
else result = LdapManager.AD_RemoveUserFromGroup(employee.LoginName, groupSuffix);
}
}
}
catch (Exception ex)
{
WriteLogException(ex, $"An error occurred while '{action}' the '{employee.LoginName}' into '{groupSuffix}'.");
return false;
}
if (!result)
{
WriteLogError($"An error occurred while '{action}' the '{employee.LoginName}' into '{groupSuffix}'.");
return false;
};
return true;
}
public override async Task<bool> UpdateAsync(EmployeeToWebApp entity, bool saveEntity = true)
{
if (entity == default)
{
throw new ArgumentNullException(nameof(entity));
}
var orgEntity = await base.GetByIdAsync(entity.EmployeeToWebAppId, true);
var oldWebAppRoleId = 0;
var newWebAppRoleId = 0;
if (orgEntity.WebAppRoleId != entity.WebAppRoleId)
{
oldWebAppRoleId = orgEntity.WebAppRoleId;
newWebAppRoleId = entity.WebAppRoleId;
}
int? oldDepartmentId = 0;
int? newDepartmentId = 0;
if (orgEntity.DepartmentId != entity.DepartmentId)
{
oldDepartmentId = orgEntity.DepartmentId;
newDepartmentId = entity.DepartmentId;
}
orgEntity = null;
if ((oldDepartmentId == 0 && oldWebAppRoleId == 0) ||
await RemoveUserFromAdGroup(entity, oldWebAppRoleId, oldDepartmentId)
&& await AddUserToAdGroup(entity, newWebAppRoleId, newDepartmentId))
{
var result = await base.UpdateAsync(entity, saveEntity);
return result;
}
return false;
}
public override async Task<bool> UpdateListAsync(List<EmployeeToWebApp> entities, bool saveEntity = true)
{
var result = true;
for (int i = 0; i < entities.Count; i++)
{
if (!await UpdateAsync(entities[i], saveEntity)) result = false;
}
return result;
}
public override async Task<bool> AddAsync(EmployeeToWebApp entity, bool saveEntity = true)
{
if (await AddUserToAdGroup(entity, entity.WebAppRoleId, entity.DepartmentId))
{
var result = await base.AddAsync(entity, saveEntity);
return result;
}
return false;
}
public override async Task<bool> AddListAsync(List<EmployeeToWebApp> entities, bool saveEntity = true)
{
var result = true;
for (int i = 0; i < entities.Count; i++)
{
if (!await AddAsync(entities[i], saveEntity)) result = false;
}
return result;
}
public override async Task<bool> DeleteByIdAsync(int id, bool saveEntity = true)
{
try
{
var entity = await base.GetByIdAsync(id);
if (entity == default)
{
throw new ArgumentNullException(nameof(entity));
}
if (await RemoveUserFromAdGroup(entity, entity.WebAppRoleId, entity.DepartmentId))
{
var result = await base.DeleteByIdAsync(id, saveEntity);
return result;
}
return false;
}
catch (Exception ex)
{
WriteLogException(ex, $"An error occurred while deleting the Id {id}");
return false;
}
}
public async Task<WebApp> GetWebAppById(int entityId)
{
try
{
return await this.RepositoryContext.Set<WebApp>().FindAsync(entityId);
}
catch (Exception ex)
{
base.WriteLogException(ex, $"{typeof(WebApp).Name} id:{entityId}");
}
return default;
}
public async Task<Department> GetDepartmentById(int? entityId)
{
try
{
return await this.RepositoryContext.Set<Department>().FindAsync(entityId);
}
catch (Exception ex)
{
WriteLogException(ex, $"{typeof(Department).Name} id:{entityId}");
}
return default;
}
public async Task<Employee> GetEmployeeById(int entityId)
{
try
{
return await this.RepositoryContext.Set<Employee>().FindAsync(entityId);
}
catch (Exception ex)
{
WriteLogException(ex, $"{typeof(Employee).Name} id:{entityId}");
}
return default;
}
public async Task<WebAppRole> GetWebAppRoleById(int entityId)
{
try
{
return await this.RepositoryContext.Set<WebAppRole>().FindAsync(entityId);
}
catch (Exception ex)
{
WriteLogException(ex, $"{typeof(WebAppRole).Name} id:{entityId}");
}
return default;
}
}
}

View File

@ -0,0 +1,12 @@
using DAL.Models.Entities;
using HRD.WebApi.Repositories;
namespace DAL.Repositories
{
public class ProjectRepository : BaseRepository<Project>
{
public ProjectRepository() : base(new WebApiContext())
{
}
}
}

View File

@ -0,0 +1,12 @@
using DAL.Models.Entities;
using HRD.WebApi.Repositories;
namespace DAL.Repositories
{
public class RangRepository : BaseRepository<Rang>
{
public RangRepository() : base(new WebApiContext())
{
}
}
}

View File

@ -0,0 +1,12 @@
using DAL.Models.Entities;
using HRD.WebApi.Repositories;
namespace DAL.Repositories
{
public class SubsidiaryRepository : BaseRepository<Subsidiary>
{
public SubsidiaryRepository() : base(new WebApiContext())
{
}
}
}

View File

@ -0,0 +1,29 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WebAppAdditionalRoleRepository : BaseRepository<WebAppAdditionalRole>
{
public WebAppAdditionalRoleRepository() : base(new WebApiContext())
{
}
public async Task<List<WebAppAdditionalRole>> GetListByFilterAsync(WebAppFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WebAppAdditionalRole>().AsQueryable();
if (filter.WebAppId != null && filter.WebAppId != 0)
{
items = items.Where(x => x.WebAppId == filter.WebAppId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
}
}

View File

@ -0,0 +1,12 @@
using DAL.Models.Entities;
using HRD.WebApi.Repositories;
namespace DAL.Repositories
{
public class WebAppRepository : BaseRepository<WebApp>
{
public WebAppRepository() : base(new WebApiContext())
{
}
}
}

View File

@ -0,0 +1,12 @@
using DAL.Models.Entities;
using HRD.WebApi.Repositories;
namespace DAL.Repositories
{
public class WebAppRoleRepository : BaseRepository<WebAppRole>
{
public WebAppRoleRepository() : base(new WebApiContext())
{
}
}
}

View File

@ -0,0 +1,178 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.LDAPService;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WebAppToDepartmentRepository : BaseRepository<WebAppToDepartment>
{
public WebAppToDepartmentRepository() : base(new WebApiContext())
{
}
public async Task<List<WebAppToDepartment>> GetListByFilterAsync(EmployeeToWebAppFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WebAppToDepartment>().AsQueryable();
if (filter.EmployeeToWebAppId != null && filter.EmployeeToWebAppId != 0)
{
items = items.Where(x => x.EmployeeToWebAppId == filter.EmployeeToWebAppId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
private async Task<bool> AddUserToAdGroup(WebAppToDepartment entity)
{
return await ProcessGroup(entity, "adding");
}
private async Task<bool> RemoveUserFromAdGroup(WebAppToDepartment entity)
{
return await ProcessGroup(entity, "deleting");
}
private async Task<bool> ProcessGroup(WebAppToDepartment entity, string action)
{
if (entity == default) throw new ArgumentNullException(nameof(entity));
var employee2Web = await GetEmployeeToWebAppById(entity.EmployeeToWebAppId);
if (employee2Web == default) throw new ArgumentNullException(nameof(employee2Web));
var department = await GetDepartmentById(entity.DepartmentId);
if (department == default) throw new ArgumentNullException(nameof(department));
if (string.IsNullOrEmpty(department.AdGroupDepartmentName)) return true;
var employee = await GetEmployeeById(employee2Web.EmployeeId);
if (employee == default) throw new ArgumentNullException(nameof(employee));
var webapp = await GetWebAppById(employee2Web.WebAppId);
if (webapp == default) throw new ArgumentNullException(nameof(webapp));
bool result;
var isAdding = action == "adding";
var groupSuffix = $"{webapp.AdWebAppName}_{department.AdGroupDepartmentName}";
if (!LdapManager.IsWindreamSuffixGroup(groupSuffix)) return true;
try
{
if (isAdding) result = LdapManager.AD_AddUserloginToGroup(employee.LoginName, groupSuffix);
else result = LdapManager.AD_RemoveUserFromGroup(employee.LoginName, groupSuffix);
}
catch (Exception ex)
{
WriteLogException(ex, $"An error occurred while '{action}' the '{employee.LoginName}' into '{groupSuffix}'.");
return false;
}
if (!result)
{
WriteLogError($"An error occurred while '{action}' the '{employee.LoginName}' into '{groupSuffix}'.");
return false;
};
return true;
}
public override async Task<bool> AddAsync(WebAppToDepartment entity, bool saveEntity = true)
{
if (await AddUserToAdGroup(entity))
{
var result = await base.AddAsync(entity, saveEntity);
return result;
}
return false;
}
public override async Task<bool> AddListAsync(List<WebAppToDepartment> entities, bool saveEntity = true)
{
var result = true;
for (int i = 0; i < entities.Count; i++)
{
if (!await AddAsync(entities[i], saveEntity)) result = false;
}
return result;
}
public override async Task<bool> DeleteByIdAsync(int id, bool saveEntity = true)
{
try
{
var entity = await base.GetByIdAsync(id);
if (entity == default)
{
throw new ArgumentNullException(nameof(entity));
}
if (await RemoveUserFromAdGroup(entity))
{
var result = await base.DeleteByIdAsync(id, saveEntity);
return result;
}
return false;
}
catch (Exception ex)
{
WriteLogException(ex, $"An error occurred while deleting the Id {id}");
return false;
}
}
public async Task<EmployeeToWebApp> GetEmployeeToWebAppById(int entityId)
{
try
{
return await this.RepositoryContext.Set<EmployeeToWebApp>().FindAsync(entityId);
}
catch (Exception ex)
{
WriteLogException(ex, $"{typeof(EmployeeToWebApp).Name} id:{entityId}");
}
return default;
}
public async Task<WebApp> GetWebAppById(int entityId)
{
try
{
return await this.RepositoryContext.Set<WebApp>().FindAsync(entityId);
}
catch (Exception ex)
{
WriteLogException(ex, $"{typeof(WebApp).Name} id:{entityId}");
}
return default;
}
public async Task<Department> GetDepartmentById(int entityId)
{
try
{
return await this.RepositoryContext.Set<Department>().FindAsync(entityId);
}
catch (Exception ex)
{
WriteLogException(ex, $"{typeof(Department).Name} id:{entityId}");
}
return default;
}
public async Task<Employee> GetEmployeeById(int entityId)
{
try
{
return await this.RepositoryContext.Set<Employee>().FindAsync(entityId);
}
catch (Exception ex)
{
WriteLogException(ex, $"{typeof(Employee).Name} id:{entityId}");
}
return default;
}
}
}

View File

@ -0,0 +1,176 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.LDAPService;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WebAppToWebAppAdditionalRoleRepository : BaseRepository<WebAppToWebAppAdditionalRole>
{
public WebAppToWebAppAdditionalRoleRepository() : base(new WebApiContext())
{
}
public async Task<List<WebAppToWebAppAdditionalRole>> GetListByFilterAsync(EmployeeToWebAppFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WebAppToWebAppAdditionalRole>().AsQueryable();
if (filter.EmployeeToWebAppId != null && filter.EmployeeToWebAppId != 0)
{
items = items.Where(x => x.EmployeeToWebAppId == filter.EmployeeToWebAppId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
private async Task<bool> AddUserToAdGroup(WebAppToWebAppAdditionalRole entity)
{
return await ProcessGroup(entity, "adding");
}
private async Task<bool> RemoveUserFromAdGroup(WebAppToWebAppAdditionalRole entity)
{
return await ProcessGroup(entity, "deleting");
}
private async Task<bool> ProcessGroup(WebAppToWebAppAdditionalRole entity, string action)
{
if (entity == default) throw new ArgumentNullException(nameof(entity));
var employee2Web = await GetEmployeeToWebAppById(entity.EmployeeToWebAppId);
if (employee2Web == default) throw new ArgumentNullException(nameof(employee2Web));
var webappRole = await GetWebAppAddRoleById(entity.WebAppAdditionalRoleId);
if (webappRole == default) throw new ArgumentNullException(nameof(webappRole));
if (string.IsNullOrEmpty(webappRole.AdWebAppAdditionalRoleName)) return true;
var employee = await GetEmployeeById(employee2Web.EmployeeId);
if (employee == default) throw new ArgumentNullException(nameof(employee));
var webapp = await GetWebAppById(employee2Web.WebAppId);
if (webapp == default) throw new ArgumentNullException(nameof(webapp));
bool result;
var isAdding = action == "adding";
var groupSuffix = $"{webapp.AdWebAppName}_{webappRole.AdWebAppAdditionalRoleName}";
try
{
if (isAdding) result = LdapManager.AD_AddUserloginToGroup(employee.LoginName, groupSuffix);
else result = LdapManager.AD_RemoveUserFromGroup(employee.LoginName, groupSuffix);
}
catch (Exception ex)
{
WriteLogException(ex, $"An error occurred while '{action}' the '{employee.LoginName}' into '{groupSuffix}'.");
return false;
}
if (!result)
{
WriteLogError($"An error occurred while '{action}' the '{employee.LoginName}' into '{groupSuffix}'.");
return false;
};
return true;
}
public override async Task<bool> AddAsync(WebAppToWebAppAdditionalRole entity, bool saveEntity = true)
{
if (await AddUserToAdGroup(entity))
{
var result = await base.AddAsync(entity, saveEntity);
return result;
}
return false;
}
public override async Task<bool> AddListAsync(List<WebAppToWebAppAdditionalRole> entities, bool saveEntity = true)
{
var result = true;
for (int i = 0; i < entities.Count; i++)
{
if (!await AddAsync(entities[i], saveEntity)) result = false;
}
return result;
}
public override async Task<bool> DeleteByIdAsync(int id, bool saveEntity = true)
{
try
{
var entity = await base.GetByIdAsync(id);
if (entity == default)
{
throw new ArgumentNullException(nameof(entity));
}
if (await RemoveUserFromAdGroup(entity))
{
var result = await base.DeleteByIdAsync(id, saveEntity);
return result;
}
return false;
}
catch (Exception ex)
{
WriteLogException(ex, $"An error occurred while deleting the Id {id}");
return false;
}
}
public async Task<EmployeeToWebApp> GetEmployeeToWebAppById(int entityId)
{
try
{
return await this.RepositoryContext.Set<EmployeeToWebApp>().FindAsync(entityId);
}
catch (Exception ex)
{
WriteLogException(ex, $"{typeof(EmployeeToWebApp).Name} id:{entityId}");
}
return default;
}
public async Task<WebApp> GetWebAppById(int entityId)
{
try
{
return await this.RepositoryContext.Set<WebApp>().FindAsync(entityId);
}
catch (Exception ex)
{
WriteLogException(ex, $"{typeof(WebApp).Name} id:{entityId}");
}
return default;
}
public async Task<WebAppAdditionalRole> GetWebAppAddRoleById(int entityId)
{
try
{
return await this.RepositoryContext.Set<WebAppAdditionalRole>().FindAsync(entityId);
}
catch (Exception ex)
{
WriteLogException(ex, $"{typeof(WebAppAdditionalRole).Name} id:{entityId}");
}
return default;
}
public async Task<Employee> GetEmployeeById(int entityId)
{
try
{
return await this.RepositoryContext.Set<Employee>().FindAsync(entityId);
}
catch (Exception ex)
{
WriteLogException(ex, $"{typeof(Employee).Name} id:{entityId}");
}
return default;
}
}
}

View File

@ -0,0 +1,29 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WebAppToWebAppRoleRepository : BaseRepository<WebAppToWebAppRole>
{
public WebAppToWebAppRoleRepository() : base(new WebApiContext())
{
}
public async Task<List<WebAppToWebAppRole>> GetListByFilterAsync(WebAppFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WebAppToWebAppRole>().AsQueryable();
if (filter.WebAppId != null && filter.WebAppId != 0)
{
items = items.Where(x => x.WebAppId == filter.WebAppId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
}
}

View File

@ -0,0 +1,34 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WindreamColumnsToDepartmentRepository : BaseRepository<WindreamColumnsToDepartment>
{
public WindreamColumnsToDepartmentRepository() : base(new WebApiContext())
{
}
public async Task<List<WindreamColumnsToDepartment>> GetListByFilterAsync(DepartmentFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WindreamColumnsToDepartment>().AsQueryable();
if (filter.DepartmentId != null && filter.DepartmentId != 0)
{
items = items.Where(x => x.DepartmentId == filter.DepartmentId);
}
if (filter.WindreamSearchId != null && filter.WindreamSearchId != 0)
{
items = items.Where(x => x.WindreamSearchId == filter.WindreamSearchId);
}
return asNoTracking ? await items.OrderBy(x => x.Seq).AsNoTracking().ToListAsync() : await items.OrderBy(x => x.Seq).ToListAsync();
}
}
}

View File

@ -0,0 +1,29 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WindreamIndexRepository : BaseRepository<WindreamIndex>
{
public WindreamIndexRepository() : base(new WebApiContext())
{
}
public async Task<List<WindreamIndex>> GetListByFilterAsync(ClientIdFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WindreamIndex>().AsQueryable();
if (filter.ClientId != null)
{
items = items.Where(x => x.ClientId == filter.ClientId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
}
}

View File

@ -0,0 +1,29 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WindreamIndexToWindreamSearchToDepartmentRepository : BaseRepository<WindreamIndexToWindreamSearchToDepartment>
{
public WindreamIndexToWindreamSearchToDepartmentRepository() : base(new WebApiContext())
{
}
public async Task<List<WindreamIndexToWindreamSearchToDepartment>> GetListByFilterAsync(WindreamSearchToDepartmentFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WindreamIndexToWindreamSearchToDepartment>().AsQueryable();
if (filter.WindreamSearchToDepartmentId != null && filter.WindreamSearchToDepartmentId != 0)
{
items = items.Where(x => x.WindreamSearchToDepartmentId == filter.WindreamSearchToDepartmentId);
}
return asNoTracking ? await items.OrderBy(x => x.Seq).AsNoTracking().ToListAsync() : await items.OrderBy(x => x.Seq).ToListAsync();
}
}
}

View File

@ -0,0 +1,34 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WindreamInputFolderRepository : BaseRepository<WindreamInputFolder>
{
public WindreamInputFolderRepository() : base(new WebApiContext())
{
}
public async Task<List<WindreamInputFolder>> GetListByFilterAsync(WindreamInputFolderFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WindreamInputFolder>().AsQueryable();
if (filter.WindreamInputFolderId != null && filter.WindreamInputFolderId != 0)
{
items = items.Where(x => x.WindreamInputFolderId == filter.WindreamInputFolderId);
return asNoTracking ? await items.ToListAsync() : await items.ToListAsync();
}
if (filter.ClientId != null)
{
items = items.Where(x => x.ClientId == filter.ClientId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
}
}

View File

@ -0,0 +1,29 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WindreamSearchItemRepository : BaseRepository<WindreamSearchItem>
{
public WindreamSearchItemRepository() : base(new WebApiContext())
{
}
public async Task<List<WindreamSearchItem>> GetListByFilterAsync(ClientIdFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WindreamSearchItem>().AsQueryable();
if (filter.ClientId != null)
{
items = items.Where(x => x.ClientId == filter.ClientId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
}
}

View File

@ -0,0 +1,33 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WindreamSearchItemToWindreamSearchToDepartmentRepository : BaseRepository<WindreamSearchItemToWindreamSearchToDepartment>
{
public WindreamSearchItemToWindreamSearchToDepartmentRepository() : base(new WebApiContext())
{
}
public async Task<List<WindreamSearchItemToWindreamSearchToDepartment>> GetListByFilterAsync(WindreamSearchToDepartmentFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WindreamSearchItemToWindreamSearchToDepartment>().AsQueryable();
if (filter.WindreamSearchToDepartmentId != null && filter.WindreamSearchToDepartmentId != 0)
{
items = items.Where(x => x.WindreamSearchToDepartmentId == filter.WindreamSearchToDepartmentId);
}
if (filter.DepartmentId != null && filter.DepartmentId != 0)
{
items = items.Where(x => x.DepartmentId == filter.DepartmentId);
}
return asNoTracking ? await items.OrderBy(x => x.Seq).AsNoTracking().ToListAsync() : await items.OrderBy(x => x.Seq).ToListAsync();
}
}
}

View File

@ -0,0 +1,29 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WindreamSearchRepository : BaseRepository<WindreamSearch>
{
public WindreamSearchRepository() : base(new WebApiContext())
{
}
public async Task<List<WindreamSearch>> GetListByFilterAsync(ClientIdFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WindreamSearch>().AsQueryable();
if (filter.ClientId != null)
{
items = items.Where(x => x.ClientId == filter.ClientId);
}
return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
}
}
}

View File

@ -0,0 +1,36 @@
using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class WindreamSearchToDepartmentRepository : BaseRepository<WindreamSearchToDepartment>
{
public WindreamSearchToDepartmentRepository() : base(new WebApiContext())
{
}
public async Task<List<WindreamSearchToDepartment>> GetListByFilterAsync(DepartmentFilter filter, bool asNoTracking = true)
{
var items = this.RepositoryContext.Set<WindreamSearchToDepartment>().AsQueryable();
if (filter.DepartmentId != null && filter.DepartmentId != 0)
{
items = items.Where(x => x.DepartmentId == filter.DepartmentId);
}
items = items.Where(x => x.IsActive);
return asNoTracking ? await items.OrderBy(x => x.Seq).AsNoTracking().ToListAsync() : await items.OrderBy(x => x.Seq).ToListAsync();
}
public async Task<bool> AddWindreamTile(int srcWindreamSearch2DepartmentId, string trgDepartmentIds)
{
return await ExecStoredProcedureAsync("webapi.sp_TransferWindreamSettings", $"null, {srcWindreamSearch2DepartmentId}, \"{trgDepartmentIds}\"");
}
}
}

213
DAL/WebApiContext.cs Normal file
View File

@ -0,0 +1,213 @@
using DAL._Shared.SharedModels;
using DAL.Models.Entities;
using HRD.WebApi.DAL;
using Microsoft.EntityFrameworkCore;
namespace DAL
{
public partial class WebApiContext : WebApiBaseContext
{
public WebApiContext() : base()
{
}
public WebApiContext(DbContextOptions<DbContext> options) : base(options)
{
}
public virtual DbSet<WebAppUser> WebAppUserSet { get; set; }
public virtual DbSet<WebAppEmployeeInfo> WebAppEmployeeInfo { get; set; }
public virtual DbSet<AdWebAppToWebAppRole> AdWebAppToWebAppRoleSet { get; set; }
public virtual DbSet<CostCentre> CostCentreSet { get; set; }
public virtual DbSet<Department> DepartmentSet { get; set; }
public virtual DbSet<DocumentArt> DocumentArtSet { get; set; }
public virtual DbSet<EmployeeAttribute> EmployeeAttributeSet { get; set; }
public virtual DbSet<EmployeeStatus> EmployeeStatusSet { get; set; }
public virtual DbSet<Project> ProjectSet { get; set; }
public virtual DbSet<Rang> RangSet { get; set; }
public virtual DbSet<WebApp> WebAppSet { get; set; }
public virtual DbSet<WebAppRole> WebAppRoleSet { get; set; }
public virtual DbSet<DepartmentToWebAppToEmployeeForWindream> DepartmentToWebAppToEmployeeForWindreamSet { get; set; }
public virtual DbSet<DocumentArtToDepartment> DocumentArtToDepartmentSet { get; set; }
public virtual DbSet<Employee> EmployeeSet { get; set; }
public virtual DbSet<EmployeeToAttribute> EmployeeToAttributeSet { get; set; }
public virtual DbSet<EmployeeToDepartment> EmployeeToDepartmentSet { get; set; }
public virtual DbSet<EmployeeToWebApp> EmployeeToWebAppSet { get; set; }
public virtual DbSet<WebAppAdditionalRole> WebAppAdditionalRoleSet { get; set; }
public virtual DbSet<WebAppToDepartment> WebAppToDepartmentSet { get; set; }
public virtual DbSet<WebAppToWebAppAdditionalRole> WebAppToWebAppAdditionalRoleSet { get; set; }
public virtual DbSet<WebAppToWebAppRole> WebAppToWebAppRoleSet { get; set; }
public virtual DbSet<WindreamColumnsToDepartment> WindreamColumnsToDepartmentSet { get; set; }
public virtual DbSet<WindreamIndex> WindreamIndexSet { get; set; }
public virtual DbSet<WindreamIndexToWindreamSearchToDepartment> WindreamIndexToWindreamSearchToDepartmentSet { get; set; }
public virtual DbSet<WindreamSearch> WindreamSearchSet { get; set; }
public virtual DbSet<WindreamSearchItem> WindreamSearchItemSet { get; set; }
public virtual DbSet<WindreamSearchItemToWindreamSearchToDepartment> WindreamSearchItemToWindreamSearchToDepartmentSet { get; set; }
public virtual DbSet<WindreamSearchToDepartment> WindreamSearchToDepartmentSet { get; set; }
public virtual DbSet<WindreamInputFolder> WindreamInputFolderSet { get; set; }
public virtual DbSet<Subsidiary> SubsidiarySet { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Subsidiary>(entity =>
{
entity.ToTable("Subsidiary", "webapi");
});
modelBuilder.Entity<WindreamInputFolder>(entity =>
{
entity.ToTable("WindreamInputFolder", "webapi");
});
modelBuilder.Entity<WindreamSearchToDepartment>(entity =>
{
entity.ToTable("WindreamSearchToDepartment", "webapi");
});
modelBuilder.Entity<WindreamSearchItemToWindreamSearchToDepartment>(entity =>
{
entity.ToTable("WindreamSearchItemToWindreamSearchToDepartment", "webapi");
});
modelBuilder.Entity<WindreamSearchItem>(entity =>
{
entity.ToTable("WindreamSearchItem", "webapi");
});
modelBuilder.Entity<WindreamSearch>(entity =>
{
entity.ToTable("WindreamSearch", "webapi");
});
modelBuilder.Entity<WindreamIndexToWindreamSearchToDepartment>(entity =>
{
entity.ToTable("WindreamIndexToWindreamSearchToDepartment", "webapi");
});
modelBuilder.Entity<WindreamIndex>(entity =>
{
entity.ToTable("WindreamIndex", "webapi");
});
modelBuilder.Entity<WindreamColumnsToDepartment>(entity =>
{
entity.ToTable("WindreamColumnsToDepartment", "webapi");
});
modelBuilder.Entity<WebAppToWebAppRole>(entity =>
{
entity.ToTable("WebAppToWebAppRole", "webapi");
});
modelBuilder.Entity<WebAppToWebAppAdditionalRole>(entity =>
{
entity.ToTable("WebAppToWebAppAdditionalRole", "webapi");
});
modelBuilder.Entity<WebAppToDepartment>(entity =>
{
entity.ToTable("WebAppToDepartment", "webapi");
});
modelBuilder.Entity<WebAppAdditionalRole>(entity =>
{
entity.ToTable("WebAppAdditionalRole", "webapi");
});
modelBuilder.Entity<EmployeeToWebApp>(entity =>
{
entity.ToTable("EmployeeToWebApp", "webapi");
});
modelBuilder.Entity<EmployeeToDepartment>(entity =>
{
entity.ToTable("EmployeeToDepartment", "webapi");
});
modelBuilder.Entity<EmployeeToAttribute>(entity =>
{
entity.ToTable("EmployeeToAttribute", "webapi");
});
modelBuilder.Entity<Employee>(entity =>
{
entity.ToTable("Employee", "webapi");
});
modelBuilder.Entity<DocumentArtToDepartment>(entity =>
{
entity.ToTable("DocumentArtToDepartment", "webapi");
});
modelBuilder.Entity<DepartmentToWebAppToEmployeeForWindream>(entity =>
{
entity.ToTable("DepartmentToWebAppToEmployeeForWindream", "webapi");
});
modelBuilder.Entity<WebAppRole>(entity =>
{
entity.ToTable("WebAppRole", "webapi");
});
modelBuilder.Entity<WebApp>(entity =>
{
entity.ToTable("WebApp", "webapi");
});
modelBuilder.Entity<Rang>(entity =>
{
entity.ToTable("Rang", "webapi");
});
modelBuilder.Entity<Project>(entity =>
{
entity.ToTable("Project", "webapi");
});
modelBuilder.Entity<EmployeeStatus>(entity =>
{
entity.ToTable("EmployeeStatus", "webapi");
});
modelBuilder.Entity<EmployeeAttribute>(entity =>
{
entity.ToTable("EmployeeAttribute", "webapi");
});
modelBuilder.Entity<DocumentArt>(entity =>
{
entity.ToTable("DocumentArt", "webapi");
});
modelBuilder.Entity<Department>(entity =>
{
entity.ToTable("Department", "webapi");
});
modelBuilder.Entity<CostCentre>(entity =>
{
entity.ToTable("CostCentre", "webapi");
});
modelBuilder.Entity<AdWebAppToWebAppRole>(entity =>
{
entity.ToTable("AdWebAppToWebAppRole", "webapi");
});
modelBuilder.Entity<WebAppUser>(entity =>
{
entity.ToTable("WebAppUser", "webapi");
});
modelBuilder.Entity<WebAppEmployeeInfo>(entity =>
{
entity.ToTable("WebAppEmployeeInfo", "webapi");
});
base.OnModelCreating(modelBuilder);
}
}
}

View File

@ -0,0 +1,37 @@
using HRD.WebApi.DAL;
namespace DAL._Shared.SharedModels
{
public partial class WebAppEmployeeInfo : BaseEntity
{
public int WebAppEmployeeInfoId { get; set; }
public string EmployeeNo { get; set; }
public string Salutation { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ShortName { get; set; }
public string Title { get; set; }
public string Position { get; set; }
public string LoginName { get; set; }
public string Email { get; set; }
public int DepartmentId { get; set; }
public string ExtendedDepartmentIdList { get; set; }
public string DepartmentName { get; set; }
public int EmployeeId { get; set; }
public int CostCentreId { get; set; }
public string RangShortname { get; set; }
public string RangName { get; set; }
public int RangOrder { get; set; }
public int ClientId { get; set; }
public int WebAppId { get; set; }
//generic Id
public override int GetEntityId() => WebAppEmployeeInfoId;
//generic ToString()
public override string ToString() => $"WebAppEmployeeInfoId: {GetEntityId()}; Name: {LoginName}";
//generic EntityInfo()
public override string EntityInfo() => base.EntityInfo();
}
}

View File

@ -0,0 +1,59 @@
using HRD.WebApi.DAL;
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL._Shared.SharedModels
{
public partial class WebAppUser : BaseEntity
{
public WebAppUser()
{
}
public WebAppUser(string loginName, string shortName, string roleList, string name)
{
LoginName = loginName;
ShortName = shortName;
RoleList = roleList;
Name = name;
}
public int WebAppUserId { get; set; }
public string Name { get; set; }
public string ShortName { get; set; }
public string LoginName { get; set; }
public string Password { get; set; } = string.Empty;
public string RoleList { get; set; }
public string WebAppRoleList { get; set; } = string.Empty;
public DateTime? JwtExpiredOn { get; set; }
public DateTime? LastLogin { get; set; }
[NotMapped]
public string Token { get; set; }
public string ClientVersion { get; set; }
[NotMapped]
public int TimeZoneOffsetInMin { get; set; }
public string Language { get; set; }
public string Culture { get; set; }
public bool IsGermanCulture() => Culture?.Substring(0, 2).ToLower() == "de";
//generic Id
public override int GetEntityId() => WebAppUserId;
//generic ToString()
public override string ToString() => $"WebAppUserId: {GetEntityId()}; Name: {Name}";
//generic EntityInfo()
public override string EntityInfo()
{
return $"WebAppUserId: {GetEntityId()}; Loginname:{LoginName}; JwtExpiredOn:{JwtExpiredOn}";
}
}
}

View File

@ -0,0 +1,114 @@
using DAL._Shared.SharedModels;
using HRD.LDAPService;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DAL._Shared.SharedRepositories
{
public class WebAppEmployeeInfoRepository : BaseRepository<WebAppEmployeeInfo>
{
public WebAppEmployeeInfoRepository() : base(new WebApiContext())
{
}
private IQueryable<WebAppEmployeeInfo> PrepareList(List<int> departmentIds)
{
IQueryable<WebAppEmployeeInfo> items = RepositoryContext.Set<WebAppEmployeeInfo>().AsNoTracking();
return items.Where(x => departmentIds.Contains(x.DepartmentId));
}
public async Task<List<string>> GetEmailListForDepartmentsAsync(List<int> departmentIds)
{
return await PrepareList(departmentIds).Select(x => x.Email).ToListAsync();
}
public async Task<List<string>> GetLoginnameListForDepartmentsAsync(List<int> departmentIds)
{
return await PrepareList(departmentIds).Select(x => x.LoginName).ToListAsync();
}
public async Task<List<string>> GetShortnameListForDepartmentsAsync(List<int> departmentIds)
{
return await PrepareList(departmentIds).Select(x => x.ShortName).ToListAsync();
}
public async Task<string> GetShortnameForLoginAsync(string loginname)
{
return (await RepositoryContext.Set<WebAppEmployeeInfo>().FirstAsync(x => x.LoginName == loginname)).ShortName;
}
//----------------
public List<string> GetEmailListForDepartments(List<int> departmentIds)
{
return PrepareList(departmentIds).Select(x => x.Email).ToList();
}
public List<string> GetLoginnameListForDepartments(List<int> departmentIds)
{
return PrepareList(departmentIds).Select(x => x.LoginName).ToList();
}
public List<string> GetShortnameListForDepartments(List<int> departmentIds)
{
return PrepareList(departmentIds).Select(x => x.ShortName).ToList();
}
public string GetShortnameForLogin(string loginname)
{
return RepositoryContext.Set<WebAppEmployeeInfo>().First(x => x.LoginName == loginname).ShortName;
}
//----------------
public bool PrepareForUserLoginnameOrLoginnameListFilter(LdapUser ldapUser, ref string loginName, ref List<string> loginNameList)
{
if (ldapUser.IsAdmin() || ldapUser.IsMaster())
{
}
else if (ldapUser.IsDepartmentMaster() || ldapUser.IsDepartmentUser())
{
loginNameList = GetLoginnameListForDepartments(ldapUser.DepartmentIdListAll());
loginName = default;
}
else if (ldapUser.IsUser())
{
loginNameList = default;
loginName = ldapUser.LoginName;
}
else
{
return false; //shouldn't happen
}
return true;
}
public bool PrepareForUserEmailOrEmailListFilter(LdapUser ldapUser, ref string EmailBV, ref List<string> EmailBVList)
{
if (string.IsNullOrEmpty(EmailBV)) //check for user & master
{
if (ldapUser.IsAdmin() || ldapUser.IsMaster())
{
// No correction
}
else if (ldapUser.IsDepartmentMaster() || ldapUser.IsDepartmentUser())
{
EmailBVList = GetEmailListForDepartments(ldapUser.DepartmentIdListAll());
EmailBV = default;
}
else if (ldapUser.IsUser())
{
EmailBVList = default;
EmailBV = ldapUser.Email;
}
else
{
return false; //shouldn't happen
}
}
return true;
}
}
}

View File

@ -0,0 +1,12 @@
using DAL._Shared.SharedModels;
using HRD.WebApi.Repositories;
namespace DAL._Shared.SharedRepositories
{
public class WebAppUserRepository : BaseRepository<WebAppUser>
{
public WebAppUserRepository() : base(new WebApiContext())
{
}
}
}

View File

@ -0,0 +1,2 @@
dotnet ef dbcontext scaffold "Server=192.168.110.105\\DEV1;Database=ctx;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o ModelCTX
pause

View File

@ -0,0 +1,255 @@
using HRD.AppLogger;
using NLog;
using NLog.Config;
using NLog.Targets;
using System;
using System.Collections.Generic;
using System.IO;
namespace HRD.AppLogger
{
public enum EN_LoggingLevel
{
Trace = 1,
Debug = 2,
Info = 3,
Warn = 4,
Error = 5,
Fatal = 6,
Off = 7
}
}
public static class AppLoggerConfig
{
private static readonly string DBLOG_CommandText =
@"
INSERT INTO dbo.DBLog
( MachineName,
Application,
Logged,
Level,
Message,
Logger,
CallSite,
Webrequest,
Stacktrace,
InnerException,
Exception,
Version,
Entity
)
VALUES
( @machineName,
@application,
@logged,
@level,
@message,
@logger,
@callsite,
iif(@webrequestaction='',@webrequest, concat(@webrequest,' | action:',@webrequestaction)),
@stacktrace,
@innerException,
@exception,
@Version,
@Entity
);";
private static readonly Dictionary<string, string> DBLOG_Parameters = new Dictionary<string, string>() {
//Globals
{"@version", "${gdc:item=Version}"},
{"@application", "${gdc:item=Application}"},
//Local
//{"@webrequest", "${mdlc:item=Webrequest}"},
{"@entity", "${mdlc:item=Entity}"},
//WebApi
{"@webrequest", "${aspnet-request-url}"},
{"@webrequestaction", "${aspnet-mvc-action}"},
//Nlog
{"@machineName", "${machinename}" },
{"@logged", "${date}"},
{"@level", "${level:upperCase=true}"},
{"@message", "${message}"},
{"@logger", "${logger}"},
{"@callSite", "${callsite:fileName=true:includeSourcePath=false:skipFrames=1}"}, //{"@callSite", "${callsite:filename=false:className=true:methodName=true}"},
{"@stacktrace", "${stacktrace:topFrames=10}"},
{"@InnerException", "${exception:format=Message,StackTrace,Data:maxInnerExceptionLevel=10}"},
{"@Exception", "${exception:format=ToString}"},
};
public static string AssemblyName { get; set; }
public static string AssemblyVersion { get; set; }
public static EN_LoggingLevel DBLogLevel { get; set; } = EN_LoggingLevel.Warn;
public static EN_LoggingLevel FileLogLevel { get; set; } = EN_LoggingLevel.Error;
public static string LogDirectory { get; set; } = String.Empty;
public static string NlogConnectionstring { get; set; }
public static LogLevel NlogDBLogLevel { get; set; }
public static LogLevel NlogFileLogLevel { get; set; }
public static NlogSentryConfig NlogSentryConfig { get; set; } = new NlogSentryConfig();
public static LoggingConfiguration CreateConfig()
{
NlogDBLogLevel = MapLogLevel(DBLogLevel);
NlogFileLogLevel = MapLogLevel(FileLogLevel);
var config = new LoggingConfiguration();
DatabaseTarget dbTarget = CreateDatabaseTarget(config);
var dbRule = new LoggingRule("*", NlogDBLogLevel, dbTarget);
config.LoggingRules.Add(dbRule);
//Rules
FileTarget targetFile = CreateFileTarget(config);
var rule = new LoggingRule("*", NlogFileLogLevel, targetFile);
config.LoggingRules.Add(rule);
if (NlogSentryConfig.NlogSentryIsEnable)
{
AddSentry(config);
}
return config;
}
public static void Init(
string assemblyName,
string assemblyVersion,
EN_LoggingLevel dbLogLevel = EN_LoggingLevel.Warn
, EN_LoggingLevel fileLoogLevel = EN_LoggingLevel.Off
, string logDirectory = "")
{
AssemblyVersion = assemblyVersion;
AssemblyName = assemblyName;
DBLogLevel = dbLogLevel;
FileLogLevel = fileLoogLevel;
LogDirectory = logDirectory;
}
private static void AddSentry(LoggingConfiguration config)
{
config.AddSentry(o =>
{
o.Dsn = NlogSentryConfig.Dsn;
o.Layout = "${message}";
o.BreadcrumbLayout = "${logger}: ${message} #url: ${aspnet-request-url} | #action: ${aspnet-mvc-action}";
// Optionally specify a separate format for breadcrumbs
o.MinimumBreadcrumbLevel = NlogSentryConfig.MinimumBreadcrumbLevel; // Debug and higher are stored as breadcrumbs (default is Info)
o.MinimumEventLevel = NlogSentryConfig.MinimumEventLevel; // Error and higher is sent as event (default is Error)
// If DSN is not set, the SDK will look for an environment variable called SENTRY_DSN. If
// nothing is found, SDK is disabled.
o.AttachStacktrace = NlogSentryConfig.AttachStacktrace;
o.SendDefaultPii = NlogSentryConfig.SendDefaultPii; // Send Personal Identifiable information like the username of the user logged in to the device
o.IncludeEventDataOnBreadcrumbs = NlogSentryConfig.IncludeEventDataOnBreadcrumbs; // Optionally include event properties with breadcrumbs
o.ShutdownTimeoutSeconds = 5;
o.TracesSampleRate = 0.3;
//Optionally specify user properties via NLog (here using MappedDiagnosticsLogicalContext as an example)
// o.User = new SentryNLogUser
// {
// Id = "${mdlc:item=id}",
// Username = "${mdlc:item=username}",
// Email = "${mdlc:item=email}",
// IpAddress = "${mdlc:item=ipAddress}",
// Other =
//{
// new TargetPropertyWithContext("mood", "joyous")
//},
//};
o.AddTag("Backend", "${gdc:item=Application}"); // Send the logger name as a tag
o.AddTag("BackendVersion", "${gdc:item=Version}"); // Send the logger name as a tag
o.AddTag("logger", "${logger}"); // Send the logger name as a tag
// Other configuration
});
}
private static DatabaseTarget CreateDatabaseTarget(LoggingConfiguration config)
{
var dbTarget = new DatabaseTarget
{
ConnectionString = NlogConnectionstring,
CommandText = DBLOG_CommandText
};
foreach (var item in DBLOG_Parameters)
{
dbTarget.Parameters.Add(new DatabaseParameterInfo(item.Key, item.Value));
}
config.AddTarget("database", dbTarget);
return dbTarget;
}
private static FileTarget CreateFileTarget(LoggingConfiguration config)
{
var targetFile =
new FileTarget
{
FileName = Path.Combine(
!string.IsNullOrEmpty(LogDirectory) ? LogDirectory : "${basedir}/_logs/",
"${gdc:item=Application}" + "_V." + "${gdc:item=Version}" + $"_{DateTime.Now:yyyyMMdd}.log"),
Layout = "${date}|${uppercase:${level}}|${stacktrace}|${message}" +
"|${exception:format=Message,StackTrace,Data:maxInnerExceptionLevel=10}" +
"${event-properties:item=EventId.Id}"
};
config.AddTarget("logfile", targetFile);
return targetFile;
}
private static LogLevel MapLogLevel(EN_LoggingLevel loggingLevel)
{
LogLevel logLevel = LogLevel.Error;
switch (loggingLevel)
{
case EN_LoggingLevel.Trace:
logLevel = LogLevel.Trace;
break;
case EN_LoggingLevel.Debug:
logLevel = LogLevel.Debug;
break;
case EN_LoggingLevel.Info:
logLevel = LogLevel.Info;
break;
case EN_LoggingLevel.Warn:
logLevel = LogLevel.Warn;
break;
case EN_LoggingLevel.Error:
logLevel = LogLevel.Error;
break;
case EN_LoggingLevel.Fatal:
logLevel = LogLevel.Fatal;
break;
case EN_LoggingLevel.Off:
logLevel = LogLevel.Off;
break;
default:
break;
}
return logLevel;
}
public static void SetSentryUser(int id, string login, string email, IDictionary<string, string> others = null)
{
NlogSentryConfig.SentryUser = new Sentry.User { Id = id.ToString(), Username = login, Email = email };
if (others != null) NlogSentryConfig.SentryUser.Other = others;
Sentry.SentrySdk.ConfigureScope(scope => { scope.User = NlogSentryConfig.SentryUser; });
}
}

View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp7.0</TargetFramework>
<Company>Hensel Recycling GmbH</Company>
<Authors>IT Entwicklung</Authors>
<Version>1.5.0</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NLog.Web.AspNetCore" Version="4.14.0" />
<PackageReference Include="Sentry.NLog" Version="3.41.4" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,17 @@
using System;
namespace HRD.AppLogger
{
public interface ILoggerManager
{
void LogDebug(string message, string entityMessage = null, string webrequest = null, string userLogin = null);
void LogError(string message, string entityMessage = null, string webrequest = null, string userLogin = null);
void LogInfo(string message, string entityMessage = null, string webrequest = null, string userLogin = null);
void LogWarn(string message, string entityMessage = null, string webrequest = null, string userLogin = null);
void LogException(Exception exception, string entityMessage = null, string webrequest = null, string userLogin = null);
}
}

View File

@ -0,0 +1,214 @@
using NLog;
using Sentry;
using System;
namespace HRD.AppLogger
{
public class LoggerManager : ILoggerManager
{
private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
public LoggerManager(bool throwExceptions = true) : this()
{
LogManager.ThrowExceptions = throwExceptions;
}
public LoggerManager()
{
GlobalDiagnosticsContext.Set("Version", AppLoggerConfig.AssemblyVersion);
GlobalDiagnosticsContext.Set("Application", AppLoggerConfig.AssemblyName);
LogManager.ThrowConfigExceptions = true;
LogManager.ThrowExceptions = false;
LogManager.Configuration = AppLoggerConfig.CreateConfig();
}
public void WriteLog(Action<Object> log, Object message, string entityMessage = null, string webrequest = null, string userLogin = null)
{
MappedDiagnosticsLogicalContext.Set("Entity", !String.IsNullOrEmpty(entityMessage) ? entityMessage : "");
MappedDiagnosticsLogicalContext.Set("Webrequest", !String.IsNullOrEmpty(webrequest) ? webrequest : "");
if (AppLoggerConfig.NlogSentryConfig.NlogSentryIsEnable)
{
SentrySdk.WithScope(scope =>
{
if (!String.IsNullOrEmpty(entityMessage))
{
scope.SetTag("Entity", entityMessage);
}
if (!String.IsNullOrEmpty(webrequest))
{
scope.SetTag("Webrequest", webrequest);
}
if (!String.IsNullOrEmpty(userLogin))
{
scope.SetTag("UserLogin", userLogin);
}
log(message);
});
}
else log(message);
}
public void LogDebug(string message, string entityMessage = null, string webrequest = null, string userLogin = null)
{
WriteLog(logger.Debug, message, entityMessage, webrequest, userLogin);
/* MappedDiagnosticsLogicalContext.Set("Entity", !String.IsNullOrEmpty(entityMessage) ? entityMessage : "");
MappedDiagnosticsLogicalContext.Set("Webrequest", !String.IsNullOrEmpty(webrequest) ? webrequest : "");
if (AppLoggerConfig.NlogSentryConfig.NlogSentryIsEnable)
{
SentrySdk.WithScope(scope =>
{
if (!String.IsNullOrEmpty(entityMessage))
{
scope.SetTag("Entity", entityMessage);
}
if (!String.IsNullOrEmpty(webrequest))
{
scope.SetTag("Webrequest", webrequest);
}
if (!String.IsNullOrEmpty(userLogin))
{
scope.SetTag("UserLogin", userLogin);
}
logger.Debug(message);
});
}
else logger.Debug(message);*/
}
public void LogError(string message, string entityMessage = null, string webrequest = null, string userLogin = null)
{
//WriteLog(logger.Error, message, entityMessage, webrequest, userLogin);
MappedDiagnosticsLogicalContext.Set("Entity", !String.IsNullOrEmpty(entityMessage) ? entityMessage : "");
MappedDiagnosticsLogicalContext.Set("Webrequest", !String.IsNullOrEmpty(webrequest) ? webrequest : "");
if (AppLoggerConfig.NlogSentryConfig.NlogSentryIsEnable)
{
SentrySdk.WithScope(scope =>
{
if (!String.IsNullOrEmpty(entityMessage))
{
scope.SetTag("Entity", entityMessage);
}
if (!String.IsNullOrEmpty(webrequest))
{
scope.SetTag("Webrequest", webrequest);
}
if (!String.IsNullOrEmpty(userLogin))
{
scope.SetTag("UserLogin", userLogin);
}
logger.Error(message);
});
}
else logger.Error(message);
}
public void LogException(Exception exception, string entityMessage = null, string webrequest = null, string userLogin = null)
{
//WriteLog(logger.Error, exception, entityMessage, webrequest, userLogin);
MappedDiagnosticsLogicalContext.Set("Entity", !String.IsNullOrEmpty(entityMessage) ? entityMessage : "");
MappedDiagnosticsLogicalContext.Set("Webrequest", !String.IsNullOrEmpty(webrequest) ? webrequest : "");
if (AppLoggerConfig.NlogSentryConfig.NlogSentryIsEnable)
{
SentrySdk.WithScope(scope =>
{
if (!String.IsNullOrEmpty(entityMessage))
{
scope.SetTag("Entity", entityMessage);
}
if (!String.IsNullOrEmpty(webrequest))
{
scope.SetTag("Webrequest", webrequest);
}
if (!String.IsNullOrEmpty(userLogin))
{
scope.SetTag("UserLogin", userLogin);
}
logger.Error(exception);
});
}
else logger.Error(exception);
}
public void LogWarn(string message, string entityMessage = null, string webrequest = null, string userLogin = null)
{
//WriteLog(logger.Warn, message, entityMessage, webrequest, userLogin);
MappedDiagnosticsLogicalContext.Set("Entity", !String.IsNullOrEmpty(entityMessage) ? entityMessage : "");
MappedDiagnosticsLogicalContext.Set("Webrequest", !String.IsNullOrEmpty(webrequest) ? webrequest : "");
if (AppLoggerConfig.NlogSentryConfig.NlogSentryIsEnable)
{
SentrySdk.WithScope(scope =>
{
if (!String.IsNullOrEmpty(entityMessage))
{
scope.SetTag("Entity", entityMessage);
}
if (!String.IsNullOrEmpty(webrequest))
{
scope.SetTag("Webrequest", webrequest);
}
if (!String.IsNullOrEmpty(userLogin))
{
scope.SetTag("UserLogin", userLogin);
}
logger.Warn(message);
});
}
else logger.Warn(message);
}
public void LogInfo(string message, string entityMessage = null, string webrequest = null, string userLogin = null)
{
//WriteLog(logger.Info, message, entityMessage, webrequest, userLogin);
MappedDiagnosticsLogicalContext.Set("Entity", !String.IsNullOrEmpty(entityMessage) ? entityMessage : "");
MappedDiagnosticsLogicalContext.Set("Webrequest", !String.IsNullOrEmpty(webrequest) ? webrequest : "");
if (AppLoggerConfig.NlogSentryConfig.NlogSentryIsEnable)
{
SentrySdk.WithScope(scope =>
{
if (!String.IsNullOrEmpty(entityMessage))
{
scope.SetTag("Entity", entityMessage);
}
if (!String.IsNullOrEmpty(webrequest))
{
scope.SetTag("Webrequest", webrequest);
}
if (!String.IsNullOrEmpty(userLogin))
{
scope.SetTag("UserLogin", userLogin);
}
logger.Info(message);
});
}
else logger.Info(message);
}
}
}

View File

@ -0,0 +1,29 @@
using NLog;
using Sentry;
namespace HRD.AppLogger
{
public class NlogSentryConfig
{
public bool AttachStacktrace { get; set; } = false;
public string Dsn { get; set; }
//
// Summary:
// Determines whether or not to include event-level data as data in breadcrumbs
// for future errors. Defaults to false.
public bool IncludeEventDataOnBreadcrumbs { get; set; } = false;
// Minimum log level to be included in the breadcrumb. Defaults to LogLevel.Info.
public LogLevel MinimumBreadcrumbLevel { get; set; } = LogLevel.Warn;
//
// Summary:
// Minimum log level for events to trigger a send to Sentry. Defaults to LogLevel.Error.
public LogLevel MinimumEventLevel { get; set; } = LogLevel.Warn;
public bool NlogSentryIsEnable { get; set; }
public bool SendDefaultPii { get; set; } = false;
public User? SentryUser { get; set; }
}
}

View File

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<PackageId>HRD.LDAPService</PackageId>
<Authors>Valeri Bojarski</Authors>
<Company>Hensel Recycling GmbH</Company>
<Version>1.4.6</Version>
<Description>Json Web Token (JWT) &amp; LDAP user authentication
</Description>
</PropertyGroup>
<ItemGroup>
<None Include="..\.editorconfig" Link=".editorconfig" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="IdentityServer4.Storage" Version="4.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.20" />
<PackageReference Include="System.DirectoryServices.AccountManagement" Version="7.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.6.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,21 @@
using Newtonsoft.Json;
namespace HRD.LDAPService.JWT
{
public class HttpErrorDetails
{
public HttpErrorDetails(int statusCode, string message)
{
StatusCode = statusCode;
Message = message;
}
public string Message { get; set; }
public int StatusCode { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}

View File

@ -0,0 +1,40 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
namespace HRD.LDAPService.JWT
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class JWTAuthorizeAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
if (JwtTokenConfig.AktivateAuthorizationFilter)
{
bool isInWhiteList = false;
//allow access with logn & pwd and without Authorization token
var path = context?.HttpContext.Request.Path.Value;
if (!string.IsNullOrEmpty(path))
{
if (JwtTokenConfig.IsInBlackList(path))
{
context.Result = new JsonResult(new { message = $"Unauthorized access. Path is in a blacklist: '${path}'" }) { StatusCode = StatusCodes.Status403Forbidden };
}
isInWhiteList = JwtTokenConfig.IsInWhiteList(path);
if (!isInWhiteList)
{ //need jwt check
var check = (string)context.HttpContext.Items[JwtGlobals.HttpContextItem_IsValidHenselToken];
if (check == null)
{
context.Result = new JsonResult(new { message = $"Unauthorized access. Path: '${path}'" }) { StatusCode = StatusCodes.Status401Unauthorized };
}
}
}
}
}
}
}

View File

@ -0,0 +1,125 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace HRD.LDAPService.JWT
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class JWTAuthorizeVendorId : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
if (JwtTokenConfig.AktivateAuthorizationFilter)
{
//allow access with logn & pwd and without Authorization token
var path = context?.HttpContext.Request.Path.Value;
if (!string.IsNullOrEmpty(path))
{
if (JwtTokenConfig.IsInBlackList(path))
{
context.Result = new JsonResult(new { message = $"Unauthorized access. Path is in a blacklist: '${path}'" }) { StatusCode = StatusCodes.Status403Forbidden };
return;
}
if (JwtTokenConfig.IsInWhiteList(path))
{
return;
}
else //need jwt check
{
var check = (string)context.HttpContext.Items[JwtGlobals.HttpContextItem_IsValidHenselToken];
if (check == null)
{
context.Result = new JsonResult(new { message = $"Unauthorized access. Path: '${path}'" }) { StatusCode = StatusCodes.Status401Unauthorized };
return;
}
}
var headerAuthorization = context.HttpContext.Request.Headers["Authorization"];
var authorizationType = headerAuthorization.FirstOrDefault()?.Split(" ").First();
if (authorizationType == null)
{
context.Result = new JsonResult(new { message = $"Eror. Path: '${path}'" }) { StatusCode = StatusCodes.Status401Unauthorized };
return;
}
var jwt = headerAuthorization.FirstOrDefault();
if (!JwtManager.IsValidatJwtTokenSubject(jwt))
{
throw new UnauthorizedAccessException($"Not valid JWT");
}
LdapUser ldapUser = JwtManager.DecryptTokenAsLdapUser(jwt);
string ldapUserVendorId = ldapUser.GetExtendedAttributeValue("VendorId");
if (string.IsNullOrEmpty(ldapUserVendorId))
{
context.Result = new JsonResult(new { message = $"Vendor Id is empty. Path: '${path}'" }) { StatusCode = StatusCodes.Status401Unauthorized };
return;
}
var syncIOFeature = context.HttpContext.Features.Get<IHttpBodyControlFeature>();
if (syncIOFeature != null)
{
syncIOFeature.AllowSynchronousIO = true;
var req = context.HttpContext.Request;
req.EnableBuffering();
// read the body here as a workarond for the JSON parser disposing the stream
if (req.Body.CanSeek)
{
req.Body.Seek(0, SeekOrigin.Begin);
// if body (stream) can seek, we can read the body to a string for logging purposes
using (var reader = new StreamReader(
req.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
bufferSize: 8192,
leaveOpen: true))
{
var jsonString = reader.ReadToEnd();
var content = JsonConvert.DeserializeObject<dynamic>(jsonString);
if (content == null)
{
context.Result = new JsonResult(new { message = $"Unauthorized access. Can not deserialize the the Request: '${path}'" }) { StatusCode = StatusCodes.Status403Forbidden };
}
if (content?.Root != null && string.Equals(content?.Root?.Type.ToString(), "Array", StringComparison.InvariantCulture))
{
List<dynamic> contentList = JsonConvert.DeserializeObject<List<dynamic>>(jsonString);
string jwtVendorId = contentList?.FirstOrDefault()?.vendorId;
if (string.IsNullOrEmpty(jwtVendorId) || ldapUserVendorId != jwtVendorId)
{
context.Result = new JsonResult(new { message = $"Vendor {ldapUserVendorId} is not equal to Vendor from Token {jwtVendorId} List. Path: '${path}'" }) { StatusCode = StatusCodes.Status401Unauthorized };
return;
}
}
else
{
string jwtVendorId = content.vendorId;
if (string.IsNullOrEmpty(jwtVendorId) || ldapUserVendorId != jwtVendorId)
{
context.Result = new JsonResult(new { message = $"Vendor {ldapUserVendorId} is not equal to Vendor from Token {jwtVendorId}. Path: '${path}'" }) { StatusCode = StatusCodes.Status401Unauthorized };
return;
}
}
}
// Important! go back to beginning so json reader get's the whole thing
req.Body.Seek(0, SeekOrigin.Begin);
}
}
}
}
}
}
}

View File

@ -0,0 +1,31 @@
namespace HRD.LDAPService.JWT
{
public static class JWTCrypt
{
public static string GenerateHashPassword(string inputKey)
{
return BCrypt.Net.BCrypt.EnhancedHashPassword(inputKey, 11, BCrypt.Net.HashType.SHA512);
}
public static bool VerifyHashPassword(string hashedPassword, string providedPassword)
{
return BCrypt.Net.BCrypt.Verify(providedPassword, hashedPassword, true, BCrypt.Net.HashType.SHA512);
}
public static string SHA512(string input)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(input);
using (var hash = System.Security.Cryptography.SHA512.Create())
{
var hashedInputBytes = hash.ComputeHash(bytes);
// Convert to text
// StringBuilder Capacity is 128, because 512 bits / 8 bits in byte * 2 symbols for byte
var hashedInputStringBuilder = new System.Text.StringBuilder(128);
foreach (var b in hashedInputBytes)
hashedInputStringBuilder.Append(b.ToString("X2"));
return hashedInputStringBuilder.ToString();
}
}
}
}

View File

@ -0,0 +1,19 @@
namespace HRD.LDAPService.JWT
{
public static class JwtGlobals
{
public const string HttpContextItem_LdapUser = "ldapuser";
public const string HttpContextItem_IsValidHenselToken = "IsValidHenselToken";
public const string CLAIM_DEPARTNENTID = "departmentid";
public const string CLAIM_EXTENDETDEPARTNENTIDLIST = "extendetdepartmentidlist";
public const string CLAIM_ROLE = "role";
public const string ROLE_USER = "User";
public const string ROLE_DEPARTMENTUSER = "DepartmentUser";
public const string ROLE_DEPARTMENTMASTER = "DepartmentMaster";
public const string ROLE_MASTER = "Master";
public const string ROLE_ADMIN = "Admin";
}
}

View File

@ -0,0 +1,355 @@
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
namespace HRD.LDAPService.JWT
{
public static class JwtManager
{
private const string GlbExtendedAttributes = "ExtendedAttributes_";
public static LdapUser DecryptTokenAsLdapUser(string token)
{
if (string.IsNullOrEmpty(token)) { return default; }
//Check token with "Bearer" prefix
if (token.StartsWith("Bearer", StringComparison.InvariantCultureIgnoreCase))
{
token = token.Split(" ").Last();
}
if (string.IsNullOrEmpty(token)) { return default; }
JwtSecurityToken jwtSecurityToken = DecryptToken(token);
if (jwtSecurityToken == null) { return default; }
LdapUser ldapUser = ClaimsIdentityToLdapUser(jwtSecurityToken.Claims.ToList());
if (ldapUser == null)
{
return default;
}
ldapUser.Token = token;
return ldapUser;
}
public static JwtSecurityToken DecryptToken(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(JwtTokenConfig.Secret);
try
{
tokenHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.FromSeconds(60) // set clockskew to zero so tokens expire exactly at token expiration time
}, out SecurityToken validatedToken);
var jwtToken = (JwtSecurityToken)validatedToken;
return jwtToken;
}
//IDX10223: Lifetime validation failed. The token is expired. ValidTo: 'System.DateTime', Current time: 'System.DateTime'.
catch (SecurityTokenExpiredException ex)
{
throw ex;
}
catch (Exception ex)
{
// return null if validation fails
throw ex;
}
}
public static LdapUser RenewLdapUserWithJwtToken(string token)
{
LdapUser renewLdapUser = null;
try
{
if (string.IsNullOrEmpty(token))
{
throw new ArgumentNullException($"Token is missing!");
}
renewLdapUser = LdapAuthenticationService.RenewIdentity(token);
if (renewLdapUser is null)
{
throw new Exception($"Can't renew from token!");
}
if (!renewLdapUser.IsValidatCredentials)
{
throw new Exception($"Invalid credentials!");
}
if (!renewLdapUser.Enabled)
{
throw new Exception($"Ldap-User is disabled!");
}
(string newtoken, DateTime newExpiredOn) = CreateToken(renewLdapUser);
renewLdapUser.Token = newtoken;
renewLdapUser.JwtExpiredOn = newExpiredOn;
if (!renewLdapUser.IsValid())
{
throw new Exception($"Ldapuser is not valid!");
}
return renewLdapUser;
}
catch (Exception ex)
{
throw ex;
}
}
public static LdapUser RenewLdapUserWithJwtToken(LdapUser ldapUser)
{
LdapUser renewLdapUser = null;
try
{
if (string.IsNullOrEmpty(ldapUser?.Token))
{
throw new Exception($"Token is missing (Login:{ldapUser.LoginName})");
}
renewLdapUser = LdapAuthenticationService.RenewIdentity(ldapUser);
if (renewLdapUser is null)
{
return default;
}
//if (!ldapUser.IsValidatCredentials)
//{
// ldapUser.Token = string.Empty;
// return false;
//}
if (!renewLdapUser.Enabled)
{
renewLdapUser.Token = string.Empty;
return renewLdapUser;
}
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(JwtTokenConfig.Secret);
var claims = CreateClaimsIdentity(renewLdapUser);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = claims,
Expires = DateTime.UtcNow.AddMinutes(JwtTokenConfig.ExpirationInMin),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
ldapUser.Token = tokenHandler.WriteToken(token);
ldapUser.JwtExpiredOn = token.ValidTo;
if (renewLdapUser.IsValid())
{
return renewLdapUser;
}
return default;
}
catch (Exception ex)
{
throw ex;
}
}
public static bool GenerateLdapUserWithJwtToken(LdapUser ldapUser)
{
try
{
if (!LdapAuthenticationService.CheckAndUpdateIdentityWithPassword(ldapUser))
{
return false;
}
if (!ldapUser.IsValidatCredentials)
{
ldapUser.Token = string.Empty;
return false;
}
if (!ldapUser.Enabled)
{
ldapUser.Token = string.Empty;
return false;
}
(string token, DateTime jwtExpiredOn) = CreateToken(ldapUser);
ldapUser.Token = token;
ldapUser.JwtExpiredOn = jwtExpiredOn;
return ldapUser.IsValid();
}
catch (Exception ex)
{
throw ex;
}
}
public static string GenerateHash(string password)
{
return JWTCrypt.SHA512(password);
}
private static (string, DateTime) CreateToken(LdapUser ldapUser)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(JwtTokenConfig.Secret);
var claims = CreateClaimsIdentity(ldapUser);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = claims,
Expires = DateTime.UtcNow.AddMinutes(JwtTokenConfig.ExpirationInMin),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return (tokenHandler.WriteToken(token), token.ValidTo);
}
public static bool IsValidatJwtTokenSubject(string token)
{
if (string.IsNullOrEmpty(token))
{
return false;
}
token = token.Trim();
if (token.IndexOf(" ", StringComparison.InvariantCultureIgnoreCase) > 0)
{
if (token.StartsWith("Bearer", StringComparison.InvariantCultureIgnoreCase)) //token with "Bearer" prefix
{
token = token.Split(" ").Last();
}
else
{
token = token.Split(" ").First();
}
}
try
{
var jwtToken = DecryptToken(token);
return !String.IsNullOrEmpty(jwtToken?.Subject); //Loginname
}
catch (Exception ex)
{
throw ex;
}
}
private static LdapUser ClaimsIdentityToLdapUser(List<Claim> claims)
{
LdapUser user = new LdapUser("");
foreach (var claim in claims)
{
switch (claim.Type)
{
case JwtRegisteredClaimNames.Sub:
user.LoginName = claim.Value;
break;
case JwtRegisteredClaimNames.Email:
user.Email = claim.Value;
break;
case JwtRegisteredClaimNames.NameId:
{
if (int.TryParse(claim.Value, out int id))
{
user.UserId = id;
}
}
break;
case JwtRegisteredClaimNames.Jti:
{
if (Guid.TryParse(claim.Value, out Guid g))
{
user.LdapGuid = g;
}
}
break;
case JwtGlobals.CLAIM_DEPARTNENTID:
user.DepartmentId = int.Parse(claim.Value);
break;
case JwtGlobals.CLAIM_EXTENDETDEPARTNENTIDLIST:
user.ExtendedDepartmentIdList = claim.Value;
break;
case JwtGlobals.CLAIM_ROLE:
user.AddRole(claim.Value);
break;
case JwtRegisteredClaimNames.Exp:
{
//#pragma warning disable CA1305 // Specify IFormatProvider
var expValue = Convert.ToInt32(claim.Value);
//#pragma warning restore CA1305 // Specify IFormatProvider
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(expValue);
user.JwtExpiredOn = dateTimeOffset.UtcDateTime;
}
break;
case var s when claim.Type.StartsWith(GlbExtendedAttributes):
var strKey = claim.Type.Substring(GlbExtendedAttributes.Length, claim.Type.Length - GlbExtendedAttributes.Length);
user.ExtendedAttributesList.Add(new KeyValuePair<string, string>(strKey, claim.Value));
break;
default:
break;
}
}
return user;
}
private static ClaimsIdentity CreateClaimsIdentity(LdapUser user)
{
ClaimsIdentity claimsIdentity = new ClaimsIdentity();
List<Claim> claims = new List<Claim>
{
CreateClaim(JwtRegisteredClaimNames.Sub, user.LoginName),
CreateClaim(JwtRegisteredClaimNames.NameId, user.UserId),
CreateClaim(JwtRegisteredClaimNames.Email, user.Email),
CreateClaim(JwtGlobals.CLAIM_DEPARTNENTID, user.DepartmentId),
CreateClaim(JwtGlobals.CLAIM_EXTENDETDEPARTNENTIDLIST, user.ExtendedDepartmentIdList)
};
user.RoleList.ForEach(role => claims.Add(
CreateClaim(ClaimTypes.Role, role.Role)
));
user.ExtendedAttributesList.ForEach(item => claims.Add(
CreateClaim($"{GlbExtendedAttributes}{item.Key}", item.Value)
));
claimsIdentity.AddClaims(claims);
return claimsIdentity;
}
private static Claim CreateClaim(string claimName, int claimValue)
{
return new Claim(claimName, string.IsNullOrEmpty($"{claimValue}") ? string.Empty : $"{claimValue}");
}
private static Claim CreateClaim(string claimName, string claimValue)
{
return new Claim(claimName, string.IsNullOrEmpty(claimValue) ? string.Empty : claimValue);
}
}
}

View File

@ -0,0 +1,97 @@
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Net.Mime;
using System.Threading.Tasks;
namespace HRD.LDAPService.JWT
{
public class JwtMiddleware
{
private readonly RequestDelegate _next;
public JwtMiddleware(RequestDelegate next)
{
_next = next;
}
#pragma warning disable AMNF0001 // Asynchronous method name is not ending with 'Async'
public async Task Invoke(HttpContext httpContext)
#pragma warning restore AMNF0001 // Asynchronous method name is not ending with 'Async'
{
if (httpContext == null)
{
throw new ArgumentNullException($"Jwt {httpContext} is null");
}
if (JwtTokenConfig.AktivateAuthorizationFilter)
{
var path = httpContext.Request.Path.Value;
if (!string.IsNullOrEmpty(path))
{
if (JwtTokenConfig.IsInBlackList(path))
{
httpContext.Response.ContentType = MediaTypeNames.Application.Json;
httpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
var responseJson = JsonConvert.SerializeObject($"Path is in a blacklist: '${path}'");
await httpContext.Response.WriteAsync(responseJson).ConfigureAwait(false);
return;
}
if (JwtTokenConfig.IsInWhiteList(path))
{
await _next(httpContext).ConfigureAwait(false); // calling next middleware
return;
}
}
}
var headerAuthorization = httpContext.Request.Headers["Authorization"];
var authorizationType = headerAuthorization.FirstOrDefault()?.Split(" ").First();
if (authorizationType == null)
{
await _next(httpContext).ConfigureAwait(false); // calling next middleware
return;
}
var jwt = headerAuthorization.FirstOrDefault();
//Check token
if (JwtManager.IsValidatJwtTokenSubject(jwt))
{
var user = JwtManager.DecryptTokenAsLdapUser(jwt);
if (user == default)
{
httpContext.Response.ContentType = MediaTypeNames.Application.Json;
httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
var responseJson = JsonConvert.SerializeObject($"Failed to decode JWT. The User was not valid");
await httpContext.Response.WriteAsync(responseJson).ConfigureAwait(false);
return;
}
httpContext.Items[JwtGlobals.HttpContextItem_IsValidHenselToken] = "true";
httpContext.Items[JwtGlobals.HttpContextItem_LdapUser] = user;
await _next(httpContext).ConfigureAwait(false); // calling next middleware
return;
}
else
{
httpContext.Response.ContentType = MediaTypeNames.Application.Json;
httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
var responseJson = JsonConvert.SerializeObject($"The JWT was not valid.");
await httpContext.Response.WriteAsync(responseJson).ConfigureAwait(false);
return;
}
}
private string GetAction(HttpContext httpContext)
{
if (httpContext.Request.Headers.ContainsKey("action"))
{
return httpContext.Request.Headers["action"].ToString();
}
return string.Empty;
}
}
}

View File

@ -0,0 +1,69 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Security.Claims;
using System.Text;
namespace HRD.LDAPService.JWT
{
public static class JwtMiddlewareExtensions
{
public static IApplicationBuilder UseJwtMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<JwtMiddleware>();
}
public static void ConfigureJWT(this IServiceCollection services, JwtMiddlewareOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
JwtTokenConfig.DeaktivateLDAP = options.DeaktivateLDAP; //if true => use login + pwd only
JwtTokenConfig.Secret = options.Secret;
JwtTokenConfig.Issuer = options.Issuer;
JwtTokenConfig.Audience = options.Audience;
JwtTokenConfig.JwtRoleList = options.JwtRoleList;
JwtTokenConfig.ExpirationInMin = options.ExpirationInMin;
JwtTokenConfig.AktivateAuthorizationFilter = options.AktivateAuthorizationFilter;
JwtTokenConfig.AuthorizationFilterWhitelistPath = options.AuthorizationFilterWhitelistPath;
JwtTokenConfig.AuthorizationFilterBlacklistPath = options.AuthorizationFilterBlacklistPath;
//Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
//JwtBearer
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.RequireHttpsMetadata = true;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = JwtTokenConfig.Issuer, //JWT-Site
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtTokenConfig.Secret)),
ValidAudience = JwtTokenConfig.Audience,
ValidateAudience = true, //App-Site
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(1),
NameClaimType = ClaimTypes.NameIdentifier
};
});
//Authorization
services.AddAuthorization(authopt =>
{
authopt.AddPolicy("UserMustHaveRole", polBuilder => polBuilder.RequireClaim(ClaimTypes.Role));
});
}
}
}

View File

@ -0,0 +1,18 @@
using System.Collections.Generic;
namespace HRD.LDAPService.JWT
{
public class JwtMiddlewareOptions
{
public string Secret { get; set; }
public int ExpirationInMin { get; set; } = 60 * 24 * 28; //28 Tage
public List<JwtRole> JwtRoleList { get; set; }
public List<string> AuthorizationFilterWhitelistPath { get; set; }
public List<string> AuthorizationFilterBlacklistPath { get; set; }
public bool AktivateAuthorizationFilter { get; set; } = true;
public string Issuer { get; set; }
public string Audience { get; set; }
public bool DeaktivateLDAP { get; set; }
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.ComponentModel.DataAnnotations;
namespace HRD.LDAPService
{
public class JwtRole
{
private string role;
private string _group;
public JwtRole(string role) : this(role, string.Empty)
{ }
public JwtRole(string role, string group)
{
Role = role;
Group = group;
}
[Required]
public string Role { get => role; set => role = value; }
[Required]
public string Group
{
get => _group;
//"dhr/" prefix should be removed
set => _group = string.IsNullOrEmpty(value) ? string.Empty : value.Replace(@"DHR\", "", StringComparison.InvariantCultureIgnoreCase);
}
}
}

View File

@ -0,0 +1,49 @@
using System.Collections.Generic;
namespace HRD.LDAPService.JWT
{
public static class JwtTokenConfig
{
private static string secret;
public static int ExpirationInMin { get; set; }
public static string Secret { get; set; }
public static string Issuer { get; internal set; }
public static string Audience { get; internal set; }
#warning use internal setter
public static List<JwtRole> JwtRoleList { get; set; } = new List<JwtRole>();
public static List<string> AuthorizationFilterWhitelistPath { get; set; }
public static List<string> AuthorizationFilterBlacklistPath { get; set; }
public static bool AktivateAuthorizationFilter { get; set; }
public static bool DeaktivateLDAP { get; set; }
public static bool IsInWhiteList(string path)
{
if (string.IsNullOrEmpty(path)) { return false; }
foreach (var item in JwtTokenConfig.AuthorizationFilterWhitelistPath)
{
if (path.Contains(item, System.StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
public static bool IsInBlackList(string path)
{
if (string.IsNullOrEmpty(path)) { return false; }
foreach (var item in JwtTokenConfig.AuthorizationFilterBlacklistPath)
{
if (path.Contains(item, System.StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
}
}

View File

@ -0,0 +1,9 @@
namespace HRD.LDAPService
{
public enum EN_LdapRoleListFilter
{
All = 1,
OnlyRoleList = 2,
OnlyWebAppRoleList = 3
}
}

View 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);
}
}
}
}

View 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;
}
}
}

View 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";
}
}

View 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;
}
}
}
}

View 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} ";
}
}
}

View File

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp7.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="xunit" Version="2.8.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HRD.LDAPService\HRD.LDAPService.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,134 @@
using HRD.LDAPService;
using HRD.LDAPService.JWT;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using Xunit;
namespace HRD.LdapService.Text
{
public class LdapTest
{
private static void InitJWTConfig(bool deaktivateLDAP = false)
{
var list = new List<JwtRole>();
var ADGroupPrefix = "";
//Admin Role
list.Add(new JwtRole(JwtGlobals.ROLE_ADMIN, "GG_WebApp" + ADGroupPrefix + "_Visitors_Admin"));
//Core RoleList
list.Add(new JwtRole(JwtGlobals.ROLE_USER, "GG_WebApp" + ADGroupPrefix + "_Visitors_User")); //(RO) nur eigene
list.Add(new JwtRole(JwtGlobals.ROLE_MASTER, "GG_WebApp" + ADGroupPrefix + "_Visitors_Master")); //RW ALLE Abteilungen
list.Add(new JwtRole(JwtGlobals.ROLE_DEPARTMENTUSER, "GG_WebApp" + ADGroupPrefix + "_Visitors_DepartmentUser")); //(RW) auch andere aus eigener Abteilung
list.Add(new JwtRole(JwtGlobals.ROLE_DEPARTMENTMASTER, "GG_WebApp" + ADGroupPrefix + "_Visitors_DepartmentMaster")); //(RW) auch andere aus eigener Abteilung
//WebApp RoleList
list.Add(new JwtRole("Ipad", "GG_WebApp" + ADGroupPrefix + "_Visitors_Ipad")); //RW ALLE Abteilungen
list.Add(new JwtRole("Security", "GG_WebApp" + ADGroupPrefix + "_Visitors_Security")); //RW ALLE Abteilungen
JwtTokenConfig.JwtRoleList = list;
JwtTokenConfig.Secret = "12345678901234567809_WEBAPISERVER";
JwtTokenConfig.ExpirationInMin = 60 * 1 * 100; //100 min
JwtTokenConfig.DeaktivateLDAP = deaktivateLDAP;
}
[Fact]
public void Renew_LDAP()
{
InitJWTConfig(false);
var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ2LmJvamFyc2tpIiwibmFtZWlkIjoiMCIsImVtYWlsIjoiVi5Cb2phcnNraUBoZW5zZWwtcmVjeWNsaW5nLmNvbSIsImRlcGFydG1lbnRpZCI6IjAiLCJleHRlbmRldGRlcGFydG1lbnRpZGxpc3QiOiIiLCJFeHRlbmRlZEF0dHJpYnV0ZXNfUmVnaW9uIjoiMTAsMjAiLCJFeHRlbmRlZEF0dHJpYnV0ZXNfQXR0cmlidXQjMSI6IkFCQ0BBQkMuREUsREVGQEFCQy5ERSxHRUhAQUJDLkRFIiwibmJmIjoxNjU4NzU4NDE0LCJleHAiOjE2NTkxMTg0MTQsImlhdCI6MTY1ODc1ODQxNH0.KUODwRBRn-xc3-0RaVKJ0uzwsXZ7RgORRAZUzTfxfNk";
var loginName = "v.bojarski";
LdapUser renewLdapUser = JwtManager.RenewLdapUserWithJwtToken(token);
Assert.Same(renewLdapUser.LoginName, loginName);
Assert.True(renewLdapUser.IsValid());
}
[Fact]
public void Login_LDAP()
{
InitJWTConfig();
//JwtTokenConfig.ExpirationInMin = 60 * 24 * 30 * 12; //12 Month
var LoginName = "visitoripad2";
var Password = "HenselVisitor2020!";
LdapUser ldapUser = new LdapUser(LoginName);
ldapUser.Password = Password;
List<KeyValuePair<string, string>> extendedAttributesList = new List<KeyValuePair<string, string>>();
//List<KeyValuePair<string, List<string>>> extendedAttributesList = new();
//List<string> list = new() { "10,20" };
extendedAttributesList.Add(new KeyValuePair<string, string>("VendorId", "100210"));
extendedAttributesList.Add(new KeyValuePair<string, string>("Region", "10,20"));
extendedAttributesList.Add(new KeyValuePair<string, string>("Attribut#1", "ABC@ABC.DE,DEF@ABC.DE,GEH@ABC.DE"));
ldapUser.ExtendedAttributesList = extendedAttributesList;
var isOk = JwtManager.GenerateLdapUserWithJwtToken(ldapUser);
LdapUser ldapUserWithJWT = new LdapUser(ldapUser.LoginName);
ldapUserWithJWT.Token = ldapUser.Token;
extendedAttributesList = new List<KeyValuePair<string, string>>();
extendedAttributesList.Add(new KeyValuePair<string, string>("Attribut#1", "ABC@ABC.DE,DEF@ABC.DE,GEH@ABC.DE"));
ldapUser.ExtendedAttributesList = extendedAttributesList;
var renewLdapUserWithJWT = LdapAuthenticationService.RenewIdentity( ldapUserWithJWT);
Assert.True(renewLdapUserWithJWT.IsValid());
}
[Fact]
public void JWT_GeneratePasswordHash()
{
InitJWTConfig(true);
var LoginName = "visitoripad2";
var Password = "HenselVisitor2020!";
LdapUser ldapUser = new LdapUser(LoginName);
ldapUser.Password = Password;
//var passwordHash = JWTCrypt.GenerateHashPassword(ldapUser.Password);
ldapUser.AddExtendedAttribute("Attribut#1", "ABC@ABC.DE,DEF@ABC.DE,GEH@ABC.DE");
ldapUser.AddExtendedAttribute("VendorId", "100210");
var isOk = JwtManager.GenerateLdapUserWithJwtToken(ldapUser);
LdapUser ldapUserWithJWT = new LdapUser(ldapUser.LoginName);
ldapUserWithJWT.Token = ldapUser.Token;
ldapUserWithJWT.PasswordHash = ldapUser.PasswordHash;
var renewLdapUserWithJWT = LdapAuthenticationService.RenewIdentity(ldapUserWithJWT);
LdapUser ldapUser2 = new LdapUser(LoginName);
ldapUser2.PasswordHash = ldapUser.PasswordHash;
var returLdapUser = JwtManager.RenewLdapUserWithJwtToken(ldapUserWithJWT);
Assert.Equal(ldapUser.PasswordHashShort, ldapUserWithJWT.PasswordHashShort);
Assert.True(renewLdapUserWithJWT.IsValid());
}
[Fact]
public void Add_User_To_Group()
{
var loginName = "v.bojarski";
var groupName = "GG_WebApp__Test_Apps_User";
Assert.True(LdapManager.AD_AddUserloginToGroup(loginName, groupName));
}
}
}

Some files were not shown because too many files have changed in this diff Show More