diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/AbpIdentityApplicationContractsModule.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/AbpIdentityApplicationContractsModule.cs index 253d5385d9..43dbf4ccdf 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/AbpIdentityApplicationContractsModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/AbpIdentityApplicationContractsModule.cs @@ -6,43 +6,42 @@ using Volo.Abp.PermissionManagement; using Volo.Abp.Users; using Volo.Abp.Threading; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[DependsOn( + typeof(AbpIdentityDomainSharedModule), + typeof(AbpUsersAbstractionModule), + typeof(AbpAuthorizationModule), + typeof(AbpPermissionManagementApplicationContractsModule) + )] +public class AbpIdentityApplicationContractsModule : AbpModule { - [DependsOn( - typeof(AbpIdentityDomainSharedModule), - typeof(AbpUsersAbstractionModule), - typeof(AbpAuthorizationModule), - typeof(AbpPermissionManagementApplicationContractsModule) - )] - public class AbpIdentityApplicationContractsModule : AbpModule - { - private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); + private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); - public override void ConfigureServices(ServiceConfigurationContext context) - { + public override void ConfigureServices(ServiceConfigurationContext context) + { - } + } - public override void PostConfigureServices(ServiceConfigurationContext context) + public override void PostConfigureServices(ServiceConfigurationContext context) + { + OneTimeRunner.Run(() => { - OneTimeRunner.Run(() => - { - ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToApi( - IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.Role, - getApiTypes: new[] { typeof(IdentityRoleDto) }, - createApiTypes: new[] { typeof(IdentityRoleCreateDto) }, - updateApiTypes: new[] { typeof(IdentityRoleUpdateDto) } - ); + ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToApi( + IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.Role, + getApiTypes: new[] { typeof(IdentityRoleDto) }, + createApiTypes: new[] { typeof(IdentityRoleCreateDto) }, + updateApiTypes: new[] { typeof(IdentityRoleUpdateDto) } + ); - ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToApi( - IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.User, - getApiTypes: new[] { typeof(IdentityUserDto) }, - createApiTypes: new[] { typeof(IdentityUserCreateDto) }, - updateApiTypes: new[] { typeof(IdentityUserUpdateDto) } - ); - }); - } + ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToApi( + IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.User, + getApiTypes: new[] { typeof(IdentityUserDto) }, + createApiTypes: new[] { typeof(IdentityUserCreateDto) }, + updateApiTypes: new[] { typeof(IdentityUserUpdateDto) } + ); + }); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityRolesInput.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityRolesInput.cs index c5db3405a8..270075ae6a 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityRolesInput.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityRolesInput.cs @@ -1,9 +1,8 @@ using Volo.Abp.Application.Dtos; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class GetIdentityRolesInput : PagedAndSortedResultRequestDto { - public class GetIdentityRolesInput : PagedAndSortedResultRequestDto - { - public string Filter { get; set; } - } + public string Filter { get; set; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityUsersInput.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityUsersInput.cs index 29c6e296e7..fab945b4e3 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityUsersInput.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityUsersInput.cs @@ -1,9 +1,8 @@ using Volo.Abp.Application.Dtos; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class GetIdentityUsersInput : PagedAndSortedResultRequestDto { - public class GetIdentityUsersInput : PagedAndSortedResultRequestDto - { - public string Filter { get; set; } - } + public string Filter { get; set; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityRoleAppService.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityRoleAppService.cs index 2bd855927d..26b729f880 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityRoleAppService.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityRoleAppService.cs @@ -3,16 +3,15 @@ using System.Threading.Tasks; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IIdentityRoleAppService + : ICrudAppService< + IdentityRoleDto, + Guid, + GetIdentityRolesInput, + IdentityRoleCreateDto, + IdentityRoleUpdateDto> { - public interface IIdentityRoleAppService - : ICrudAppService< - IdentityRoleDto, - Guid, - GetIdentityRolesInput, - IdentityRoleCreateDto, - IdentityRoleUpdateDto> - { - Task> GetAllListAsync(); - } + Task> GetAllListAsync(); } diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityUserAppService.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityUserAppService.cs index db6cbdfe38..55946e21ab 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityUserAppService.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityUserAppService.cs @@ -3,24 +3,23 @@ using System.Threading.Tasks; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IIdentityUserAppService + : ICrudAppService< + IdentityUserDto, + Guid, + GetIdentityUsersInput, + IdentityUserCreateDto, + IdentityUserUpdateDto> { - public interface IIdentityUserAppService - : ICrudAppService< - IdentityUserDto, - Guid, - GetIdentityUsersInput, - IdentityUserCreateDto, - IdentityUserUpdateDto> - { - Task> GetRolesAsync(Guid id); + Task> GetRolesAsync(Guid id); - Task> GetAssignableRolesAsync(); + Task> GetAssignableRolesAsync(); - Task UpdateRolesAsync(Guid id, IdentityUserUpdateRolesDto input); + Task UpdateRolesAsync(Guid id, IdentityUserUpdateRolesDto input); - Task FindByUsernameAsync(string userName); + Task FindByUsernameAsync(string userName); - Task FindByEmailAsync(string email); - } + Task FindByEmailAsync(string email); } diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityUserLookupAppService.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityUserLookupAppService.cs index 2b1b1de331..7a14579af5 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityUserLookupAppService.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityUserLookupAppService.cs @@ -4,16 +4,15 @@ using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IIdentityUserLookupAppService : IApplicationService { - public interface IIdentityUserLookupAppService : IApplicationService - { - Task FindByIdAsync(Guid id); + Task FindByIdAsync(Guid id); + + Task FindByUserNameAsync(string userName); - Task FindByUserNameAsync(string userName); + Task> SearchAsync(UserLookupSearchInputDto input); - Task> SearchAsync(UserLookupSearchInputDto input); - - Task GetCountAsync(UserLookupCountInputDto input); - } + Task GetCountAsync(UserLookupCountInputDto input); } diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityPermissionDefinitionProvider.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityPermissionDefinitionProvider.cs index 14c12adde2..c04bdf2c49 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityPermissionDefinitionProvider.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityPermissionDefinitionProvider.cs @@ -2,34 +2,33 @@ using Volo.Abp.Identity.Localization; using Volo.Abp.Localization; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityPermissionDefinitionProvider : PermissionDefinitionProvider { - public class IdentityPermissionDefinitionProvider : PermissionDefinitionProvider + public override void Define(IPermissionDefinitionContext context) { - public override void Define(IPermissionDefinitionContext context) - { - var identityGroup = context.AddGroup(IdentityPermissions.GroupName, L("Permission:IdentityManagement")); + var identityGroup = context.AddGroup(IdentityPermissions.GroupName, L("Permission:IdentityManagement")); - var rolesPermission = identityGroup.AddPermission(IdentityPermissions.Roles.Default, L("Permission:RoleManagement")); - rolesPermission.AddChild(IdentityPermissions.Roles.Create, L("Permission:Create")); - rolesPermission.AddChild(IdentityPermissions.Roles.Update, L("Permission:Edit")); - rolesPermission.AddChild(IdentityPermissions.Roles.Delete, L("Permission:Delete")); - rolesPermission.AddChild(IdentityPermissions.Roles.ManagePermissions, L("Permission:ChangePermissions")); + var rolesPermission = identityGroup.AddPermission(IdentityPermissions.Roles.Default, L("Permission:RoleManagement")); + rolesPermission.AddChild(IdentityPermissions.Roles.Create, L("Permission:Create")); + rolesPermission.AddChild(IdentityPermissions.Roles.Update, L("Permission:Edit")); + rolesPermission.AddChild(IdentityPermissions.Roles.Delete, L("Permission:Delete")); + rolesPermission.AddChild(IdentityPermissions.Roles.ManagePermissions, L("Permission:ChangePermissions")); - var usersPermission = identityGroup.AddPermission(IdentityPermissions.Users.Default, L("Permission:UserManagement")); - usersPermission.AddChild(IdentityPermissions.Users.Create, L("Permission:Create")); - usersPermission.AddChild(IdentityPermissions.Users.Update, L("Permission:Edit")); - usersPermission.AddChild(IdentityPermissions.Users.Delete, L("Permission:Delete")); - usersPermission.AddChild(IdentityPermissions.Users.ManagePermissions, L("Permission:ChangePermissions")); + var usersPermission = identityGroup.AddPermission(IdentityPermissions.Users.Default, L("Permission:UserManagement")); + usersPermission.AddChild(IdentityPermissions.Users.Create, L("Permission:Create")); + usersPermission.AddChild(IdentityPermissions.Users.Update, L("Permission:Edit")); + usersPermission.AddChild(IdentityPermissions.Users.Delete, L("Permission:Delete")); + usersPermission.AddChild(IdentityPermissions.Users.ManagePermissions, L("Permission:ChangePermissions")); - identityGroup - .AddPermission(IdentityPermissions.UserLookup.Default, L("Permission:UserLookup")) - .WithProviders(ClientPermissionValueProvider.ProviderName); - } + identityGroup + .AddPermission(IdentityPermissions.UserLookup.Default, L("Permission:UserLookup")) + .WithProviders(ClientPermissionValueProvider.ProviderName); + } - private static LocalizableString L(string name) - { - return LocalizableString.Create(name); - } + private static LocalizableString L(string name) + { + return LocalizableString.Create(name); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityPermissions.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityPermissions.cs index e22869295f..de38cedc86 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityPermissions.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityPermissions.cs @@ -1,37 +1,36 @@ using Volo.Abp.Reflection; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class IdentityPermissions { - public static class IdentityPermissions - { - public const string GroupName = "AbpIdentity"; + public const string GroupName = "AbpIdentity"; - public static class Roles - { - public const string Default = GroupName + ".Roles"; - public const string Create = Default + ".Create"; - public const string Update = Default + ".Update"; - public const string Delete = Default + ".Delete"; - public const string ManagePermissions = Default + ".ManagePermissions"; - } + public static class Roles + { + public const string Default = GroupName + ".Roles"; + public const string Create = Default + ".Create"; + public const string Update = Default + ".Update"; + public const string Delete = Default + ".Delete"; + public const string ManagePermissions = Default + ".ManagePermissions"; + } - public static class Users - { - public const string Default = GroupName + ".Users"; - public const string Create = Default + ".Create"; - public const string Update = Default + ".Update"; - public const string Delete = Default + ".Delete"; - public const string ManagePermissions = Default + ".ManagePermissions"; - } + public static class Users + { + public const string Default = GroupName + ".Users"; + public const string Create = Default + ".Create"; + public const string Update = Default + ".Update"; + public const string Delete = Default + ".Delete"; + public const string ManagePermissions = Default + ".ManagePermissions"; + } - public static class UserLookup - { - public const string Default = GroupName + ".UserLookup"; - } + public static class UserLookup + { + public const string Default = GroupName + ".UserLookup"; + } - public static string[] GetAll() - { - return ReflectionHelper.GetPublicConstantsRecursively(typeof(IdentityPermissions)); - } + public static string[] GetAll() + { + return ReflectionHelper.GetPublicConstantsRecursively(typeof(IdentityPermissions)); } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRemoteServiceConsts.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRemoteServiceConsts.cs index 667fbbece2..9848cd10c6 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRemoteServiceConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRemoteServiceConsts.cs @@ -1,9 +1,8 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class IdentityRemoteServiceConsts { - public static class IdentityRemoteServiceConsts - { - public const string RemoteServiceName = "AbpIdentity"; + public const string RemoteServiceName = "AbpIdentity"; - public const string ModuleName = "identity"; - } + public const string ModuleName = "identity"; } diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleCreateDto.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleCreateDto.cs index d98edfb638..bb8d3b36a3 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleCreateDto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleCreateDto.cs @@ -1,7 +1,6 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityRoleCreateDto : IdentityRoleCreateOrUpdateDtoBase { - public class IdentityRoleCreateDto : IdentityRoleCreateOrUpdateDtoBase - { - } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleCreateOrUpdateDtoBase.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleCreateOrUpdateDtoBase.cs index 6b68c43568..61e6eee2a5 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleCreateOrUpdateDtoBase.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleCreateOrUpdateDtoBase.cs @@ -2,21 +2,20 @@ using Volo.Abp.ObjectExtending; using Volo.Abp.Validation; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityRoleCreateOrUpdateDtoBase : ExtensibleObject { - public class IdentityRoleCreateOrUpdateDtoBase : ExtensibleObject - { - [Required] - [DynamicStringLength(typeof(IdentityRoleConsts), nameof(IdentityRoleConsts.MaxNameLength))] - public string Name { get; set; } + [Required] + [DynamicStringLength(typeof(IdentityRoleConsts), nameof(IdentityRoleConsts.MaxNameLength))] + public string Name { get; set; } - public bool IsDefault { get; set; } + public bool IsDefault { get; set; } - public bool IsPublic { get; set; } + public bool IsPublic { get; set; } + + protected IdentityRoleCreateOrUpdateDtoBase() : base(false) + { - protected IdentityRoleCreateOrUpdateDtoBase() : base(false) - { - - } } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleDto.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleDto.cs index ae5d8a5feb..71185cf288 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleDto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleDto.cs @@ -2,18 +2,17 @@ using Volo.Abp.Application.Dtos; using Volo.Abp.Domain.Entities; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityRoleDto : ExtensibleEntityDto, IHasConcurrencyStamp { - public class IdentityRoleDto : ExtensibleEntityDto, IHasConcurrencyStamp - { - public string Name { get; set; } + public string Name { get; set; } + + public bool IsDefault { get; set; } - public bool IsDefault { get; set; } - - public bool IsStatic { get; set; } + public bool IsStatic { get; set; } - public bool IsPublic { get; set; } + public bool IsPublic { get; set; } - public string ConcurrencyStamp { get; set; } - } -} \ No newline at end of file + public string ConcurrencyStamp { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleUpdateDto.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleUpdateDto.cs index c8a44f92c2..b57745ab02 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleUpdateDto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleUpdateDto.cs @@ -1,9 +1,8 @@ using Volo.Abp.Domain.Entities; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityRoleUpdateDto : IdentityRoleCreateOrUpdateDtoBase, IHasConcurrencyStamp { - public class IdentityRoleUpdateDto : IdentityRoleCreateOrUpdateDtoBase, IHasConcurrencyStamp - { - public string ConcurrencyStamp { get; set; } - } -} \ No newline at end of file + public string ConcurrencyStamp { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserCreateDto.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserCreateDto.cs index a080a7e33e..064673d8e7 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserCreateDto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserCreateDto.cs @@ -2,13 +2,12 @@ using System.ComponentModel.DataAnnotations; using Volo.Abp.Auditing; using Volo.Abp.Validation; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUserCreateDto : IdentityUserCreateOrUpdateDtoBase { - public class IdentityUserCreateDto : IdentityUserCreateOrUpdateDtoBase - { - [DisableAuditing] - [Required] - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))] - public string Password { get; set; } - } -} \ No newline at end of file + [DisableAuditing] + [Required] + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))] + public string Password { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserCreateOrUpdateDtoBase.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserCreateOrUpdateDtoBase.cs index 3b6959b60c..c7e11b38ce 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserCreateOrUpdateDtoBase.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserCreateOrUpdateDtoBase.cs @@ -4,38 +4,37 @@ using JetBrains.Annotations; using Volo.Abp.ObjectExtending; using Volo.Abp.Validation; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class IdentityUserCreateOrUpdateDtoBase : ExtensibleObject { - public abstract class IdentityUserCreateOrUpdateDtoBase : ExtensibleObject - { - [Required] - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxUserNameLength))] - public string UserName { get; set; } + [Required] + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxUserNameLength))] + public string UserName { get; set; } - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxNameLength))] - public string Name { get; set; } + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxNameLength))] + public string Name { get; set; } - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxSurnameLength))] - public string Surname { get; set; } + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxSurnameLength))] + public string Surname { get; set; } - [Required] - [EmailAddress] - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxEmailLength))] - public string Email { get; set; } + [Required] + [EmailAddress] + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxEmailLength))] + public string Email { get; set; } - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPhoneNumberLength))] - public string PhoneNumber { get; set; } + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPhoneNumberLength))] + public string PhoneNumber { get; set; } - public bool IsActive { get; set; } + public bool IsActive { get; set; } - public bool LockoutEnabled { get; set; } + public bool LockoutEnabled { get; set; } - [CanBeNull] - public string[] RoleNames { get; set; } + [CanBeNull] + public string[] RoleNames { get; set; } - protected IdentityUserCreateOrUpdateDtoBase() : base(false) - { + protected IdentityUserCreateOrUpdateDtoBase() : base(false) + { - } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserDto.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserDto.cs index f3b03ab8dc..e20b8d715b 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserDto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserDto.cs @@ -3,32 +3,31 @@ using Volo.Abp.Application.Dtos; using Volo.Abp.Domain.Entities; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUserDto : ExtensibleFullAuditedEntityDto, IMultiTenant, IHasConcurrencyStamp { - public class IdentityUserDto : ExtensibleFullAuditedEntityDto, IMultiTenant, IHasConcurrencyStamp - { - public Guid? TenantId { get; set; } + public Guid? TenantId { get; set; } - public string UserName { get; set; } + public string UserName { get; set; } - public string Name { get; set; } + public string Name { get; set; } - public string Surname { get; set; } + public string Surname { get; set; } - public string Email { get; set; } + public string Email { get; set; } - public bool EmailConfirmed { get; set; } + public bool EmailConfirmed { get; set; } - public string PhoneNumber { get; set; } + public string PhoneNumber { get; set; } - public bool PhoneNumberConfirmed { get; set; } + public bool PhoneNumberConfirmed { get; set; } - public bool IsActive { get; set; } + public bool IsActive { get; set; } - public bool LockoutEnabled { get; set; } + public bool LockoutEnabled { get; set; } - public DateTimeOffset? LockoutEnd { get; set; } + public DateTimeOffset? LockoutEnd { get; set; } - public string ConcurrencyStamp { get; set; } - } + public string ConcurrencyStamp { get; set; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserUpdateDto.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserUpdateDto.cs index aa499bf2cd..f236977973 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserUpdateDto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserUpdateDto.cs @@ -3,14 +3,13 @@ using Volo.Abp.Auditing; using Volo.Abp.Domain.Entities; using Volo.Abp.Validation; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUserUpdateDto : IdentityUserCreateOrUpdateDtoBase, IHasConcurrencyStamp { - public class IdentityUserUpdateDto : IdentityUserCreateOrUpdateDtoBase, IHasConcurrencyStamp - { - [DisableAuditing] - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))] - public string Password { get; set; } - - public string ConcurrencyStamp { get; set; } - } -} \ No newline at end of file + [DisableAuditing] + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))] + public string Password { get; set; } + + public string ConcurrencyStamp { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserUpdateRolesDto.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserUpdateRolesDto.cs index c6f86669b4..3d389c7bd4 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserUpdateRolesDto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserUpdateRolesDto.cs @@ -1,10 +1,9 @@ using System.ComponentModel.DataAnnotations; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUserUpdateRolesDto { - public class IdentityUserUpdateRolesDto - { - [Required] - public string[] RoleNames { get; set; } - } -} \ No newline at end of file + [Required] + public string[] RoleNames { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/UserLookupCountInputDto.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/UserLookupCountInputDto.cs index c8972615df..203f5783eb 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/UserLookupCountInputDto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/UserLookupCountInputDto.cs @@ -1,7 +1,6 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class UserLookupCountInputDto { - public class UserLookupCountInputDto - { - public string Filter { get; set; } - } -} \ No newline at end of file + public string Filter { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/UserLookupSearchInputDto.cs b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/UserLookupSearchInputDto.cs index cc9835afd1..9e75ed83fe 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/UserLookupSearchInputDto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/UserLookupSearchInputDto.cs @@ -1,9 +1,8 @@ using Volo.Abp.Application.Dtos; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class UserLookupSearchInputDto : PagedAndSortedResultRequestDto { - public class UserLookupSearchInputDto : PagedAndSortedResultRequestDto - { - public string Filter { get; set; } - } -} \ No newline at end of file + public string Filter { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/AbpIdentityApplicationModule.cs b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/AbpIdentityApplicationModule.cs index 15f057db8a..673a0605c7 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/AbpIdentityApplicationModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/AbpIdentityApplicationModule.cs @@ -3,24 +3,23 @@ using Volo.Abp.AutoMapper; using Volo.Abp.Modularity; using Volo.Abp.PermissionManagement; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[DependsOn( + typeof(AbpIdentityDomainModule), + typeof(AbpIdentityApplicationContractsModule), + typeof(AbpAutoMapperModule), + typeof(AbpPermissionManagementApplicationModule) + )] +public class AbpIdentityApplicationModule : AbpModule { - [DependsOn( - typeof(AbpIdentityDomainModule), - typeof(AbpIdentityApplicationContractsModule), - typeof(AbpAutoMapperModule), - typeof(AbpPermissionManagementApplicationModule) - )] - public class AbpIdentityApplicationModule : AbpModule + public override void ConfigureServices(ServiceConfigurationContext context) { - public override void ConfigureServices(ServiceConfigurationContext context) - { - context.Services.AddAutoMapperObjectMapper(); + context.Services.AddAutoMapperObjectMapper(); - Configure(options => - { - options.AddProfile(validate: true); - }); - } + Configure(options => + { + options.AddProfile(validate: true); + }); } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/AbpIdentityApplicationModuleAutoMapperProfile.cs b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/AbpIdentityApplicationModuleAutoMapperProfile.cs index 7b166152b0..a546a9bca1 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/AbpIdentityApplicationModuleAutoMapperProfile.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/AbpIdentityApplicationModuleAutoMapperProfile.cs @@ -1,16 +1,15 @@ using AutoMapper; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class AbpIdentityApplicationModuleAutoMapperProfile : Profile { - public class AbpIdentityApplicationModuleAutoMapperProfile : Profile + public AbpIdentityApplicationModuleAutoMapperProfile() { - public AbpIdentityApplicationModuleAutoMapperProfile() - { - CreateMap() - .MapExtraProperties(); + CreateMap() + .MapExtraProperties(); - CreateMap() - .MapExtraProperties(); - } + CreateMap() + .MapExtraProperties(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityAppServiceBase.cs b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityAppServiceBase.cs index 4c01a885c0..65c9136621 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityAppServiceBase.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityAppServiceBase.cs @@ -1,14 +1,13 @@ using Volo.Abp.Application.Services; using Volo.Abp.Identity.Localization; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class IdentityAppServiceBase : ApplicationService { - public abstract class IdentityAppServiceBase : ApplicationService + protected IdentityAppServiceBase() { - protected IdentityAppServiceBase() - { - ObjectMapperContext = typeof(AbpIdentityApplicationModule); - LocalizationResource = typeof(IdentityResource); - } + ObjectMapperContext = typeof(AbpIdentityApplicationModule); + LocalizationResource = typeof(IdentityResource); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityRoleAppService.cs b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityRoleAppService.cs index c219d4b24d..13c79029fa 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityRoleAppService.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityRoleAppService.cs @@ -7,99 +7,98 @@ using Volo.Abp.Application.Dtos; using Volo.Abp.Data; using Volo.Abp.ObjectExtending; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[Authorize(IdentityPermissions.Roles.Default)] +public class IdentityRoleAppService : IdentityAppServiceBase, IIdentityRoleAppService { - [Authorize(IdentityPermissions.Roles.Default)] - public class IdentityRoleAppService : IdentityAppServiceBase, IIdentityRoleAppService + protected IdentityRoleManager RoleManager { get; } + protected IIdentityRoleRepository RoleRepository { get; } + + public IdentityRoleAppService( + IdentityRoleManager roleManager, + IIdentityRoleRepository roleRepository) { - protected IdentityRoleManager RoleManager { get; } - protected IIdentityRoleRepository RoleRepository { get; } + RoleManager = roleManager; + RoleRepository = roleRepository; + } - public IdentityRoleAppService( - IdentityRoleManager roleManager, - IIdentityRoleRepository roleRepository) - { - RoleManager = roleManager; - RoleRepository = roleRepository; - } + public virtual async Task GetAsync(Guid id) + { + return ObjectMapper.Map( + await RoleManager.GetByIdAsync(id) + ); + } - public virtual async Task GetAsync(Guid id) - { - return ObjectMapper.Map( - await RoleManager.GetByIdAsync(id) - ); - } + public virtual async Task> GetAllListAsync() + { + var list = await RoleRepository.GetListAsync(); + return new ListResultDto( + ObjectMapper.Map, List>(list) + ); + } - public virtual async Task> GetAllListAsync() - { - var list = await RoleRepository.GetListAsync(); - return new ListResultDto( - ObjectMapper.Map, List>(list) + public virtual async Task> GetListAsync(GetIdentityRolesInput input) + { + var list = await RoleRepository.GetListAsync(input.Sorting, input.MaxResultCount, input.SkipCount, input.Filter); + var totalCount = await RoleRepository.GetCountAsync(input.Filter); + + return new PagedResultDto( + totalCount, + ObjectMapper.Map, List>(list) ); - } + } - public virtual async Task> GetListAsync(GetIdentityRolesInput input) + [Authorize(IdentityPermissions.Roles.Create)] + public virtual async Task CreateAsync(IdentityRoleCreateDto input) + { + var role = new IdentityRole( + GuidGenerator.Create(), + input.Name, + CurrentTenant.Id + ) { - var list = await RoleRepository.GetListAsync(input.Sorting, input.MaxResultCount, input.SkipCount, input.Filter); - var totalCount = await RoleRepository.GetCountAsync(input.Filter); + IsDefault = input.IsDefault, + IsPublic = input.IsPublic + }; - return new PagedResultDto( - totalCount, - ObjectMapper.Map, List>(list) - ); - } + input.MapExtraPropertiesTo(role); - [Authorize(IdentityPermissions.Roles.Create)] - public virtual async Task CreateAsync(IdentityRoleCreateDto input) - { - var role = new IdentityRole( - GuidGenerator.Create(), - input.Name, - CurrentTenant.Id - ) - { - IsDefault = input.IsDefault, - IsPublic = input.IsPublic - }; - - input.MapExtraPropertiesTo(role); - - (await RoleManager.CreateAsync(role)).CheckErrors(); - await CurrentUnitOfWork.SaveChangesAsync(); - - return ObjectMapper.Map(role); - } + (await RoleManager.CreateAsync(role)).CheckErrors(); + await CurrentUnitOfWork.SaveChangesAsync(); - [Authorize(IdentityPermissions.Roles.Update)] - public virtual async Task UpdateAsync(Guid id, IdentityRoleUpdateDto input) - { - var role = await RoleManager.GetByIdAsync(id); - - role.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp); + return ObjectMapper.Map(role); + } - (await RoleManager.SetRoleNameAsync(role, input.Name)).CheckErrors(); + [Authorize(IdentityPermissions.Roles.Update)] + public virtual async Task UpdateAsync(Guid id, IdentityRoleUpdateDto input) + { + var role = await RoleManager.GetByIdAsync(id); - role.IsDefault = input.IsDefault; - role.IsPublic = input.IsPublic; + role.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp); - input.MapExtraPropertiesTo(role); + (await RoleManager.SetRoleNameAsync(role, input.Name)).CheckErrors(); - (await RoleManager.UpdateAsync(role)).CheckErrors(); - await CurrentUnitOfWork.SaveChangesAsync(); + role.IsDefault = input.IsDefault; + role.IsPublic = input.IsPublic; - return ObjectMapper.Map(role); - } + input.MapExtraPropertiesTo(role); - [Authorize(IdentityPermissions.Roles.Delete)] - public virtual async Task DeleteAsync(Guid id) - { - var role = await RoleManager.FindByIdAsync(id.ToString()); - if (role == null) - { - return; - } + (await RoleManager.UpdateAsync(role)).CheckErrors(); + await CurrentUnitOfWork.SaveChangesAsync(); + + return ObjectMapper.Map(role); + } - (await RoleManager.DeleteAsync(role)).CheckErrors(); + [Authorize(IdentityPermissions.Roles.Delete)] + public virtual async Task DeleteAsync(Guid id) + { + var role = await RoleManager.FindByIdAsync(id.ToString()); + if (role == null) + { + return; } + + (await RoleManager.DeleteAsync(role)).CheckErrors(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityUserAppService.cs b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityUserAppService.cs index e380ffa0d0..498184b9cc 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityUserAppService.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityUserAppService.cs @@ -8,181 +8,180 @@ using Volo.Abp.Application.Dtos; using Volo.Abp.Data; using Volo.Abp.ObjectExtending; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUserAppService : IdentityAppServiceBase, IIdentityUserAppService { - public class IdentityUserAppService : IdentityAppServiceBase, IIdentityUserAppService + protected IdentityUserManager UserManager { get; } + protected IIdentityUserRepository UserRepository { get; } + protected IIdentityRoleRepository RoleRepository { get; } + protected IOptions IdentityOptions { get; } + + public IdentityUserAppService( + IdentityUserManager userManager, + IIdentityUserRepository userRepository, + IIdentityRoleRepository roleRepository, + IOptions identityOptions) { - protected IdentityUserManager UserManager { get; } - protected IIdentityUserRepository UserRepository { get; } - protected IIdentityRoleRepository RoleRepository { get; } - protected IOptions IdentityOptions { get; } - - public IdentityUserAppService( - IdentityUserManager userManager, - IIdentityUserRepository userRepository, - IIdentityRoleRepository roleRepository, - IOptions identityOptions) - { - UserManager = userManager; - UserRepository = userRepository; - RoleRepository = roleRepository; - IdentityOptions = identityOptions; - } + UserManager = userManager; + UserRepository = userRepository; + RoleRepository = roleRepository; + IdentityOptions = identityOptions; + } - //TODO: [Authorize(IdentityPermissions.Users.Default)] should go the IdentityUserAppService class. - [Authorize(IdentityPermissions.Users.Default)] - public virtual async Task GetAsync(Guid id) - { - return ObjectMapper.Map( - await UserManager.GetByIdAsync(id) - ); - } + //TODO: [Authorize(IdentityPermissions.Users.Default)] should go the IdentityUserAppService class. + [Authorize(IdentityPermissions.Users.Default)] + public virtual async Task GetAsync(Guid id) + { + return ObjectMapper.Map( + await UserManager.GetByIdAsync(id) + ); + } - [Authorize(IdentityPermissions.Users.Default)] - public virtual async Task> GetListAsync(GetIdentityUsersInput input) - { - var count = await UserRepository.GetCountAsync(input.Filter); - var list = await UserRepository.GetListAsync(input.Sorting, input.MaxResultCount, input.SkipCount, input.Filter); + [Authorize(IdentityPermissions.Users.Default)] + public virtual async Task> GetListAsync(GetIdentityUsersInput input) + { + var count = await UserRepository.GetCountAsync(input.Filter); + var list = await UserRepository.GetListAsync(input.Sorting, input.MaxResultCount, input.SkipCount, input.Filter); - return new PagedResultDto( - count, - ObjectMapper.Map, List>(list) - ); - } + return new PagedResultDto( + count, + ObjectMapper.Map, List>(list) + ); + } - [Authorize(IdentityPermissions.Users.Default)] - public virtual async Task> GetRolesAsync(Guid id) - { - //TODO: Should also include roles of the related OUs. + [Authorize(IdentityPermissions.Users.Default)] + public virtual async Task> GetRolesAsync(Guid id) + { + //TODO: Should also include roles of the related OUs. - var roles = await UserRepository.GetRolesAsync(id); + var roles = await UserRepository.GetRolesAsync(id); - return new ListResultDto( - ObjectMapper.Map, List>(roles) - ); - } + return new ListResultDto( + ObjectMapper.Map, List>(roles) + ); + } - [Authorize(IdentityPermissions.Users.Default)] - public virtual async Task> GetAssignableRolesAsync() - { - var list = await RoleRepository.GetListAsync(); - return new ListResultDto( - ObjectMapper.Map, List>(list)); - } + [Authorize(IdentityPermissions.Users.Default)] + public virtual async Task> GetAssignableRolesAsync() + { + var list = await RoleRepository.GetListAsync(); + return new ListResultDto( + ObjectMapper.Map, List>(list)); + } - [Authorize(IdentityPermissions.Users.Create)] - public virtual async Task CreateAsync(IdentityUserCreateDto input) - { - await IdentityOptions.SetAsync(); + [Authorize(IdentityPermissions.Users.Create)] + public virtual async Task CreateAsync(IdentityUserCreateDto input) + { + await IdentityOptions.SetAsync(); - var user = new IdentityUser( - GuidGenerator.Create(), - input.UserName, - input.Email, - CurrentTenant.Id - ); + var user = new IdentityUser( + GuidGenerator.Create(), + input.UserName, + input.Email, + CurrentTenant.Id + ); - input.MapExtraPropertiesTo(user); + input.MapExtraPropertiesTo(user); - (await UserManager.CreateAsync(user, input.Password)).CheckErrors(); - await UpdateUserByInput(user, input); - (await UserManager.UpdateAsync(user)).CheckErrors(); + (await UserManager.CreateAsync(user, input.Password)).CheckErrors(); + await UpdateUserByInput(user, input); + (await UserManager.UpdateAsync(user)).CheckErrors(); - await CurrentUnitOfWork.SaveChangesAsync(); + await CurrentUnitOfWork.SaveChangesAsync(); - return ObjectMapper.Map(user); - } + return ObjectMapper.Map(user); + } - [Authorize(IdentityPermissions.Users.Update)] - public virtual async Task UpdateAsync(Guid id, IdentityUserUpdateDto input) - { - await IdentityOptions.SetAsync(); + [Authorize(IdentityPermissions.Users.Update)] + public virtual async Task UpdateAsync(Guid id, IdentityUserUpdateDto input) + { + await IdentityOptions.SetAsync(); - var user = await UserManager.GetByIdAsync(id); + var user = await UserManager.GetByIdAsync(id); - user.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp); + user.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp); - (await UserManager.SetUserNameAsync(user, input.UserName)).CheckErrors(); + (await UserManager.SetUserNameAsync(user, input.UserName)).CheckErrors(); - await UpdateUserByInput(user, input); - input.MapExtraPropertiesTo(user); + await UpdateUserByInput(user, input); + input.MapExtraPropertiesTo(user); - (await UserManager.UpdateAsync(user)).CheckErrors(); + (await UserManager.UpdateAsync(user)).CheckErrors(); - if (!input.Password.IsNullOrEmpty()) - { - (await UserManager.RemovePasswordAsync(user)).CheckErrors(); - (await UserManager.AddPasswordAsync(user, input.Password)).CheckErrors(); - } + if (!input.Password.IsNullOrEmpty()) + { + (await UserManager.RemovePasswordAsync(user)).CheckErrors(); + (await UserManager.AddPasswordAsync(user, input.Password)).CheckErrors(); + } - await CurrentUnitOfWork.SaveChangesAsync(); + await CurrentUnitOfWork.SaveChangesAsync(); - return ObjectMapper.Map(user); - } + return ObjectMapper.Map(user); + } - [Authorize(IdentityPermissions.Users.Delete)] - public virtual async Task DeleteAsync(Guid id) + [Authorize(IdentityPermissions.Users.Delete)] + public virtual async Task DeleteAsync(Guid id) + { + if (CurrentUser.Id == id) { - if (CurrentUser.Id == id) - { - throw new BusinessException(code: IdentityErrorCodes.UserSelfDeletion); - } - - var user = await UserManager.FindByIdAsync(id.ToString()); - if (user == null) - { - return; - } - - (await UserManager.DeleteAsync(user)).CheckErrors(); + throw new BusinessException(code: IdentityErrorCodes.UserSelfDeletion); } - [Authorize(IdentityPermissions.Users.Update)] - public virtual async Task UpdateRolesAsync(Guid id, IdentityUserUpdateRolesDto input) + var user = await UserManager.FindByIdAsync(id.ToString()); + if (user == null) { - var user = await UserManager.GetByIdAsync(id); - (await UserManager.SetRolesAsync(user, input.RoleNames)).CheckErrors(); - await UserRepository.UpdateAsync(user); + return; } - [Authorize(IdentityPermissions.Users.Default)] - public virtual async Task FindByUsernameAsync(string userName) + (await UserManager.DeleteAsync(user)).CheckErrors(); + } + + [Authorize(IdentityPermissions.Users.Update)] + public virtual async Task UpdateRolesAsync(Guid id, IdentityUserUpdateRolesDto input) + { + var user = await UserManager.GetByIdAsync(id); + (await UserManager.SetRolesAsync(user, input.RoleNames)).CheckErrors(); + await UserRepository.UpdateAsync(user); + } + + [Authorize(IdentityPermissions.Users.Default)] + public virtual async Task FindByUsernameAsync(string userName) + { + return ObjectMapper.Map( + await UserManager.FindByNameAsync(userName) + ); + } + + [Authorize(IdentityPermissions.Users.Default)] + public virtual async Task FindByEmailAsync(string email) + { + return ObjectMapper.Map( + await UserManager.FindByEmailAsync(email) + ); + } + + protected virtual async Task UpdateUserByInput(IdentityUser user, IdentityUserCreateOrUpdateDtoBase input) + { + if (!string.Equals(user.Email, input.Email, StringComparison.InvariantCultureIgnoreCase)) { - return ObjectMapper.Map( - await UserManager.FindByNameAsync(userName) - ); + (await UserManager.SetEmailAsync(user, input.Email)).CheckErrors(); } - [Authorize(IdentityPermissions.Users.Default)] - public virtual async Task FindByEmailAsync(string email) + if (!string.Equals(user.PhoneNumber, input.PhoneNumber, StringComparison.InvariantCultureIgnoreCase)) { - return ObjectMapper.Map( - await UserManager.FindByEmailAsync(email) - ); + (await UserManager.SetPhoneNumberAsync(user, input.PhoneNumber)).CheckErrors(); } - protected virtual async Task UpdateUserByInput(IdentityUser user, IdentityUserCreateOrUpdateDtoBase input) + (await UserManager.SetLockoutEnabledAsync(user, input.LockoutEnabled)).CheckErrors(); + + user.Name = input.Name; + user.Surname = input.Surname; + (await UserManager.UpdateAsync(user)).CheckErrors(); + user.SetIsActive(input.IsActive); + if (input.RoleNames != null) { - if (!string.Equals(user.Email, input.Email, StringComparison.InvariantCultureIgnoreCase)) - { - (await UserManager.SetEmailAsync(user, input.Email)).CheckErrors(); - } - - if (!string.Equals(user.PhoneNumber, input.PhoneNumber, StringComparison.InvariantCultureIgnoreCase)) - { - (await UserManager.SetPhoneNumberAsync(user, input.PhoneNumber)).CheckErrors(); - } - - (await UserManager.SetLockoutEnabledAsync(user, input.LockoutEnabled)).CheckErrors(); - - user.Name = input.Name; - user.Surname = input.Surname; - (await UserManager.UpdateAsync(user)).CheckErrors(); - user.SetIsActive(input.IsActive); - if (input.RoleNames != null) - { - (await UserManager.SetRolesAsync(user, input.RoleNames)).CheckErrors(); - } + (await UserManager.SetRolesAsync(user, input.RoleNames)).CheckErrors(); } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityUserLookupAppService.cs b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityUserLookupAppService.cs index ec9aaa3805..a0594949b6 100644 --- a/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityUserLookupAppService.cs +++ b/modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityUserLookupAppService.cs @@ -5,60 +5,59 @@ using Microsoft.AspNetCore.Authorization; using Volo.Abp.Application.Dtos; using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[Authorize(IdentityPermissions.UserLookup.Default)] +public class IdentityUserLookupAppService : IdentityAppServiceBase, IIdentityUserLookupAppService { - [Authorize(IdentityPermissions.UserLookup.Default)] - public class IdentityUserLookupAppService : IdentityAppServiceBase, IIdentityUserLookupAppService + protected IdentityUserRepositoryExternalUserLookupServiceProvider UserLookupServiceProvider { get; } + + public IdentityUserLookupAppService( + IdentityUserRepositoryExternalUserLookupServiceProvider userLookupServiceProvider) { - protected IdentityUserRepositoryExternalUserLookupServiceProvider UserLookupServiceProvider { get; } + UserLookupServiceProvider = userLookupServiceProvider; + } - public IdentityUserLookupAppService( - IdentityUserRepositoryExternalUserLookupServiceProvider userLookupServiceProvider) + public virtual async Task FindByIdAsync(Guid id) + { + var userData = await UserLookupServiceProvider.FindByIdAsync(id); + if (userData == null) { - UserLookupServiceProvider = userLookupServiceProvider; + return null; } - public virtual async Task FindByIdAsync(Guid id) - { - var userData = await UserLookupServiceProvider.FindByIdAsync(id); - if (userData == null) - { - return null; - } - - return new UserData(userData); - } + return new UserData(userData); + } - public virtual async Task FindByUserNameAsync(string userName) + public virtual async Task FindByUserNameAsync(string userName) + { + var userData = await UserLookupServiceProvider.FindByUserNameAsync(userName); + if (userData == null) { - var userData = await UserLookupServiceProvider.FindByUserNameAsync(userName); - if (userData == null) - { - return null; - } - - return new UserData(userData); + return null; } - public async Task> SearchAsync(UserLookupSearchInputDto input) - { - var users = await UserLookupServiceProvider.SearchAsync( - input.Sorting, - input.Filter, - input.MaxResultCount, - input.SkipCount - ); + return new UserData(userData); + } - return new ListResultDto( - users - .Select(u => new UserData(u)) - .ToList() - ); - } + public async Task> SearchAsync(UserLookupSearchInputDto input) + { + var users = await UserLookupServiceProvider.SearchAsync( + input.Sorting, + input.Filter, + input.MaxResultCount, + input.SkipCount + ); + + return new ListResultDto( + users + .Select(u => new UserData(u)) + .ToList() + ); + } - public async Task GetCountAsync(UserLookupCountInputDto input) - { - return await UserLookupServiceProvider.GetCountAsync(input.Filter); - } + public async Task GetCountAsync(UserLookupCountInputDto input) + { + return await UserLookupServiceProvider.GetCountAsync(input.Filter); } } diff --git a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreModule.cs b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreModule.cs index 82679b10b7..93d8a52ee7 100644 --- a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreModule.cs @@ -2,43 +2,42 @@ using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Modularity; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +[DependsOn( + typeof(AbpIdentityDomainModule) + )] +public class AbpIdentityAspNetCoreModule : AbpModule { - [DependsOn( - typeof(AbpIdentityDomainModule) - )] - public class AbpIdentityAspNetCoreModule : AbpModule + public override void PreConfigureServices(ServiceConfigurationContext context) { - public override void PreConfigureServices(ServiceConfigurationContext context) + PreConfigure(builder => { - PreConfigure(builder => - { - builder - .AddDefaultTokenProviders() - .AddTokenProvider(LinkUserTokenProviderConsts.LinkUserTokenProviderName) - .AddSignInManager(); - }); - } + builder + .AddDefaultTokenProviders() + .AddTokenProvider(LinkUserTokenProviderConsts.LinkUserTokenProviderName) + .AddSignInManager(); + }); + } - public override void ConfigureServices(ServiceConfigurationContext context) - { - //(TODO: Extract an extension method like IdentityBuilder.AddAbpSecurityStampValidator()) - context.Services.AddScoped(); - context.Services.AddScoped(typeof(SecurityStampValidator), provider => provider.GetService(typeof(AbpSecurityStampValidator))); - context.Services.AddScoped(typeof(ISecurityStampValidator), provider => provider.GetService(typeof(AbpSecurityStampValidator))); + public override void ConfigureServices(ServiceConfigurationContext context) + { + //(TODO: Extract an extension method like IdentityBuilder.AddAbpSecurityStampValidator()) + context.Services.AddScoped(); + context.Services.AddScoped(typeof(SecurityStampValidator), provider => provider.GetService(typeof(AbpSecurityStampValidator))); + context.Services.AddScoped(typeof(ISecurityStampValidator), provider => provider.GetService(typeof(AbpSecurityStampValidator))); - var options = context.Services.ExecutePreConfiguredActions(new AbpIdentityAspNetCoreOptions()); + var options = context.Services.ExecutePreConfiguredActions(new AbpIdentityAspNetCoreOptions()); - if (options.ConfigureAuthentication) - { - context.Services - .AddAuthentication(o => - { - o.DefaultScheme = IdentityConstants.ApplicationScheme; - o.DefaultSignInScheme = IdentityConstants.ExternalScheme; - }) - .AddIdentityCookies(); - } + if (options.ConfigureAuthentication) + { + context.Services + .AddAuthentication(o => + { + o.DefaultScheme = IdentityConstants.ApplicationScheme; + o.DefaultSignInScheme = IdentityConstants.ExternalScheme; + }) + .AddIdentityCookies(); } } } diff --git a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreOptions.cs b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreOptions.cs index 590d691eaa..d457d84e5d 100644 --- a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreOptions.cs +++ b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreOptions.cs @@ -1,10 +1,9 @@ -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public class AbpIdentityAspNetCoreOptions { - public class AbpIdentityAspNetCoreOptions - { - /// - /// Default: true. - /// - public bool ConfigureAuthentication { get; set; } = true; - } + /// + /// Default: true. + /// + public bool ConfigureAuthentication { get; set; } = true; } diff --git a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSecurityStampValidator.cs b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSecurityStampValidator.cs index 8ae543bed2..d62c33992a 100644 --- a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSecurityStampValidator.cs +++ b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSecurityStampValidator.cs @@ -8,47 +8,46 @@ using Microsoft.Extensions.Options; using Volo.Abp.MultiTenancy; using Volo.Abp.Uow; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public class AbpSecurityStampValidator : SecurityStampValidator { - public class AbpSecurityStampValidator : SecurityStampValidator + protected ITenantConfigurationProvider TenantConfigurationProvider { get; } + protected ICurrentTenant CurrentTenant { get; } + + public AbpSecurityStampValidator( + IOptions options, + SignInManager signInManager, + ISystemClock systemClock, + ILoggerFactory loggerFactory, + ITenantConfigurationProvider tenantConfigurationProvider, + ICurrentTenant currentTenant) + : base( + options, + signInManager, + systemClock, + loggerFactory) { - protected ITenantConfigurationProvider TenantConfigurationProvider { get; } - protected ICurrentTenant CurrentTenant { get; } + TenantConfigurationProvider = tenantConfigurationProvider; + CurrentTenant = currentTenant; + } - public AbpSecurityStampValidator( - IOptions options, - SignInManager signInManager, - ISystemClock systemClock, - ILoggerFactory loggerFactory, - ITenantConfigurationProvider tenantConfigurationProvider, - ICurrentTenant currentTenant) - : base( - options, - signInManager, - systemClock, - loggerFactory) + [UnitOfWork] + public override async Task ValidateAsync(CookieValidatePrincipalContext context) + { + TenantConfiguration tenant = null; + try { - TenantConfigurationProvider = tenantConfigurationProvider; - CurrentTenant = currentTenant; + tenant = await TenantConfigurationProvider.GetAsync(saveResolveResult: false); } - - [UnitOfWork] - public override async Task ValidateAsync(CookieValidatePrincipalContext context) + catch (Exception e) { - TenantConfiguration tenant = null; - try - { - tenant = await TenantConfigurationProvider.GetAsync(saveResolveResult: false); - } - catch (Exception e) - { - Logger.LogException(e); - } + Logger.LogException(e); + } - using (CurrentTenant.Change(tenant?.Id, tenant?.Name)) - { - await base.ValidateAsync(context); - } + using (CurrentTenant.Change(tenant?.Id, tenant?.Name)) + { + await base.ValidateAsync(context); } } } diff --git a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSecurityStampValidatorCallback.cs b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSecurityStampValidatorCallback.cs index 2adc65d497..63bed70dfd 100644 --- a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSecurityStampValidatorCallback.cs +++ b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSecurityStampValidatorCallback.cs @@ -2,32 +2,31 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public class AbpSecurityStampValidatorCallback { - public class AbpSecurityStampValidatorCallback + /// + /// Implements callback for SecurityStampValidator's OnRefreshingPrincipal event. + /// https://github.com/IdentityServer/IdentityServer4/blob/main/src/AspNetIdentity/src/SecurityStampValidatorCallback.cs + /// + public class SecurityStampValidatorCallback { /// - /// Implements callback for SecurityStampValidator's OnRefreshingPrincipal event. - /// https://github.com/IdentityServer/IdentityServer4/blob/main/src/AspNetIdentity/src/SecurityStampValidatorCallback.cs + /// Maintains the claims captured at login time that are not being created by ASP.NET Identity. + /// This is needed to preserve claims such as idp, auth_time, amr. /// - public class SecurityStampValidatorCallback + /// The context. + /// + public static Task UpdatePrincipal(SecurityStampRefreshingPrincipalContext context) { - /// - /// Maintains the claims captured at login time that are not being created by ASP.NET Identity. - /// This is needed to preserve claims such as idp, auth_time, amr. - /// - /// The context. - /// - public static Task UpdatePrincipal(SecurityStampRefreshingPrincipalContext context) - { - var newClaimTypes = context.NewPrincipal.Claims.Select(x => x.Type).ToArray(); - var currentClaimsToKeep = context.CurrentPrincipal.Claims.Where(x => !newClaimTypes.Contains(x.Type)).ToArray(); + var newClaimTypes = context.NewPrincipal.Claims.Select(x => x.Type).ToArray(); + var currentClaimsToKeep = context.CurrentPrincipal.Claims.Where(x => !newClaimTypes.Contains(x.Type)).ToArray(); - var id = context.NewPrincipal.Identities.First(); - id.AddClaims(currentClaimsToKeep); + var id = context.NewPrincipal.Identities.First(); + id.AddClaims(currentClaimsToKeep); - return Task.CompletedTask; - } + return Task.CompletedTask; } } } diff --git a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInManager.cs b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInManager.cs index b9c7b06abf..313be4ae3f 100644 --- a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInManager.cs +++ b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInManager.cs @@ -6,72 +6,71 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public class AbpSignInManager : SignInManager { - public class AbpSignInManager : SignInManager + protected AbpIdentityOptions AbpOptions { get; } + + public AbpSignInManager( + IdentityUserManager userManager, + IHttpContextAccessor contextAccessor, + IUserClaimsPrincipalFactory claimsFactory, + IOptions optionsAccessor, + ILogger> logger, + IAuthenticationSchemeProvider schemes, + IUserConfirmation confirmation, + IOptions options + ) : base( + userManager, + contextAccessor, + claimsFactory, + optionsAccessor, + logger, + schemes, + confirmation) { - protected AbpIdentityOptions AbpOptions { get; } + AbpOptions = options.Value; + } - public AbpSignInManager( - IdentityUserManager userManager, - IHttpContextAccessor contextAccessor, - IUserClaimsPrincipalFactory claimsFactory, - IOptions optionsAccessor, - ILogger> logger, - IAuthenticationSchemeProvider schemes, - IUserConfirmation confirmation, - IOptions options - ) : base( - userManager, - contextAccessor, - claimsFactory, - optionsAccessor, - logger, - schemes, - confirmation) + public override async Task PasswordSignInAsync( + string userName, + string password, + bool isPersistent, + bool lockoutOnFailure) + { + foreach (var externalLoginProviderInfo in AbpOptions.ExternalLoginProviders.Values) { - AbpOptions = options.Value; - } + var externalLoginProvider = (IExternalLoginProvider)Context.RequestServices + .GetRequiredService(externalLoginProviderInfo.Type); - public override async Task PasswordSignInAsync( - string userName, - string password, - bool isPersistent, - bool lockoutOnFailure) - { - foreach (var externalLoginProviderInfo in AbpOptions.ExternalLoginProviders.Values) + if (await externalLoginProvider.TryAuthenticateAsync(userName, password)) { - var externalLoginProvider = (IExternalLoginProvider)Context.RequestServices - .GetRequiredService(externalLoginProviderInfo.Type); - - if (await externalLoginProvider.TryAuthenticateAsync(userName, password)) + var user = await UserManager.FindByNameAsync(userName); + if (user == null) { - var user = await UserManager.FindByNameAsync(userName); - if (user == null) - { - user = await externalLoginProvider.CreateUserAsync(userName, externalLoginProviderInfo.Name); - } - else - { - await externalLoginProvider.UpdateUserAsync(user, externalLoginProviderInfo.Name); - } - - return await SignInOrTwoFactorAsync(user, isPersistent); + user = await externalLoginProvider.CreateUserAsync(userName, externalLoginProviderInfo.Name); + } + else + { + await externalLoginProvider.UpdateUserAsync(user, externalLoginProviderInfo.Name); } - } - return await base.PasswordSignInAsync(userName, password, isPersistent, lockoutOnFailure); + return await SignInOrTwoFactorAsync(user, isPersistent); + } } - protected override async Task PreSignInCheck(IdentityUser user) - { - if (!user.IsActive) - { - Logger.LogWarning($"The user is not active therefore cannot login! (username: \"{user.UserName}\", id:\"{user.Id}\")"); - return SignInResult.NotAllowed; - } + return await base.PasswordSignInAsync(userName, password, isPersistent, lockoutOnFailure); + } - return await base.PreSignInCheck(user); + protected override async Task PreSignInCheck(IdentityUser user) + { + if (!user.IsActive) + { + Logger.LogWarning($"The user is not active therefore cannot login! (username: \"{user.UserName}\", id:\"{user.Id}\")"); + return SignInResult.NotAllowed; } + + return await base.PreSignInCheck(user); } } diff --git a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/LinkUserTokenProvider.cs b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/LinkUserTokenProvider.cs index 2fadb53a83..b2fe7c772c 100644 --- a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/LinkUserTokenProvider.cs +++ b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/LinkUserTokenProvider.cs @@ -3,17 +3,16 @@ using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public class LinkUserTokenProvider : DataProtectorTokenProvider { - public class LinkUserTokenProvider : DataProtectorTokenProvider + public LinkUserTokenProvider( + IDataProtectionProvider dataProtectionProvider, + IOptions options, + ILogger> logger) + : base(dataProtectionProvider, options, logger) { - public LinkUserTokenProvider( - IDataProtectionProvider dataProtectionProvider, - IOptions options, - ILogger> logger) - : base(dataProtectionProvider, options, logger) - { - } } } diff --git a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/SignInResultExtensions.cs b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/SignInResultExtensions.cs index 39e3ae92fc..bdb283909d 100644 --- a/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/SignInResultExtensions.cs +++ b/modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/SignInResultExtensions.cs @@ -1,37 +1,36 @@ using Microsoft.AspNetCore.Identity; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public static class SignInResultExtensions { - public static class SignInResultExtensions + public static string ToIdentitySecurityLogAction(this SignInResult result) { - public static string ToIdentitySecurityLogAction(this SignInResult result) + if (result.Succeeded) { - if (result.Succeeded) - { - return IdentitySecurityLogActionConsts.LoginSucceeded; - } - - if (result.IsLockedOut) - { - return IdentitySecurityLogActionConsts.LoginLockedout; - } + return IdentitySecurityLogActionConsts.LoginSucceeded; + } - if (result.RequiresTwoFactor) - { - return IdentitySecurityLogActionConsts.LoginRequiresTwoFactor; - } + if (result.IsLockedOut) + { + return IdentitySecurityLogActionConsts.LoginLockedout; + } - if (result.IsNotAllowed) - { - return IdentitySecurityLogActionConsts.LoginNotAllowed; - } + if (result.RequiresTwoFactor) + { + return IdentitySecurityLogActionConsts.LoginRequiresTwoFactor; + } - if (!result.Succeeded) - { - return IdentitySecurityLogActionConsts.LoginFailed; - } + if (result.IsNotAllowed) + { + return IdentitySecurityLogActionConsts.LoginNotAllowed; + } + if (!result.Succeeded) + { return IdentitySecurityLogActionConsts.LoginFailed; } + + return IdentitySecurityLogActionConsts.LoginFailed; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Blazor.Server/AbpIdentityBlazorServerModule.cs b/modules/identity/src/Volo.Abp.Identity.Blazor.Server/AbpIdentityBlazorServerModule.cs index 2c2e92c6f3..ed46baf6bb 100644 --- a/modules/identity/src/Volo.Abp.Identity.Blazor.Server/AbpIdentityBlazorServerModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.Blazor.Server/AbpIdentityBlazorServerModule.cs @@ -2,13 +2,12 @@ using Volo.Abp.Modularity; using Volo.Abp.PermissionManagement.Blazor.Server; -namespace Volo.Abp.Identity.Blazor.Server +namespace Volo.Abp.Identity.Blazor.Server; + +[DependsOn( + typeof(AbpIdentityBlazorModule), + typeof(AbpPermissionManagementBlazorServerModule) +)] +public class AbpIdentityBlazorServerModule : AbpModule { - [DependsOn( - typeof(AbpIdentityBlazorModule), - typeof(AbpPermissionManagementBlazorServerModule) - )] - public class AbpIdentityBlazorServerModule : AbpModule - { - } } diff --git a/modules/identity/src/Volo.Abp.Identity.Blazor.WebAssembly/AbpIdentityBlazorWebAssemblyModule.cs b/modules/identity/src/Volo.Abp.Identity.Blazor.WebAssembly/AbpIdentityBlazorWebAssemblyModule.cs index 09c51e4ac8..82b4a381a1 100644 --- a/modules/identity/src/Volo.Abp.Identity.Blazor.WebAssembly/AbpIdentityBlazorWebAssemblyModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.Blazor.WebAssembly/AbpIdentityBlazorWebAssemblyModule.cs @@ -2,14 +2,13 @@ using Volo.Abp.Modularity; using Volo.Abp.PermissionManagement.Blazor.WebAssembly; -namespace Volo.Abp.Identity.Blazor.WebAssembly +namespace Volo.Abp.Identity.Blazor.WebAssembly; + +[DependsOn( + typeof(AbpIdentityBlazorModule), + typeof(AbpPermissionManagementBlazorWebAssemblyModule), + typeof(AbpIdentityHttpApiClientModule) +)] +public class AbpIdentityBlazorWebAssemblyModule : AbpModule { - [DependsOn( - typeof(AbpIdentityBlazorModule), - typeof(AbpPermissionManagementBlazorWebAssemblyModule), - typeof(AbpIdentityHttpApiClientModule) - )] - public class AbpIdentityBlazorWebAssemblyModule : AbpModule - { - } } diff --git a/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityBlazorAutoMapperProfile.cs b/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityBlazorAutoMapperProfile.cs index 989986ce6d..52a450785e 100644 --- a/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityBlazorAutoMapperProfile.cs +++ b/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityBlazorAutoMapperProfile.cs @@ -1,19 +1,18 @@ using AutoMapper; using Volo.Abp.AutoMapper; -namespace Volo.Abp.Identity.Blazor +namespace Volo.Abp.Identity.Blazor; + +public class AbpIdentityBlazorAutoMapperProfile : Profile { - public class AbpIdentityBlazorAutoMapperProfile : Profile + public AbpIdentityBlazorAutoMapperProfile() { - public AbpIdentityBlazorAutoMapperProfile() - { - CreateMap() - .MapExtraProperties() - .Ignore(x => x.Password) - .Ignore(x => x.RoleNames); - - CreateMap() - .MapExtraProperties(); - } + CreateMap() + .MapExtraProperties() + .Ignore(x => x.Password) + .Ignore(x => x.RoleNames); + + CreateMap() + .MapExtraProperties(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityBlazorModule.cs b/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityBlazorModule.cs index 14b5494531..4b9dc5326f 100644 --- a/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityBlazorModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityBlazorModule.cs @@ -9,58 +9,57 @@ using Volo.Abp.PermissionManagement.Blazor; using Volo.Abp.Threading; using Volo.Abp.UI.Navigation; -namespace Volo.Abp.Identity.Blazor +namespace Volo.Abp.Identity.Blazor; + +[DependsOn( + typeof(AbpIdentityApplicationContractsModule), + typeof(AbpAutoMapperModule), + typeof(AbpPermissionManagementBlazorModule), + typeof(AbpBlazoriseUIModule) + )] +public class AbpIdentityBlazorModule : AbpModule { - [DependsOn( - typeof(AbpIdentityApplicationContractsModule), - typeof(AbpAutoMapperModule), - typeof(AbpPermissionManagementBlazorModule), - typeof(AbpBlazoriseUIModule) - )] - public class AbpIdentityBlazorModule : AbpModule + private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); + + public override void ConfigureServices(ServiceConfigurationContext context) { - private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); + context.Services.AddAutoMapperObjectMapper(); - public override void ConfigureServices(ServiceConfigurationContext context) + Configure(options => { - context.Services.AddAutoMapperObjectMapper(); + options.AddProfile(validate: true); + }); - Configure(options => - { - options.AddProfile(validate: true); - }); - - Configure(options => - { - options.MenuContributors.Add(new AbpIdentityWebMainMenuContributor()); - }); + Configure(options => + { + options.MenuContributors.Add(new AbpIdentityWebMainMenuContributor()); + }); - Configure(options => - { - options.AdditionalAssemblies.Add(typeof(AbpIdentityBlazorModule).Assembly); - }); - } + Configure(options => + { + options.AdditionalAssemblies.Add(typeof(AbpIdentityBlazorModule).Assembly); + }); + } - public override void PostConfigureServices(ServiceConfigurationContext context) + public override void PostConfigureServices(ServiceConfigurationContext context) + { + OneTimeRunner.Run(() => { - OneTimeRunner.Run(() => - { - ModuleExtensionConfigurationHelper - .ApplyEntityConfigurationToUi( - IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.Role, - createFormTypes: new[] { typeof(IdentityRoleCreateDto) }, - editFormTypes: new[] { typeof(IdentityRoleUpdateDto) } - ); + ModuleExtensionConfigurationHelper + .ApplyEntityConfigurationToUi( + IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.Role, + createFormTypes: new[] { typeof(IdentityRoleCreateDto) }, + editFormTypes: new[] { typeof(IdentityRoleUpdateDto) } + ); - ModuleExtensionConfigurationHelper - .ApplyEntityConfigurationToUi( - IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.User, - createFormTypes: new[] { typeof(IdentityUserCreateDto) }, - editFormTypes: new[] { typeof(IdentityUserUpdateDto) } - ); - }); - } + ModuleExtensionConfigurationHelper + .ApplyEntityConfigurationToUi( + IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.User, + createFormTypes: new[] { typeof(IdentityUserCreateDto) }, + editFormTypes: new[] { typeof(IdentityUserUpdateDto) } + ); + }); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityWebMainMenuContributor.cs b/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityWebMainMenuContributor.cs index fafa8eac9b..e148e63018 100644 --- a/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityWebMainMenuContributor.cs +++ b/modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityWebMainMenuContributor.cs @@ -3,36 +3,35 @@ using Volo.Abp.Identity.Localization; using Volo.Abp.UI.Navigation; using Volo.Abp.Authorization.Permissions; -namespace Volo.Abp.Identity.Blazor +namespace Volo.Abp.Identity.Blazor; + +public class AbpIdentityWebMainMenuContributor : IMenuContributor { - public class AbpIdentityWebMainMenuContributor : IMenuContributor + public virtual Task ConfigureMenuAsync(MenuConfigurationContext context) { - public virtual Task ConfigureMenuAsync(MenuConfigurationContext context) + if (context.Menu.Name != StandardMenus.Main) { - if (context.Menu.Name != StandardMenus.Main) - { - return Task.CompletedTask; - } + return Task.CompletedTask; + } - var administrationMenu = context.Menu.GetAdministration(); + var administrationMenu = context.Menu.GetAdministration(); - var l = context.GetLocalizer(); + var l = context.GetLocalizer(); - var identityMenuItem = new ApplicationMenuItem(IdentityMenuNames.GroupName, l["Menu:IdentityManagement"], - icon: "far fa-id-card"); - administrationMenu.AddItem(identityMenuItem); + var identityMenuItem = new ApplicationMenuItem(IdentityMenuNames.GroupName, l["Menu:IdentityManagement"], + icon: "far fa-id-card"); + administrationMenu.AddItem(identityMenuItem); - identityMenuItem.AddItem(new ApplicationMenuItem( - IdentityMenuNames.Roles, - l["Roles"], - url: "~/identity/roles").RequirePermissions(IdentityPermissions.Roles.Default)); + identityMenuItem.AddItem(new ApplicationMenuItem( + IdentityMenuNames.Roles, + l["Roles"], + url: "~/identity/roles").RequirePermissions(IdentityPermissions.Roles.Default)); - identityMenuItem.AddItem(new ApplicationMenuItem( - IdentityMenuNames.Users, - l["Users"], - url: "~/identity/users").RequirePermissions(IdentityPermissions.Users.Default)); + identityMenuItem.AddItem(new ApplicationMenuItem( + IdentityMenuNames.Users, + l["Users"], + url: "~/identity/users").RequirePermissions(IdentityPermissions.Users.Default)); - return Task.CompletedTask; - } + return Task.CompletedTask; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Blazor/IdentityMenuNames.cs b/modules/identity/src/Volo.Abp.Identity.Blazor/IdentityMenuNames.cs index 9cd5b1dc37..865951d1b3 100644 --- a/modules/identity/src/Volo.Abp.Identity.Blazor/IdentityMenuNames.cs +++ b/modules/identity/src/Volo.Abp.Identity.Blazor/IdentityMenuNames.cs @@ -1,10 +1,9 @@ -namespace Volo.Abp.Identity.Blazor +namespace Volo.Abp.Identity.Blazor; + +public class IdentityMenuNames { - public class IdentityMenuNames - { - public const string GroupName = "AbpIdentity"; + public const string GroupName = "AbpIdentity"; - public const string Roles = GroupName + ".Roles"; - public const string Users = GroupName + ".Users"; - } + public const string Roles = GroupName + ".Roles"; + public const string Users = GroupName + ".Users"; } diff --git a/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/RoleManagement.razor.cs b/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/RoleManagement.razor.cs index f0a222f765..f14e5cef90 100644 --- a/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/RoleManagement.razor.cs +++ b/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/RoleManagement.razor.cs @@ -12,39 +12,39 @@ using Volo.Abp.PermissionManagement.Blazor.Components; using Volo.Abp.ObjectExtending; using Volo.Abp.Data; -namespace Volo.Abp.Identity.Blazor.Pages.Identity +namespace Volo.Abp.Identity.Blazor.Pages.Identity; + +public partial class RoleManagement { - public partial class RoleManagement - { - protected const string PermissionProviderName = "R"; + protected const string PermissionProviderName = "R"; - protected PermissionManagementModal PermissionManagementModal; + protected PermissionManagementModal PermissionManagementModal; - protected string ManagePermissionsPolicyName; + protected string ManagePermissionsPolicyName; - protected bool HasManagePermissionsPermission { get; set; } + protected bool HasManagePermissionsPermission { get; set; } - protected PageToolbar Toolbar { get; } = new(); + protected PageToolbar Toolbar { get; } = new(); - protected List RoleManagementTableColumns => TableColumns.Get(); + protected List RoleManagementTableColumns => TableColumns.Get(); - public RoleManagement() - { - ObjectMapperContext = typeof(AbpIdentityBlazorModule); - LocalizationResource = typeof(IdentityResource); + public RoleManagement() + { + ObjectMapperContext = typeof(AbpIdentityBlazorModule); + LocalizationResource = typeof(IdentityResource); - CreatePolicyName = IdentityPermissions.Roles.Create; - UpdatePolicyName = IdentityPermissions.Roles.Update; - DeletePolicyName = IdentityPermissions.Roles.Delete; - ManagePermissionsPolicyName = IdentityPermissions.Roles.ManagePermissions; - } + CreatePolicyName = IdentityPermissions.Roles.Create; + UpdatePolicyName = IdentityPermissions.Roles.Update; + DeletePolicyName = IdentityPermissions.Roles.Delete; + ManagePermissionsPolicyName = IdentityPermissions.Roles.ManagePermissions; + } - protected override ValueTask SetEntityActionsAsync() - { - EntityActions - .Get() - .AddRange(new EntityAction[] - { + protected override ValueTask SetEntityActionsAsync() + { + EntityActions + .Get() + .AddRange(new EntityAction[] + { new EntityAction { Text = L["Edit"], @@ -68,16 +68,16 @@ namespace Volo.Abp.Identity.Blazor.Pages.Identity Clicked = async (data) => await DeleteEntityAsync(data.As()), ConfirmationMessage = (data) => GetDeleteConfirmationMessage(data.As()) } - }); + }); - return base.SetEntityActionsAsync(); - } + return base.SetEntityActionsAsync(); + } - protected override ValueTask SetTableColumnsAsync() - { - RoleManagementTableColumns - .AddRange(new TableColumn[] - { + protected override ValueTask SetTableColumnsAsync() + { + RoleManagementTableColumns + .AddRange(new TableColumn[] + { new TableColumn { Title = L["Actions"], @@ -89,35 +89,34 @@ namespace Volo.Abp.Identity.Blazor.Pages.Identity Data = nameof(IdentityRoleDto.Name), Component = typeof(RoleNameComponent) }, - }); - - RoleManagementTableColumns.AddRange(GetExtensionTableColumns(IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.Role)); - - return base.SetTableColumnsAsync(); - } - - protected override async Task SetPermissionsAsync() - { - await base.SetPermissionsAsync(); - - HasManagePermissionsPermission = - await AuthorizationService.IsGrantedAsync(IdentityPermissions.Roles.ManagePermissions); - } - - protected override string GetDeleteConfirmationMessage(IdentityRoleDto entity) - { - return string.Format(L["RoleDeletionConfirmationMessage"], entity.Name); - } - - protected override ValueTask SetToolbarItemsAsync() - { - Toolbar.AddButton(L["NewRole"], - OpenCreateModalAsync, - IconName.Add, - requiredPolicyName: CreatePolicyName); - - return base.SetToolbarItemsAsync(); - } + }); + + RoleManagementTableColumns.AddRange(GetExtensionTableColumns(IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.Role)); + + return base.SetTableColumnsAsync(); + } + + protected override async Task SetPermissionsAsync() + { + await base.SetPermissionsAsync(); + + HasManagePermissionsPermission = + await AuthorizationService.IsGrantedAsync(IdentityPermissions.Roles.ManagePermissions); + } + + protected override string GetDeleteConfirmationMessage(IdentityRoleDto entity) + { + return string.Format(L["RoleDeletionConfirmationMessage"], entity.Name); + } + + protected override ValueTask SetToolbarItemsAsync() + { + Toolbar.AddButton(L["NewRole"], + OpenCreateModalAsync, + IconName.Add, + requiredPolicyName: CreatePolicyName); + + return base.SetToolbarItemsAsync(); } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/RoleNameComponent.razor.cs b/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/RoleNameComponent.razor.cs index 5c16512afc..fd25f29b88 100644 --- a/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/RoleNameComponent.razor.cs +++ b/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/RoleNameComponent.razor.cs @@ -1,9 +1,8 @@ using Microsoft.AspNetCore.Components; -namespace Volo.Abp.Identity.Blazor.Pages.Identity +namespace Volo.Abp.Identity.Blazor.Pages.Identity; + +public partial class RoleNameComponent : ComponentBase { - public partial class RoleNameComponent : ComponentBase - { - [Parameter] public object Data { get; set; } - } -} \ No newline at end of file + [Parameter] public object Data { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/UserManagement.razor.cs b/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/UserManagement.razor.cs index c9084bd14d..67b002fc4a 100644 --- a/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/UserManagement.razor.cs +++ b/modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/UserManagement.razor.cs @@ -11,129 +11,129 @@ using Volo.Abp.Identity.Localization; using Volo.Abp.ObjectExtending; using Volo.Abp.PermissionManagement.Blazor.Components; -namespace Volo.Abp.Identity.Blazor.Pages.Identity +namespace Volo.Abp.Identity.Blazor.Pages.Identity; + +public partial class UserManagement { - public partial class UserManagement - { - protected const string PermissionProviderName = "U"; + protected const string PermissionProviderName = "U"; - protected const string DefaultSelectedTab = "UserInformations"; + protected const string DefaultSelectedTab = "UserInformations"; - protected PermissionManagementModal PermissionManagementModal; + protected PermissionManagementModal PermissionManagementModal; - protected IReadOnlyList Roles; + protected IReadOnlyList Roles; - protected AssignedRoleViewModel[] NewUserRoles; + protected AssignedRoleViewModel[] NewUserRoles; - protected AssignedRoleViewModel[] EditUserRoles; + protected AssignedRoleViewModel[] EditUserRoles; - protected string ManagePermissionsPolicyName; + protected string ManagePermissionsPolicyName; - protected bool HasManagePermissionsPermission { get; set; } + protected bool HasManagePermissionsPermission { get; set; } - protected string CreateModalSelectedTab = DefaultSelectedTab; + protected string CreateModalSelectedTab = DefaultSelectedTab; - protected string EditModalSelectedTab = DefaultSelectedTab; + protected string EditModalSelectedTab = DefaultSelectedTab; - protected PageToolbar Toolbar { get; } = new(); + protected PageToolbar Toolbar { get; } = new(); - private List UserManagementTableColumns => TableColumns.Get(); + private List UserManagementTableColumns => TableColumns.Get(); - public UserManagement() - { - ObjectMapperContext = typeof(AbpIdentityBlazorModule); - LocalizationResource = typeof(IdentityResource); + public UserManagement() + { + ObjectMapperContext = typeof(AbpIdentityBlazorModule); + LocalizationResource = typeof(IdentityResource); - CreatePolicyName = IdentityPermissions.Users.Create; - UpdatePolicyName = IdentityPermissions.Users.Update; - DeletePolicyName = IdentityPermissions.Users.Delete; - ManagePermissionsPolicyName = IdentityPermissions.Users.ManagePermissions; - } + CreatePolicyName = IdentityPermissions.Users.Create; + UpdatePolicyName = IdentityPermissions.Users.Update; + DeletePolicyName = IdentityPermissions.Users.Delete; + ManagePermissionsPolicyName = IdentityPermissions.Users.ManagePermissions; + } - protected override async Task OnInitializedAsync() - { - await base.OnInitializedAsync(); + protected override async Task OnInitializedAsync() + { + await base.OnInitializedAsync(); - try - { - Roles = (await AppService.GetAssignableRolesAsync()).Items; - } - catch (Exception ex) - { - await HandleErrorAsync(ex); - } + try + { + Roles = (await AppService.GetAssignableRolesAsync()).Items; } - - protected override async Task SetPermissionsAsync() + catch (Exception ex) { - await base.SetPermissionsAsync(); - - HasManagePermissionsPermission = - await AuthorizationService.IsGrantedAsync(IdentityPermissions.Users.ManagePermissions); + await HandleErrorAsync(ex); } + } - protected override Task OpenCreateModalAsync() - { - CreateModalSelectedTab = DefaultSelectedTab; + protected override async Task SetPermissionsAsync() + { + await base.SetPermissionsAsync(); - NewUserRoles = Roles.Select(x => new AssignedRoleViewModel - { - Name = x.Name, - IsAssigned = x.IsDefault - }).ToArray(); + HasManagePermissionsPermission = + await AuthorizationService.IsGrantedAsync(IdentityPermissions.Users.ManagePermissions); + } - return base.OpenCreateModalAsync(); - } + protected override Task OpenCreateModalAsync() + { + CreateModalSelectedTab = DefaultSelectedTab; - protected override Task OnCreatingEntityAsync() + NewUserRoles = Roles.Select(x => new AssignedRoleViewModel { - // apply roles before saving - NewEntity.RoleNames = NewUserRoles.Where(x => x.IsAssigned).Select(x => x.Name).ToArray(); + Name = x.Name, + IsAssigned = x.IsDefault + }).ToArray(); - return base.OnCreatingEntityAsync(); - } + return base.OpenCreateModalAsync(); + } - protected override async Task OpenEditModalAsync(IdentityUserDto entity) - { - try - { - EditModalSelectedTab = DefaultSelectedTab; + protected override Task OnCreatingEntityAsync() + { + // apply roles before saving + NewEntity.RoleNames = NewUserRoles.Where(x => x.IsAssigned).Select(x => x.Name).ToArray(); - var userRoleNames = (await AppService.GetRolesAsync(entity.Id)).Items.Select(r => r.Name).ToList(); + return base.OnCreatingEntityAsync(); + } - EditUserRoles = Roles.Select(x => new AssignedRoleViewModel - { - Name = x.Name, - IsAssigned = userRoleNames.Contains(x.Name) - }).ToArray(); + protected override async Task OpenEditModalAsync(IdentityUserDto entity) + { + try + { + EditModalSelectedTab = DefaultSelectedTab; - await base.OpenEditModalAsync(entity); - } - catch (Exception ex) - { - await HandleErrorAsync(ex); - } - } + var userRoleNames = (await AppService.GetRolesAsync(entity.Id)).Items.Select(r => r.Name).ToList(); - protected override Task OnUpdatingEntityAsync() - { - // apply roles before saving - EditingEntity.RoleNames = EditUserRoles.Where(x => x.IsAssigned).Select(x => x.Name).ToArray(); + EditUserRoles = Roles.Select(x => new AssignedRoleViewModel + { + Name = x.Name, + IsAssigned = userRoleNames.Contains(x.Name) + }).ToArray(); - return base.OnUpdatingEntityAsync(); + await base.OpenEditModalAsync(entity); } - - protected override string GetDeleteConfirmationMessage(IdentityUserDto entity) + catch (Exception ex) { - return string.Format(L["UserDeletionConfirmationMessage"], entity.UserName); + await HandleErrorAsync(ex); } + } - protected override ValueTask SetEntityActionsAsync() - { - EntityActions - .Get() - .AddRange(new EntityAction[] - { + protected override Task OnUpdatingEntityAsync() + { + // apply roles before saving + EditingEntity.RoleNames = EditUserRoles.Where(x => x.IsAssigned).Select(x => x.Name).ToArray(); + + return base.OnUpdatingEntityAsync(); + } + + protected override string GetDeleteConfirmationMessage(IdentityUserDto entity) + { + return string.Format(L["UserDeletionConfirmationMessage"], entity.UserName); + } + + protected override ValueTask SetEntityActionsAsync() + { + EntityActions + .Get() + .AddRange(new EntityAction[] + { new EntityAction { Text = L["Edit"], @@ -157,16 +157,16 @@ namespace Volo.Abp.Identity.Blazor.Pages.Identity Clicked = async (data) => await DeleteEntityAsync(data.As()), ConfirmationMessage = (data) => GetDeleteConfirmationMessage(data.As()) } - }); + }); - return base.SetEntityActionsAsync(); - } + return base.SetEntityActionsAsync(); + } - protected override ValueTask SetTableColumnsAsync() - { - UserManagementTableColumns - .AddRange(new TableColumn[] - { + protected override ValueTask SetTableColumnsAsync() + { + UserManagementTableColumns + .AddRange(new TableColumn[] + { new TableColumn { Title = L["Actions"], @@ -187,27 +187,26 @@ namespace Volo.Abp.Identity.Blazor.Pages.Identity Title = L["PhoneNumber"], Data = nameof(IdentityUserDto.PhoneNumber), } - }); + }); - UserManagementTableColumns.AddRange(GetExtensionTableColumns(IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.User)); - return base.SetEntityActionsAsync(); - } - - protected override ValueTask SetToolbarItemsAsync() - { - Toolbar.AddButton(L["NewUser"], OpenCreateModalAsync, - IconName.Add, - requiredPolicyName: CreatePolicyName); - - return base.SetToolbarItemsAsync(); - } + UserManagementTableColumns.AddRange(GetExtensionTableColumns(IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.User)); + return base.SetEntityActionsAsync(); } - public class AssignedRoleViewModel + protected override ValueTask SetToolbarItemsAsync() { - public string Name { get; set; } + Toolbar.AddButton(L["NewUser"], OpenCreateModalAsync, + IconName.Add, + requiredPolicyName: CreatePolicyName); - public bool IsAssigned { get; set; } + return base.SetToolbarItemsAsync(); } -} \ No newline at end of file +} + +public class AssignedRoleViewModel +{ + public string Name { get; set; } + + public bool IsAssigned { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/AbpIdentityDomainSharedModule.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/AbpIdentityDomainSharedModule.cs index 80d039b7d7..3fa7507e3b 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/AbpIdentityDomainSharedModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/AbpIdentityDomainSharedModule.cs @@ -9,35 +9,34 @@ using Volo.Abp.Validation; using Volo.Abp.Validation.Localization; using Volo.Abp.VirtualFileSystem; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[DependsOn( + typeof(AbpUsersDomainSharedModule), + typeof(AbpValidationModule), + typeof(AbpFeaturesModule) + )] +public class AbpIdentityDomainSharedModule : AbpModule { - [DependsOn( - typeof(AbpUsersDomainSharedModule), - typeof(AbpValidationModule), - typeof(AbpFeaturesModule) - )] - public class AbpIdentityDomainSharedModule : AbpModule + public override void ConfigureServices(ServiceConfigurationContext context) { - public override void ConfigureServices(ServiceConfigurationContext context) + Configure(options => { - Configure(options => - { - options.FileSets.AddEmbedded(); - }); + options.FileSets.AddEmbedded(); + }); - Configure(options => - { - options.Resources - .Add("en") - .AddBaseTypes( - typeof(AbpValidationResource) - ).AddVirtualJson("/Volo/Abp/Identity/Localization"); - }); + Configure(options => + { + options.Resources + .Add("en") + .AddBaseTypes( + typeof(AbpValidationResource) + ).AddVirtualJson("/Volo/Abp/Identity/Localization"); + }); - Configure(options => - { - options.MapCodeNamespace("Volo.Abp.Identity", typeof(IdentityResource)); - }); - } + Configure(options => + { + options.MapCodeNamespace("Volo.Abp.Identity", typeof(IdentityResource)); + }); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IUserRoleFinder.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IUserRoleFinder.cs index c30528ee33..31a865fc99 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IUserRoleFinder.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IUserRoleFinder.cs @@ -1,10 +1,9 @@ using System; using System.Threading.Tasks; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IUserRoleFinder { - public interface IUserRoleFinder - { - Task GetRolesAsync(Guid userId); - } + Task GetRolesAsync(Guid userId); } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimTypeConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimTypeConsts.cs index eafd0ed135..5dd0c442b9 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimTypeConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimTypeConsts.cs @@ -1,25 +1,24 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityClaimTypeConsts { - public class IdentityClaimTypeConsts - { - /// - /// Default value: 256 - /// - public static int MaxNameLength { get; set; } = 256; - - /// - /// Default value: 512 - /// - public static int MaxRegexLength { get; set; } = 512; - - /// - /// Default value: 128 - /// - public static int MaxRegexDescriptionLength { get; set; } = 128; - - /// - /// Default value: 256 - /// - public static int MaxDescriptionLength { get; set; } = 256; - } + /// + /// Default value: 256 + /// + public static int MaxNameLength { get; set; } = 256; + + /// + /// Default value: 512 + /// + public static int MaxRegexLength { get; set; } = 512; + + /// + /// Default value: 128 + /// + public static int MaxRegexDescriptionLength { get; set; } = 128; + + /// + /// Default value: 256 + /// + public static int MaxDescriptionLength { get; set; } = 256; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimTypeEto.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimTypeEto.cs index 2d0dd4ebfc..5c3d518ddd 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimTypeEto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimTypeEto.cs @@ -1,24 +1,23 @@ using System; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[Serializable] +public class IdentityClaimTypeEto { - [Serializable] - public class IdentityClaimTypeEto - { - public Guid Id { get; set; } - - public string Name { get; set; } + public Guid Id { get; set; } + + public string Name { get; set; } - public bool Required { get; set; } + public bool Required { get; set; } - public bool IsStatic { get; set; } + public bool IsStatic { get; set; } - public string Regex { get; set; } + public string Regex { get; set; } - public string RegexDescription { get; set; } + public string RegexDescription { get; set; } - public string Description { get; set; } + public string Description { get; set; } - public IdentityClaimValueType ValueType { get; set; } - } + public IdentityClaimValueType ValueType { get; set; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimValueType.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimValueType.cs index 7ea73ef3f0..5366104f15 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimValueType.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimValueType.cs @@ -1,10 +1,9 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public enum IdentityClaimValueType { - public enum IdentityClaimValueType - { - String, - Int, - Boolean, - DateTime - } + String, + Int, + Boolean, + DateTime } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityErrorCodes.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityErrorCodes.cs index b1a292d30e..ff808d9fbb 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityErrorCodes.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityErrorCodes.cs @@ -1,14 +1,13 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class IdentityErrorCodes { - public static class IdentityErrorCodes - { - public const string UserSelfDeletion = "Volo.Abp.Identity:010001"; - public const string MaxAllowedOuMembership = "Volo.Abp.Identity:010002"; - public const string ExternalUserPasswordChange = "Volo.Abp.Identity:010003"; - public const string DuplicateOrganizationUnitDisplayName = "Volo.Abp.Identity:010004"; - public const string StaticRoleRenaming = "Volo.Abp.Identity:010005"; - public const string StaticRoleDeletion = "Volo.Abp.Identity:010006"; - public const string UsersCanNotChangeTwoFactor = "Volo.Abp.Identity:010007"; - public const string CanNotChangeTwoFactor = "Volo.Abp.Identity:010008"; - } + public const string UserSelfDeletion = "Volo.Abp.Identity:010001"; + public const string MaxAllowedOuMembership = "Volo.Abp.Identity:010002"; + public const string ExternalUserPasswordChange = "Volo.Abp.Identity:010003"; + public const string DuplicateOrganizationUnitDisplayName = "Volo.Abp.Identity:010004"; + public const string StaticRoleRenaming = "Volo.Abp.Identity:010005"; + public const string StaticRoleDeletion = "Volo.Abp.Identity:010006"; + public const string UsersCanNotChangeTwoFactor = "Volo.Abp.Identity:010007"; + public const string CanNotChangeTwoFactor = "Volo.Abp.Identity:010008"; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleClaimConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleClaimConsts.cs index 0f20ac40ef..a36d63ce4e 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleClaimConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleClaimConsts.cs @@ -1,9 +1,8 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class IdentityRoleClaimConsts { - public static class IdentityRoleClaimConsts - { - public static int MaxClaimTypeLength { get; set; } = IdentityUserClaimConsts.MaxClaimTypeLength; + public static int MaxClaimTypeLength { get; set; } = IdentityUserClaimConsts.MaxClaimTypeLength; - public static int MaxClaimValueLength { get; set; } = IdentityUserClaimConsts.MaxClaimValueLength; - } + public static int MaxClaimValueLength { get; set; } = IdentityUserClaimConsts.MaxClaimValueLength; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleConsts.cs index f51be5da8f..a4e4541e59 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleConsts.cs @@ -1,15 +1,14 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class IdentityRoleConsts { - public static class IdentityRoleConsts - { - /// - /// Default value: 256 - /// - public static int MaxNameLength { get; set; } = 256; - - /// - /// Default value: 256 - /// - public static int MaxNormalizedNameLength { get; set; } = 256; - } + /// + /// Default value: 256 + /// + public static int MaxNameLength { get; set; } = 256; + + /// + /// Default value: 256 + /// + public static int MaxNormalizedNameLength { get; set; } = 256; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleEto.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleEto.cs index 8e91eadf72..ffc29488bf 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleEto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleEto.cs @@ -1,20 +1,19 @@ using System; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[Serializable] +public class IdentityRoleEto { - [Serializable] - public class IdentityRoleEto - { - public Guid Id { get; set; } + public Guid Id { get; set; } + + public Guid? TenantId { get; set; } + + public string Name { get; set; } - public Guid? TenantId { get; set; } + public bool IsDefault { get; set; } - public string Name { get; set; } - - public bool IsDefault { get; set; } + public bool IsStatic { get; set; } - public bool IsStatic { get; set; } - - public bool IsPublic { get; set; } - } -} \ No newline at end of file + public bool IsPublic { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleNameChangedEto.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleNameChangedEto.cs index b8ae9e537b..0bce1079b5 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleNameChangedEto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleNameChangedEto.cs @@ -1,16 +1,15 @@ using System; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[Serializable] +public class IdentityRoleNameChangedEto { - [Serializable] - public class IdentityRoleNameChangedEto - { - public Guid Id { get; set; } + public Guid Id { get; set; } - public Guid? TenantId { get; set; } + public Guid? TenantId { get; set; } - public string Name { get; set; } + public string Name { get; set; } - public string OldName { get; set; } - } -} \ No newline at end of file + public string OldName { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogActionConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogActionConsts.cs index ea5276e673..cb5279fd89 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogActionConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogActionConsts.cs @@ -1,33 +1,32 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentitySecurityLogActionConsts { - public class IdentitySecurityLogActionConsts - { - public static string LoginSucceeded { get; set; } = "LoginSucceeded"; + public static string LoginSucceeded { get; set; } = "LoginSucceeded"; - public static string LoginLockedout { get; set; } = "LoginLockedout"; + public static string LoginLockedout { get; set; } = "LoginLockedout"; - public static string LoginNotAllowed { get; set; } = "LoginNotAllowed"; + public static string LoginNotAllowed { get; set; } = "LoginNotAllowed"; - public static string LoginRequiresTwoFactor { get; set; } = "LoginRequiresTwoFactor"; + public static string LoginRequiresTwoFactor { get; set; } = "LoginRequiresTwoFactor"; - public static string LoginFailed { get; set; } = "LoginFailed"; + public static string LoginFailed { get; set; } = "LoginFailed"; - public static string LoginInvalidUserName { get; set; } = "LoginInvalidUserName"; + public static string LoginInvalidUserName { get; set; } = "LoginInvalidUserName"; - public static string LoginInvalidUserNameOrPassword { get; set; } = "LoginInvalidUserNameOrPassword"; + public static string LoginInvalidUserNameOrPassword { get; set; } = "LoginInvalidUserNameOrPassword"; - public static string Logout { get; set; } = "Logout"; + public static string Logout { get; set; } = "Logout"; - public static string ChangeUserName { get; set; } = "ChangeUserName"; + public static string ChangeUserName { get; set; } = "ChangeUserName"; - public static string ChangeEmail { get; set; } = "ChangeEmail"; + public static string ChangeEmail { get; set; } = "ChangeEmail"; - public static string ChangePhoneNumber { get; set; } = "ChangePhoneNumber"; + public static string ChangePhoneNumber { get; set; } = "ChangePhoneNumber"; - public static string ChangePassword { get; set; } = "ChangePassword"; + public static string ChangePassword { get; set; } = "ChangePassword"; - public static string TwoFactorEnabled { get; set; } = "TwoFactorEnabled"; + public static string TwoFactorEnabled { get; set; } = "TwoFactorEnabled"; - public static string TwoFactorDisabled { get; set; } = "TwoFactorDisabled"; - } + public static string TwoFactorDisabled { get; set; } = "TwoFactorDisabled"; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogConsts.cs index 43b2dd25fb..7c30597b56 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogConsts.cs @@ -1,52 +1,51 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentitySecurityLogConsts { - public class IdentitySecurityLogConsts - { - /// - /// Default value: 96 - /// - public static int MaxApplicationNameLength { get; set; } = 96; - - /// - /// Default value: 96 - /// - public static int MaxIdentityLength { get; set; } = 96; - - /// - /// Default value: 96 - /// - public static int MaxActionLength { get; set; } = 96; - - - /// - /// Default value: 256 - /// - public static int MaxUserNameLength { get; set; } = 256; - - /// - /// Default value: 64 - /// - public static int MaxTenantNameLength { get; set; } = 64; - - /// - /// Default value: 64 - /// - public static int MaxClientIpAddressLength { get; set; } = 64; - - /// - /// Default value: 64 - /// - public static int MaxClientIdLength { get; set; } = 64; - - /// - /// Default value: 64 - /// - public static int MaxCorrelationIdLength { get; set; } = 64; - - /// - /// Default value: 512 - /// - public static int MaxBrowserInfoLength { get; set; } = 512; - - } + /// + /// Default value: 96 + /// + public static int MaxApplicationNameLength { get; set; } = 96; + + /// + /// Default value: 96 + /// + public static int MaxIdentityLength { get; set; } = 96; + + /// + /// Default value: 96 + /// + public static int MaxActionLength { get; set; } = 96; + + + /// + /// Default value: 256 + /// + public static int MaxUserNameLength { get; set; } = 256; + + /// + /// Default value: 64 + /// + public static int MaxTenantNameLength { get; set; } = 64; + + /// + /// Default value: 64 + /// + public static int MaxClientIpAddressLength { get; set; } = 64; + + /// + /// Default value: 64 + /// + public static int MaxClientIdLength { get; set; } = 64; + + /// + /// Default value: 64 + /// + public static int MaxCorrelationIdLength { get; set; } = 64; + + /// + /// Default value: 512 + /// + public static int MaxBrowserInfoLength { get; set; } = 512; + } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogIdentityConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogIdentityConsts.cs index 5616dfb4e6..597f187b5e 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogIdentityConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogIdentityConsts.cs @@ -1,11 +1,10 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class IdentitySecurityLogIdentityConsts { - public static class IdentitySecurityLogIdentityConsts - { - public static string Identity { get; set; } = "Identity"; + public static string Identity { get; set; } = "Identity"; - public static string IdentityExternal { get; set; } = "IdentityExternal"; + public static string IdentityExternal { get; set; } = "IdentityExternal"; - public static string IdentityTwoFactor { get; set; } = "IdentityTwoFactor"; - } + public static string IdentityTwoFactor { get; set; } = "IdentityTwoFactor"; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserClaimConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserClaimConsts.cs index 84ba493853..27c0e5c2c3 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserClaimConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserClaimConsts.cs @@ -1,15 +1,14 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class IdentityUserClaimConsts { - public static class IdentityUserClaimConsts - { - /// - /// Default value: 256 - /// - public static int MaxClaimTypeLength { get; set; } = 256; + /// + /// Default value: 256 + /// + public static int MaxClaimTypeLength { get; set; } = 256; - /// - /// Default value: 1024 - /// - public static int MaxClaimValueLength { get; set; } = 1024; - } + /// + /// Default value: 1024 + /// + public static int MaxClaimValueLength { get; set; } = 1024; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserConsts.cs index 01c6e285a9..d7039d690b 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserConsts.cs @@ -1,41 +1,40 @@ using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class IdentityUserConsts { - public static class IdentityUserConsts - { - public static int MaxUserNameLength { get; set; } = AbpUserConsts.MaxUserNameLength; + public static int MaxUserNameLength { get; set; } = AbpUserConsts.MaxUserNameLength; - public static int MaxNameLength { get; set; } = AbpUserConsts.MaxNameLength; + public static int MaxNameLength { get; set; } = AbpUserConsts.MaxNameLength; - public static int MaxSurnameLength { get; set; } = AbpUserConsts.MaxSurnameLength; + public static int MaxSurnameLength { get; set; } = AbpUserConsts.MaxSurnameLength; - public static int MaxNormalizedUserNameLength { get; set; } = MaxUserNameLength; + public static int MaxNormalizedUserNameLength { get; set; } = MaxUserNameLength; - public static int MaxEmailLength { get; set; } = AbpUserConsts.MaxEmailLength; + public static int MaxEmailLength { get; set; } = AbpUserConsts.MaxEmailLength; - public static int MaxNormalizedEmailLength { get; set; } = MaxEmailLength; + public static int MaxNormalizedEmailLength { get; set; } = MaxEmailLength; - public static int MaxPhoneNumberLength { get; set; } = AbpUserConsts.MaxPhoneNumberLength; + public static int MaxPhoneNumberLength { get; set; } = AbpUserConsts.MaxPhoneNumberLength; - /// - /// Default value: 128 - /// - public static int MaxPasswordLength { get; set; } = 128; + /// + /// Default value: 128 + /// + public static int MaxPasswordLength { get; set; } = 128; - /// - /// Default value: 256 - /// - public static int MaxPasswordHashLength { get; set; } = 256; + /// + /// Default value: 256 + /// + public static int MaxPasswordHashLength { get; set; } = 256; - /// - /// Default value: 256 - /// - public static int MaxSecurityStampLength { get; set; } = 256; + /// + /// Default value: 256 + /// + public static int MaxSecurityStampLength { get; set; } = 256; - /// - /// Default value: 16 - /// - public static int MaxLoginProviderLength { get; set; } = 16; - } + /// + /// Default value: 16 + /// + public static int MaxLoginProviderLength { get; set; } = 16; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserLoginConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserLoginConsts.cs index 8435221fd3..8daca1f914 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserLoginConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserLoginConsts.cs @@ -1,20 +1,19 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class IdentityUserLoginConsts { - public static class IdentityUserLoginConsts - { - /// - /// Default value: 64 - /// - public static int MaxLoginProviderLength { get; set; } = 64; - - /// - /// Default value: 196 - /// - public static int MaxProviderKeyLength { get; set; } = 196; - - /// - /// Default value: 128 - /// - public static int MaxProviderDisplayNameLength { get; set; } = 128; - } + /// + /// Default value: 64 + /// + public static int MaxLoginProviderLength { get; set; } = 64; + + /// + /// Default value: 196 + /// + public static int MaxProviderKeyLength { get; set; } = 196; + + /// + /// Default value: 128 + /// + public static int MaxProviderDisplayNameLength { get; set; } = 128; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserTokenConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserTokenConsts.cs index a585a8383b..d3096ddc59 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserTokenConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserTokenConsts.cs @@ -1,15 +1,14 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class IdentityUserTokenConsts { - public static class IdentityUserTokenConsts - { - /// - /// Default value: 64 - /// - public static int MaxLoginProviderLength { get; set; } = 64; + /// + /// Default value: 64 + /// + public static int MaxLoginProviderLength { get; set; } = 64; - /// - /// Default value: 128 - /// - public static int MaxNameLength { get; set; } = 128; - } + /// + /// Default value: 128 + /// + public static int MaxNameLength { get; set; } = 128; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/LinkUserTokenProviderConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/LinkUserTokenProviderConsts.cs index 863734ce8a..1432210edb 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/LinkUserTokenProviderConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/LinkUserTokenProviderConsts.cs @@ -1,11 +1,10 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class LinkUserTokenProviderConsts { - public static class LinkUserTokenProviderConsts - { - public static string LinkUserTokenProviderName { get; set; } = "AbpLinkUser"; + public static string LinkUserTokenProviderName { get; set; } = "AbpLinkUser"; - public static string LinkUserTokenPurpose { get; set; } = "AbpLinkUser"; + public static string LinkUserTokenPurpose { get; set; } = "AbpLinkUser"; - public static string LinkUserLoginTokenPurpose { get; set; } = "AbpLinkUserLogin"; - } + public static string LinkUserLoginTokenPurpose { get; set; } = "AbpLinkUserLogin"; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Localization/IdentityResource.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Localization/IdentityResource.cs index 7c5ed0bdd4..f1deaf4094 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Localization/IdentityResource.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Localization/IdentityResource.cs @@ -1,10 +1,9 @@ using Volo.Abp.Localization; -namespace Volo.Abp.Identity.Localization +namespace Volo.Abp.Identity.Localization; + +[LocalizationResourceName("AbpIdentity")] +public class IdentityResource { - [LocalizationResourceName("AbpIdentity")] - public class IdentityResource - { - - } + } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/OrganizationUnitConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/OrganizationUnitConsts.cs index 997a394a7d..1058c1b5cb 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/OrganizationUnitConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/OrganizationUnitConsts.cs @@ -1,25 +1,24 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class OrganizationUnitConsts { - public static class OrganizationUnitConsts - { - /// - /// Maximum length of the DisplayName property. - /// - public static int MaxDisplayNameLength { get; set; } = 128; + /// + /// Maximum length of the DisplayName property. + /// + public static int MaxDisplayNameLength { get; set; } = 128; - /// - /// Maximum depth of an OU hierarchy. - /// - public const int MaxDepth = 16; + /// + /// Maximum depth of an OU hierarchy. + /// + public const int MaxDepth = 16; - /// - /// Length of a code unit between dots. - /// - public const int CodeUnitLength = 5; + /// + /// Length of a code unit between dots. + /// + public const int CodeUnitLength = 5; - /// - /// Maximum length of the Code property. - /// - public const int MaxCodeLength = MaxDepth * (CodeUnitLength + 1) - 1; - } + /// + /// Maximum length of the Code property. + /// + public const int MaxCodeLength = MaxDepth * (CodeUnitLength + 1) - 1; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/OrganizationUnitEto.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/OrganizationUnitEto.cs index 09013aa1ce..3ccdb7e076 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/OrganizationUnitEto.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/OrganizationUnitEto.cs @@ -1,16 +1,15 @@ using System; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[Serializable] +public class OrganizationUnitEto { - [Serializable] - public class OrganizationUnitEto - { - public Guid Id { get; set; } + public Guid Id { get; set; } - public Guid? TenantId { get; set; } + public Guid? TenantId { get; set; } - public string Code { get; set; } + public string Code { get; set; } - public string DisplayName { get; set; } - } -} \ No newline at end of file + public string DisplayName { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Settings/IdentitySettingNames.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Settings/IdentitySettingNames.cs index 968b732092..70c2430751 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Settings/IdentitySettingNames.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Settings/IdentitySettingNames.cs @@ -1,52 +1,51 @@ -namespace Volo.Abp.Identity.Settings +namespace Volo.Abp.Identity.Settings; + +public static class IdentitySettingNames { - public static class IdentitySettingNames + private const string Prefix = "Abp.Identity"; + + public static class Password + { + private const string PasswordPrefix = Prefix + ".Password"; + + public const string RequiredLength = PasswordPrefix + ".RequiredLength"; + public const string RequiredUniqueChars = PasswordPrefix + ".RequiredUniqueChars"; + public const string RequireNonAlphanumeric = PasswordPrefix + ".RequireNonAlphanumeric"; + public const string RequireLowercase = PasswordPrefix + ".RequireLowercase"; + public const string RequireUppercase = PasswordPrefix + ".RequireUppercase"; + public const string RequireDigit = PasswordPrefix + ".RequireDigit"; + } + + public static class Lockout + { + private const string LockoutPrefix = Prefix + ".Lockout"; + + public const string AllowedForNewUsers = LockoutPrefix + ".AllowedForNewUsers"; + public const string LockoutDuration = LockoutPrefix + ".LockoutDuration"; + public const string MaxFailedAccessAttempts = LockoutPrefix + ".MaxFailedAccessAttempts"; + } + + public static class SignIn { - private const string Prefix = "Abp.Identity"; - - public static class Password - { - private const string PasswordPrefix = Prefix + ".Password"; - - public const string RequiredLength = PasswordPrefix + ".RequiredLength"; - public const string RequiredUniqueChars = PasswordPrefix + ".RequiredUniqueChars"; - public const string RequireNonAlphanumeric = PasswordPrefix + ".RequireNonAlphanumeric"; - public const string RequireLowercase = PasswordPrefix + ".RequireLowercase"; - public const string RequireUppercase = PasswordPrefix + ".RequireUppercase"; - public const string RequireDigit = PasswordPrefix + ".RequireDigit"; - } - - public static class Lockout - { - private const string LockoutPrefix = Prefix + ".Lockout"; - - public const string AllowedForNewUsers = LockoutPrefix + ".AllowedForNewUsers"; - public const string LockoutDuration = LockoutPrefix + ".LockoutDuration"; - public const string MaxFailedAccessAttempts = LockoutPrefix + ".MaxFailedAccessAttempts"; - } - - public static class SignIn - { - private const string SignInPrefix = Prefix + ".SignIn"; - - public const string RequireConfirmedEmail = SignInPrefix + ".RequireConfirmedEmail"; - public const string EnablePhoneNumberConfirmation = SignInPrefix + ".EnablePhoneNumberConfirmation"; - public const string RequireConfirmedPhoneNumber = SignInPrefix + ".RequireConfirmedPhoneNumber"; - } - - public static class User - { - private const string UserPrefix = Prefix + ".User"; - - public const string IsUserNameUpdateEnabled = UserPrefix + ".IsUserNameUpdateEnabled"; - public const string IsEmailUpdateEnabled = UserPrefix + ".IsEmailUpdateEnabled"; - } - - public static class OrganizationUnit - { - private const string OrganizationUnitPrefix = Prefix + ".OrganizationUnit"; - - public const string MaxUserMembershipCount = OrganizationUnitPrefix + ".MaxUserMembershipCount"; - } + private const string SignInPrefix = Prefix + ".SignIn"; + + public const string RequireConfirmedEmail = SignInPrefix + ".RequireConfirmedEmail"; + public const string EnablePhoneNumberConfirmation = SignInPrefix + ".EnablePhoneNumberConfirmation"; + public const string RequireConfirmedPhoneNumber = SignInPrefix + ".RequireConfirmedPhoneNumber"; + } + + public static class User + { + private const string UserPrefix = Prefix + ".User"; + + public const string IsUserNameUpdateEnabled = UserPrefix + ".IsUserNameUpdateEnabled"; + public const string IsEmailUpdateEnabled = UserPrefix + ".IsEmailUpdateEnabled"; + } + + public static class OrganizationUnit + { + private const string OrganizationUnitPrefix = Prefix + ".OrganizationUnit"; + + public const string MaxUserMembershipCount = OrganizationUnitPrefix + ".MaxUserMembershipCount"; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfiguration.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfiguration.cs index a8e488871a..4bcf4f01e3 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfiguration.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfiguration.cs @@ -1,44 +1,43 @@ using System; using Volo.Abp.ObjectExtending.Modularity; -namespace Volo.Abp.ObjectExtending +namespace Volo.Abp.ObjectExtending; + +public class IdentityModuleExtensionConfiguration : ModuleExtensionConfiguration { - public class IdentityModuleExtensionConfiguration : ModuleExtensionConfiguration + public IdentityModuleExtensionConfiguration ConfigureUser( + Action configureAction) + { + return this.ConfigureEntity( + IdentityModuleExtensionConsts.EntityNames.User, + configureAction + ); + } + + public IdentityModuleExtensionConfiguration ConfigureRole( + Action configureAction) { - public IdentityModuleExtensionConfiguration ConfigureUser( - Action configureAction) - { - return this.ConfigureEntity( - IdentityModuleExtensionConsts.EntityNames.User, - configureAction - ); - } + return this.ConfigureEntity( + IdentityModuleExtensionConsts.EntityNames.Role, + configureAction + ); + } - public IdentityModuleExtensionConfiguration ConfigureRole( - Action configureAction) - { - return this.ConfigureEntity( - IdentityModuleExtensionConsts.EntityNames.Role, - configureAction - ); - } + public IdentityModuleExtensionConfiguration ConfigureClaimType( + Action configureAction) + { + return this.ConfigureEntity( + IdentityModuleExtensionConsts.EntityNames.ClaimType, + configureAction + ); + } - public IdentityModuleExtensionConfiguration ConfigureClaimType( - Action configureAction) - { - return this.ConfigureEntity( - IdentityModuleExtensionConsts.EntityNames.ClaimType, - configureAction - ); - } - - public IdentityModuleExtensionConfiguration ConfigureOrganizationUnit( - Action configureAction) - { - return this.ConfigureEntity( - IdentityModuleExtensionConsts.EntityNames.OrganizationUnit, - configureAction - ); - } + public IdentityModuleExtensionConfiguration ConfigureOrganizationUnit( + Action configureAction) + { + return this.ConfigureEntity( + IdentityModuleExtensionConsts.EntityNames.OrganizationUnit, + configureAction + ); } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfigurationDictionaryExtensions.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfigurationDictionaryExtensions.cs index 40fbb3b594..f77c7b8752 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfigurationDictionaryExtensions.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfigurationDictionaryExtensions.cs @@ -1,18 +1,17 @@ using System; using Volo.Abp.ObjectExtending.Modularity; -namespace Volo.Abp.ObjectExtending +namespace Volo.Abp.ObjectExtending; + +public static class IdentityModuleExtensionConfigurationDictionaryExtensions { - public static class IdentityModuleExtensionConfigurationDictionaryExtensions + public static ModuleExtensionConfigurationDictionary ConfigureIdentity( + this ModuleExtensionConfigurationDictionary modules, + Action configureAction) { - public static ModuleExtensionConfigurationDictionary ConfigureIdentity( - this ModuleExtensionConfigurationDictionary modules, - Action configureAction) - { - return modules.ConfigureModule( - IdentityModuleExtensionConsts.ModuleName, - configureAction - ); - } + return modules.ConfigureModule( + IdentityModuleExtensionConsts.ModuleName, + configureAction + ); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConsts.cs b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConsts.cs index 45c9db6462..a9a150aa6d 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConsts.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConsts.cs @@ -1,18 +1,17 @@ -namespace Volo.Abp.ObjectExtending +namespace Volo.Abp.ObjectExtending; + +public static class IdentityModuleExtensionConsts { - public static class IdentityModuleExtensionConsts + public const string ModuleName = "Identity"; + + public static class EntityNames { - public const string ModuleName = "Identity"; + public const string User = "User"; - public static class EntityNames - { - public const string User = "User"; + public const string Role = "Role"; - public const string Role = "Role"; + public const string ClaimType = "ClaimType"; - public const string ClaimType = "ClaimType"; - - public const string OrganizationUnit = "OrganizationUnit"; - } + public const string OrganizationUnit = "OrganizationUnit"; } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Microsoft/AspNetCore/Identity/AbpIdentityResultExtensions.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Microsoft/AspNetCore/Identity/AbpIdentityResultExtensions.cs index cb1ffc9d8a..4f9bacac1f 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Microsoft/AspNetCore/Identity/AbpIdentityResultExtensions.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Microsoft/AspNetCore/Identity/AbpIdentityResultExtensions.cs @@ -8,146 +8,145 @@ using Volo.Abp; using Volo.Abp.Identity; using Volo.Abp.Text.Formatting; -namespace Microsoft.AspNetCore.Identity +namespace Microsoft.AspNetCore.Identity; + +public static class AbpIdentityResultExtensions { - public static class AbpIdentityResultExtensions + private static readonly Dictionary IdentityStrings = new Dictionary(); + + static AbpIdentityResultExtensions() { - private static readonly Dictionary IdentityStrings = new Dictionary(); + var identityResourceManager = new ResourceManager("Microsoft.Extensions.Identity.Core.Resources", typeof(UserManager<>).Assembly); + var resourceSet = identityResourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, false); + if (resourceSet == null) + { + throw new AbpException("Can't get the ResourceSet of Identity."); + } - static AbpIdentityResultExtensions() + var iterator = resourceSet.GetEnumerator(); + while (true) { - var identityResourceManager = new ResourceManager("Microsoft.Extensions.Identity.Core.Resources", typeof(UserManager<>).Assembly); - var resourceSet = identityResourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, false); - if (resourceSet == null) + if (!iterator.MoveNext()) { - throw new AbpException("Can't get the ResourceSet of Identity."); + break; } - var iterator = resourceSet.GetEnumerator(); - while (true) + var key = iterator.Key?.ToString(); + var value = iterator.Value?.ToString(); + if (key != null && value != null) { - if (!iterator.MoveNext()) - { - break; - } - - var key = iterator.Key?.ToString(); - var value = iterator.Value?.ToString(); - if (key != null && value != null) - { - IdentityStrings.Add(key, value); - } - } - - if (!IdentityStrings.Any()) - { - throw new AbpException("ResourceSet values of Identity is empty."); + IdentityStrings.Add(key, value); } } - public static void CheckErrors(this IdentityResult identityResult) + if (!IdentityStrings.Any()) { - if (identityResult.Succeeded) - { - return; - } - - if (identityResult.Errors == null) - { - throw new ArgumentException("identityResult.Errors should not be null."); - } + throw new AbpException("ResourceSet values of Identity is empty."); + } + } - throw new AbpIdentityResultException(identityResult); + public static void CheckErrors(this IdentityResult identityResult) + { + if (identityResult.Succeeded) + { + return; } - public static string[] GetValuesFromErrorMessage(this IdentityResult identityResult, IStringLocalizer localizer) + if (identityResult.Errors == null) { - if (identityResult.Succeeded) - { - throw new ArgumentException( - "identityResult.Succeeded should be false in order to get values from error."); - } + throw new ArgumentException("identityResult.Errors should not be null."); + } - if (identityResult.Errors == null) - { - throw new ArgumentException("identityResult.Errors should not be null."); - } + throw new AbpIdentityResultException(identityResult); + } - var error = identityResult.Errors.First(); - var englishString = IdentityStrings.GetOrDefault(error.Code); + public static string[] GetValuesFromErrorMessage(this IdentityResult identityResult, IStringLocalizer localizer) + { + if (identityResult.Succeeded) + { + throw new ArgumentException( + "identityResult.Succeeded should be false in order to get values from error."); + } - if (englishString == null) - { - return Array.Empty(); - } + if (identityResult.Errors == null) + { + throw new ArgumentException("identityResult.Errors should not be null."); + } - if (FormattedStringValueExtracter.IsMatch(error.Description, englishString, out var values)) - { - return values; - } + var error = identityResult.Errors.First(); + var englishString = IdentityStrings.GetOrDefault(error.Code); + if (englishString == null) + { return Array.Empty(); } - public static string LocalizeErrors(this IdentityResult identityResult, IStringLocalizer localizer) + if (FormattedStringValueExtracter.IsMatch(error.Description, englishString, out var values)) { - if (identityResult.Succeeded) - { - throw new ArgumentException("identityResult.Succeeded should be false in order to localize errors."); - } + return values; + } - if (identityResult.Errors == null) - { - throw new ArgumentException("identityResult.Errors should not be null."); - } + return Array.Empty(); + } - return identityResult.Errors.Select(err => LocalizeErrorMessage(err, localizer)).JoinAsString(", "); + public static string LocalizeErrors(this IdentityResult identityResult, IStringLocalizer localizer) + { + if (identityResult.Succeeded) + { + throw new ArgumentException("identityResult.Succeeded should be false in order to localize errors."); } - public static string LocalizeErrorMessage(this IdentityError error, IStringLocalizer localizer) + if (identityResult.Errors == null) { - var key = $"Volo.Abp.Identity:{error.Code}"; + throw new ArgumentException("identityResult.Errors should not be null."); + } + + return identityResult.Errors.Select(err => LocalizeErrorMessage(err, localizer)).JoinAsString(", "); + } + + public static string LocalizeErrorMessage(this IdentityError error, IStringLocalizer localizer) + { + var key = $"Volo.Abp.Identity:{error.Code}"; - var localizedString = localizer[key]; + var localizedString = localizer[key]; - if (!localizedString.ResourceNotFound) + if (!localizedString.ResourceNotFound) + { + var englishString = IdentityStrings.GetOrDefault(error.Code); + if (englishString != null) { - var englishString = IdentityStrings.GetOrDefault(error.Code); - if (englishString != null) + if (FormattedStringValueExtracter.IsMatch(error.Description, englishString, out var values)) { - if (FormattedStringValueExtracter.IsMatch(error.Description, englishString, out var values)) - { - return string.Format(localizedString.Value, values.Cast().ToArray()); - } + return string.Format(localizedString.Value, values.Cast().ToArray()); } } - - return localizer["Identity.Default"]; } - public static string GetResultAsString(this SignInResult signInResult) - { - if (signInResult.Succeeded) - { - return "Succeeded"; - } + return localizer["Identity.Default"]; + } - if (signInResult.IsLockedOut) - { - return "IsLockedOut"; - } + public static string GetResultAsString(this SignInResult signInResult) + { + if (signInResult.Succeeded) + { + return "Succeeded"; + } - if (signInResult.IsNotAllowed) - { - return "IsNotAllowed"; - } + if (signInResult.IsLockedOut) + { + return "IsLockedOut"; + } - if (signInResult.RequiresTwoFactor) - { - return "RequiresTwoFactor"; - } + if (signInResult.IsNotAllowed) + { + return "IsNotAllowed"; + } - return "Unknown"; + if (signInResult.RequiresTwoFactor) + { + return "RequiresTwoFactor"; } + + return "Unknown"; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Microsoft/Extensions/DependencyInjection/AbpIdentityServiceCollectionExtensions.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Microsoft/Extensions/DependencyInjection/AbpIdentityServiceCollectionExtensions.cs index 5dfdf2944d..37e66a4a96 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Microsoft/Extensions/DependencyInjection/AbpIdentityServiceCollectionExtensions.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Microsoft/Extensions/DependencyInjection/AbpIdentityServiceCollectionExtensions.cs @@ -3,37 +3,36 @@ using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection.Extensions; using Volo.Abp.Identity; -namespace Microsoft.Extensions.DependencyInjection +namespace Microsoft.Extensions.DependencyInjection; + +public static class AbpIdentityServiceCollectionExtensions { - public static class AbpIdentityServiceCollectionExtensions + public static IdentityBuilder AddAbpIdentity(this IServiceCollection services) { - public static IdentityBuilder AddAbpIdentity(this IServiceCollection services) - { - return services.AddAbpIdentity(setupAction: null); - } + return services.AddAbpIdentity(setupAction: null); + } - public static IdentityBuilder AddAbpIdentity(this IServiceCollection services, Action setupAction) - { - //AbpRoleManager - services.TryAddScoped(); - services.TryAddScoped(typeof(RoleManager), provider => provider.GetService(typeof(IdentityRoleManager))); + public static IdentityBuilder AddAbpIdentity(this IServiceCollection services, Action setupAction) + { + //AbpRoleManager + services.TryAddScoped(); + services.TryAddScoped(typeof(RoleManager), provider => provider.GetService(typeof(IdentityRoleManager))); - //AbpUserManager - services.TryAddScoped(); - services.TryAddScoped(typeof(UserManager), provider => provider.GetService(typeof(IdentityUserManager))); + //AbpUserManager + services.TryAddScoped(); + services.TryAddScoped(typeof(UserManager), provider => provider.GetService(typeof(IdentityUserManager))); - //AbpUserStore - services.TryAddScoped(); - services.TryAddScoped(typeof(IUserStore), provider => provider.GetService(typeof(IdentityUserStore))); + //AbpUserStore + services.TryAddScoped(); + services.TryAddScoped(typeof(IUserStore), provider => provider.GetService(typeof(IdentityUserStore))); - //AbpRoleStore - services.TryAddScoped(); - services.TryAddScoped(typeof(IRoleStore), provider => provider.GetService(typeof(IdentityRoleStore))); + //AbpRoleStore + services.TryAddScoped(); + services.TryAddScoped(typeof(IRoleStore), provider => provider.GetService(typeof(IdentityRoleStore))); - return services - .AddIdentityCore(setupAction) - .AddRoles() - .AddClaimsPrincipalFactory(); - } + return services + .AddIdentityCore(setupAction) + .AddRoles() + .AddClaimsPrincipalFactory(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityDbProperties.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityDbProperties.cs index cd40984cc0..bbf7aa6701 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityDbProperties.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityDbProperties.cs @@ -1,13 +1,12 @@ using Volo.Abp.Data; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class AbpIdentityDbProperties { - public static class AbpIdentityDbProperties - { - public static string DbTablePrefix { get; set; } = AbpCommonDbProperties.DbTablePrefix; + public static string DbTablePrefix { get; set; } = AbpCommonDbProperties.DbTablePrefix; - public static string DbSchema { get; set; } = AbpCommonDbProperties.DbSchema; + public static string DbSchema { get; set; } = AbpCommonDbProperties.DbSchema; - public const string ConnectionStringName = "AbpIdentity"; - } + public const string ConnectionStringName = "AbpIdentity"; } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityDomainModule.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityDomainModule.cs index 79f5fb647b..2278eb022c 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityDomainModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityDomainModule.cs @@ -13,84 +13,83 @@ using Volo.Abp.Security.Claims; using Volo.Abp.Threading; using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[DependsOn( + typeof(AbpDddDomainModule), + typeof(AbpIdentityDomainSharedModule), + typeof(AbpUsersDomainModule), + typeof(AbpAutoMapperModule) + )] +public class AbpIdentityDomainModule : AbpModule { - [DependsOn( - typeof(AbpDddDomainModule), - typeof(AbpIdentityDomainSharedModule), - typeof(AbpUsersDomainModule), - typeof(AbpAutoMapperModule) - )] - public class AbpIdentityDomainModule : AbpModule + private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); + + public override void ConfigureServices(ServiceConfigurationContext context) { - private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); + context.Services.AddAutoMapperObjectMapper(); - public override void ConfigureServices(ServiceConfigurationContext context) + Configure(options => { - context.Services.AddAutoMapperObjectMapper(); + options.AddProfile(validate: true); + }); - Configure(options => - { - options.AddProfile(validate: true); - }); + Configure(options => + { + options.EtoMappings.Add(typeof(AbpIdentityDomainModule)); + options.EtoMappings.Add(typeof(AbpIdentityDomainModule)); + options.EtoMappings.Add(typeof(AbpIdentityDomainModule)); + options.EtoMappings.Add(typeof(AbpIdentityDomainModule)); - Configure(options => - { - options.EtoMappings.Add(typeof(AbpIdentityDomainModule)); - options.EtoMappings.Add(typeof(AbpIdentityDomainModule)); - options.EtoMappings.Add(typeof(AbpIdentityDomainModule)); - options.EtoMappings.Add(typeof(AbpIdentityDomainModule)); - - options.AutoEventSelectors.Add(); - options.AutoEventSelectors.Add(); - }); + options.AutoEventSelectors.Add(); + options.AutoEventSelectors.Add(); + }); - var identityBuilder = context.Services.AddAbpIdentity(options => - { - options.User.RequireUniqueEmail = true; - }); + var identityBuilder = context.Services.AddAbpIdentity(options => + { + options.User.RequireUniqueEmail = true; + }); - context.Services.AddObjectAccessor(identityBuilder); - context.Services.ExecutePreConfiguredActions(identityBuilder); + context.Services.AddObjectAccessor(identityBuilder); + context.Services.ExecutePreConfiguredActions(identityBuilder); - Configure(options => - { - options.ClaimsIdentity.UserIdClaimType = AbpClaimTypes.UserId; - options.ClaimsIdentity.UserNameClaimType = AbpClaimTypes.UserName; - options.ClaimsIdentity.RoleClaimType = AbpClaimTypes.Role; - }); + Configure(options => + { + options.ClaimsIdentity.UserIdClaimType = AbpClaimTypes.UserId; + options.ClaimsIdentity.UserNameClaimType = AbpClaimTypes.UserName; + options.ClaimsIdentity.RoleClaimType = AbpClaimTypes.Role; + }); - context.Services.AddAbpDynamicOptions(); - } + context.Services.AddAbpDynamicOptions(); + } - public override void PostConfigureServices(ServiceConfigurationContext context) + public override void PostConfigureServices(ServiceConfigurationContext context) + { + OneTimeRunner.Run(() => { - OneTimeRunner.Run(() => - { - ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( - IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.User, - typeof(IdentityUser) - ); + ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( + IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.User, + typeof(IdentityUser) + ); - ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( - IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.Role, - typeof(IdentityRole) - ); + ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( + IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.Role, + typeof(IdentityRole) + ); - ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( - IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.ClaimType, - typeof(IdentityClaimType) - ); + ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( + IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.ClaimType, + typeof(IdentityClaimType) + ); - ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( - IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.OrganizationUnit, - typeof(OrganizationUnit) - ); - }); - } + ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( + IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.OrganizationUnit, + typeof(OrganizationUnit) + ); + }); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityOptions.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityOptions.cs index 6cfaf75c0c..468a978c99 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityOptions.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityOptions.cs @@ -1,12 +1,11 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class AbpIdentityOptions { - public class AbpIdentityOptions - { - public ExternalLoginProviderDictionary ExternalLoginProviders { get; } + public ExternalLoginProviderDictionary ExternalLoginProviders { get; } - public AbpIdentityOptions() - { - ExternalLoginProviders = new ExternalLoginProviderDictionary(); - } + public AbpIdentityOptions() + { + ExternalLoginProviders = new ExternalLoginProviderDictionary(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityOptionsManager.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityOptionsManager.cs index 8ff4c141eb..734aaf03d2 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityOptionsManager.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityOptionsManager.cs @@ -6,34 +6,33 @@ using Volo.Abp.Identity.Settings; using Volo.Abp.Options; using Volo.Abp.Settings; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class AbpIdentityOptionsManager : AbpDynamicOptionsManager { - public class AbpIdentityOptionsManager : AbpDynamicOptionsManager - { - protected ISettingProvider SettingProvider { get; } + protected ISettingProvider SettingProvider { get; } - public AbpIdentityOptionsManager(IOptionsFactory factory, - ISettingProvider settingProvider) - : base(factory) - { - SettingProvider = settingProvider; - } + public AbpIdentityOptionsManager(IOptionsFactory factory, + ISettingProvider settingProvider) + : base(factory) + { + SettingProvider = settingProvider; + } - protected override async Task OverrideOptionsAsync(string name, IdentityOptions options) - { - options.Password.RequiredLength = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequiredLength, options.Password.RequiredLength); - options.Password.RequiredUniqueChars = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequiredUniqueChars, options.Password.RequiredUniqueChars); - options.Password.RequireNonAlphanumeric = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequireNonAlphanumeric, options.Password.RequireNonAlphanumeric); - options.Password.RequireLowercase = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequireLowercase, options.Password.RequireLowercase); - options.Password.RequireUppercase = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequireUppercase, options.Password.RequireUppercase); - options.Password.RequireDigit = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequireDigit, options.Password.RequireDigit); + protected override async Task OverrideOptionsAsync(string name, IdentityOptions options) + { + options.Password.RequiredLength = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequiredLength, options.Password.RequiredLength); + options.Password.RequiredUniqueChars = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequiredUniqueChars, options.Password.RequiredUniqueChars); + options.Password.RequireNonAlphanumeric = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequireNonAlphanumeric, options.Password.RequireNonAlphanumeric); + options.Password.RequireLowercase = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequireLowercase, options.Password.RequireLowercase); + options.Password.RequireUppercase = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequireUppercase, options.Password.RequireUppercase); + options.Password.RequireDigit = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequireDigit, options.Password.RequireDigit); - options.Lockout.AllowedForNewUsers = await SettingProvider.GetAsync(IdentitySettingNames.Lockout.AllowedForNewUsers, options.Lockout.AllowedForNewUsers); - options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(await SettingProvider.GetAsync(IdentitySettingNames.Lockout.LockoutDuration, options.Lockout.DefaultLockoutTimeSpan.TotalSeconds.To())); - options.Lockout.MaxFailedAccessAttempts = await SettingProvider.GetAsync(IdentitySettingNames.Lockout.MaxFailedAccessAttempts, options.Lockout.MaxFailedAccessAttempts); + options.Lockout.AllowedForNewUsers = await SettingProvider.GetAsync(IdentitySettingNames.Lockout.AllowedForNewUsers, options.Lockout.AllowedForNewUsers); + options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(await SettingProvider.GetAsync(IdentitySettingNames.Lockout.LockoutDuration, options.Lockout.DefaultLockoutTimeSpan.TotalSeconds.To())); + options.Lockout.MaxFailedAccessAttempts = await SettingProvider.GetAsync(IdentitySettingNames.Lockout.MaxFailedAccessAttempts, options.Lockout.MaxFailedAccessAttempts); - options.SignIn.RequireConfirmedEmail = await SettingProvider.GetAsync(IdentitySettingNames.SignIn.RequireConfirmedEmail, options.SignIn.RequireConfirmedEmail); - options.SignIn.RequireConfirmedPhoneNumber = await SettingProvider.GetAsync(IdentitySettingNames.SignIn.RequireConfirmedPhoneNumber, options.SignIn.RequireConfirmedPhoneNumber); - } + options.SignIn.RequireConfirmedEmail = await SettingProvider.GetAsync(IdentitySettingNames.SignIn.RequireConfirmedEmail, options.SignIn.RequireConfirmedEmail); + options.SignIn.RequireConfirmedPhoneNumber = await SettingProvider.GetAsync(IdentitySettingNames.SignIn.RequireConfirmedPhoneNumber, options.SignIn.RequireConfirmedPhoneNumber); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityResultException.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityResultException.cs index 05ea00bc58..458f420411 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityResultException.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityResultException.cs @@ -9,44 +9,43 @@ using Volo.Abp.ExceptionHandling; using Volo.Abp.Identity.Localization; using Volo.Abp.Localization; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[Serializable] +public class AbpIdentityResultException : BusinessException, ILocalizeErrorMessage { - [Serializable] - public class AbpIdentityResultException : BusinessException, ILocalizeErrorMessage + public IdentityResult IdentityResult { get; } + + public AbpIdentityResultException([NotNull] IdentityResult identityResult) + : base( + code: $"Volo.Abp.Identity:{identityResult.Errors.First().Code}", + message: identityResult.Errors.Select(err => err.Description).JoinAsString(", ")) { - public IdentityResult IdentityResult { get; } + IdentityResult = Check.NotNull(identityResult, nameof(identityResult)); + } - public AbpIdentityResultException([NotNull] IdentityResult identityResult) - : base( - code: $"Volo.Abp.Identity:{identityResult.Errors.First().Code}", - message: identityResult.Errors.Select(err => err.Description).JoinAsString(", ")) - { - IdentityResult = Check.NotNull(identityResult, nameof(identityResult)); - } + public AbpIdentityResultException(SerializationInfo serializationInfo, StreamingContext context) + : base(serializationInfo, context) + { - public AbpIdentityResultException(SerializationInfo serializationInfo, StreamingContext context) - : base(serializationInfo, context) - { + } - } + public virtual string LocalizeMessage(LocalizationContext context) + { + var localizer = context.LocalizerFactory.Create(); - public virtual string LocalizeMessage(LocalizationContext context) - { - var localizer = context.LocalizerFactory.Create(); + SetData(localizer); - SetData(localizer); + return IdentityResult.LocalizeErrors(localizer); + } - return IdentityResult.LocalizeErrors(localizer); - } + protected virtual void SetData(IStringLocalizer localizer) + { + var values = IdentityResult.GetValuesFromErrorMessage(localizer); - protected virtual void SetData(IStringLocalizer localizer) + for (var index = 0; index < values.Length; index++) { - var values = IdentityResult.GetValuesFromErrorMessage(localizer); - - for (var index = 0; index < values.Length; index++) - { - Data[index.ToString()] = values[index]; - } + Data[index.ToString()] = values[index]; } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentitySettingDefinitionProvider.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentitySettingDefinitionProvider.cs index bc1ca00b25..79b4afaa05 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentitySettingDefinitionProvider.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentitySettingDefinitionProvider.cs @@ -3,121 +3,120 @@ using Volo.Abp.Identity.Settings; using Volo.Abp.Localization; using Volo.Abp.Settings; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class AbpIdentitySettingDefinitionProvider : SettingDefinitionProvider { - public class AbpIdentitySettingDefinitionProvider : SettingDefinitionProvider + public override void Define(ISettingDefinitionContext context) { - public override void Define(ISettingDefinitionContext context) - { - context.Add( - new SettingDefinition( - IdentitySettingNames.Password.RequiredLength, - 6.ToString(), - L("DisplayName:Abp.Identity.Password.RequiredLength"), - L("Description:Abp.Identity.Password.RequiredLength"), - true), + context.Add( + new SettingDefinition( + IdentitySettingNames.Password.RequiredLength, + 6.ToString(), + L("DisplayName:Abp.Identity.Password.RequiredLength"), + L("Description:Abp.Identity.Password.RequiredLength"), + true), - new SettingDefinition( - IdentitySettingNames.Password.RequiredUniqueChars, - 1.ToString(), - L("DisplayName:Abp.Identity.Password.RequiredUniqueChars"), - L("Description:Abp.Identity.Password.RequiredUniqueChars"), - true), + new SettingDefinition( + IdentitySettingNames.Password.RequiredUniqueChars, + 1.ToString(), + L("DisplayName:Abp.Identity.Password.RequiredUniqueChars"), + L("Description:Abp.Identity.Password.RequiredUniqueChars"), + true), - new SettingDefinition( - IdentitySettingNames.Password.RequireNonAlphanumeric, - true.ToString(), - L("DisplayName:Abp.Identity.Password.RequireNonAlphanumeric"), - L("Description:Abp.Identity.Password.RequireNonAlphanumeric"), - true), + new SettingDefinition( + IdentitySettingNames.Password.RequireNonAlphanumeric, + true.ToString(), + L("DisplayName:Abp.Identity.Password.RequireNonAlphanumeric"), + L("Description:Abp.Identity.Password.RequireNonAlphanumeric"), + true), - new SettingDefinition( - IdentitySettingNames.Password.RequireLowercase, - true.ToString(), - L("DisplayName:Abp.Identity.Password.RequireLowercase"), - L("Description:Abp.Identity.Password.RequireLowercase"), - true), + new SettingDefinition( + IdentitySettingNames.Password.RequireLowercase, + true.ToString(), + L("DisplayName:Abp.Identity.Password.RequireLowercase"), + L("Description:Abp.Identity.Password.RequireLowercase"), + true), - new SettingDefinition( - IdentitySettingNames.Password.RequireUppercase, - true.ToString(), - L("DisplayName:Abp.Identity.Password.RequireUppercase"), - L("Description:Abp.Identity.Password.RequireUppercase"), - true), + new SettingDefinition( + IdentitySettingNames.Password.RequireUppercase, + true.ToString(), + L("DisplayName:Abp.Identity.Password.RequireUppercase"), + L("Description:Abp.Identity.Password.RequireUppercase"), + true), - new SettingDefinition( - IdentitySettingNames.Password.RequireDigit, - true.ToString(), - L("DisplayName:Abp.Identity.Password.RequireDigit"), - L("Description:Abp.Identity.Password.RequireDigit"), - true), + new SettingDefinition( + IdentitySettingNames.Password.RequireDigit, + true.ToString(), + L("DisplayName:Abp.Identity.Password.RequireDigit"), + L("Description:Abp.Identity.Password.RequireDigit"), + true), - new SettingDefinition( - IdentitySettingNames.Lockout.AllowedForNewUsers, - true.ToString(), - L("DisplayName:Abp.Identity.Lockout.AllowedForNewUsers"), - L("Description:Abp.Identity.Lockout.AllowedForNewUsers"), - true), + new SettingDefinition( + IdentitySettingNames.Lockout.AllowedForNewUsers, + true.ToString(), + L("DisplayName:Abp.Identity.Lockout.AllowedForNewUsers"), + L("Description:Abp.Identity.Lockout.AllowedForNewUsers"), + true), - new SettingDefinition( - IdentitySettingNames.Lockout.LockoutDuration, - (5 * 60).ToString(), - L("DisplayName:Abp.Identity.Lockout.LockoutDuration"), - L("Description:Abp.Identity.Lockout.LockoutDuration"), - true), + new SettingDefinition( + IdentitySettingNames.Lockout.LockoutDuration, + (5 * 60).ToString(), + L("DisplayName:Abp.Identity.Lockout.LockoutDuration"), + L("Description:Abp.Identity.Lockout.LockoutDuration"), + true), - new SettingDefinition( - IdentitySettingNames.Lockout.MaxFailedAccessAttempts, - 5.ToString(), - L("DisplayName:Abp.Identity.Lockout.MaxFailedAccessAttempts"), - L("Description:Abp.Identity.Lockout.MaxFailedAccessAttempts"), - true), + new SettingDefinition( + IdentitySettingNames.Lockout.MaxFailedAccessAttempts, + 5.ToString(), + L("DisplayName:Abp.Identity.Lockout.MaxFailedAccessAttempts"), + L("Description:Abp.Identity.Lockout.MaxFailedAccessAttempts"), + true), - new SettingDefinition( - IdentitySettingNames.SignIn.RequireConfirmedEmail, - false.ToString(), - L("DisplayName:Abp.Identity.SignIn.RequireConfirmedEmail"), - L("Description:Abp.Identity.SignIn.RequireConfirmedEmail"), - true), - new SettingDefinition( - IdentitySettingNames.SignIn.EnablePhoneNumberConfirmation, - true.ToString(), - L("DisplayName:Abp.Identity.SignIn.EnablePhoneNumberConfirmation"), - L("Description:Abp.Identity.SignIn.EnablePhoneNumberConfirmation"), - true), - new SettingDefinition( - IdentitySettingNames.SignIn.RequireConfirmedPhoneNumber, - false.ToString(), - L("DisplayName:Abp.Identity.SignIn.RequireConfirmedPhoneNumber"), - L("Description:Abp.Identity.SignIn.RequireConfirmedPhoneNumber"), - true), + new SettingDefinition( + IdentitySettingNames.SignIn.RequireConfirmedEmail, + false.ToString(), + L("DisplayName:Abp.Identity.SignIn.RequireConfirmedEmail"), + L("Description:Abp.Identity.SignIn.RequireConfirmedEmail"), + true), + new SettingDefinition( + IdentitySettingNames.SignIn.EnablePhoneNumberConfirmation, + true.ToString(), + L("DisplayName:Abp.Identity.SignIn.EnablePhoneNumberConfirmation"), + L("Description:Abp.Identity.SignIn.EnablePhoneNumberConfirmation"), + true), + new SettingDefinition( + IdentitySettingNames.SignIn.RequireConfirmedPhoneNumber, + false.ToString(), + L("DisplayName:Abp.Identity.SignIn.RequireConfirmedPhoneNumber"), + L("Description:Abp.Identity.SignIn.RequireConfirmedPhoneNumber"), + true), - new SettingDefinition( - IdentitySettingNames.User.IsUserNameUpdateEnabled, - true.ToString(), - L("DisplayName:Abp.Identity.User.IsUserNameUpdateEnabled"), - L("Description:Abp.Identity.User.IsUserNameUpdateEnabled"), - true), + new SettingDefinition( + IdentitySettingNames.User.IsUserNameUpdateEnabled, + true.ToString(), + L("DisplayName:Abp.Identity.User.IsUserNameUpdateEnabled"), + L("Description:Abp.Identity.User.IsUserNameUpdateEnabled"), + true), - new SettingDefinition( - IdentitySettingNames.User.IsEmailUpdateEnabled, - true.ToString(), - L("DisplayName:Abp.Identity.User.IsEmailUpdateEnabled"), - L("Description:Abp.Identity.User.IsEmailUpdateEnabled"), - true), + new SettingDefinition( + IdentitySettingNames.User.IsEmailUpdateEnabled, + true.ToString(), + L("DisplayName:Abp.Identity.User.IsEmailUpdateEnabled"), + L("Description:Abp.Identity.User.IsEmailUpdateEnabled"), + true), - new SettingDefinition( - IdentitySettingNames.OrganizationUnit.MaxUserMembershipCount, - int.MaxValue.ToString(), - L("Identity.OrganizationUnit.MaxUserMembershipCount"), - L("Identity.OrganizationUnit.MaxUserMembershipCount"), - true) - ); - } + new SettingDefinition( + IdentitySettingNames.OrganizationUnit.MaxUserMembershipCount, + int.MaxValue.ToString(), + L("Identity.OrganizationUnit.MaxUserMembershipCount"), + L("Identity.OrganizationUnit.MaxUserMembershipCount"), + true) + ); + } - private static LocalizableString L(string name) - { - return LocalizableString.Create(name); - } + private static LocalizableString L(string name) + { + return LocalizableString.Create(name); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpUserClaimsPrincipalFactory.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpUserClaimsPrincipalFactory.cs index 16369e8285..d6043a1624 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpUserClaimsPrincipalFactory.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpUserClaimsPrincipalFactory.cs @@ -9,71 +9,70 @@ using Volo.Abp.DependencyInjection; using Volo.Abp.Security.Claims; using Volo.Abp.Uow; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class AbpUserClaimsPrincipalFactory : UserClaimsPrincipalFactory, + ITransientDependency { - public class AbpUserClaimsPrincipalFactory : UserClaimsPrincipalFactory, - ITransientDependency + protected ICurrentPrincipalAccessor CurrentPrincipalAccessor { get; } + protected IAbpClaimsPrincipalFactory AbpClaimsPrincipalFactory { get; } + + public AbpUserClaimsPrincipalFactory( + UserManager userManager, + RoleManager roleManager, + IOptions options, + ICurrentPrincipalAccessor currentPrincipalAccessor, + IAbpClaimsPrincipalFactory abpClaimsPrincipalFactory) + : base( + userManager, + roleManager, + options) + { + CurrentPrincipalAccessor = currentPrincipalAccessor; + AbpClaimsPrincipalFactory = abpClaimsPrincipalFactory; + } + + [UnitOfWork] + public override async Task CreateAsync(IdentityUser user) { - protected ICurrentPrincipalAccessor CurrentPrincipalAccessor { get; } - protected IAbpClaimsPrincipalFactory AbpClaimsPrincipalFactory { get; } + var principal = await base.CreateAsync(user); + var identity = principal.Identities.First(); - public AbpUserClaimsPrincipalFactory( - UserManager userManager, - RoleManager roleManager, - IOptions options, - ICurrentPrincipalAccessor currentPrincipalAccessor, - IAbpClaimsPrincipalFactory abpClaimsPrincipalFactory) - : base( - userManager, - roleManager, - options) + if (user.TenantId.HasValue) { - CurrentPrincipalAccessor = currentPrincipalAccessor; - AbpClaimsPrincipalFactory = abpClaimsPrincipalFactory; + identity.AddIfNotContains(new Claim(AbpClaimTypes.TenantId, user.TenantId.ToString())); } - [UnitOfWork] - public override async Task CreateAsync(IdentityUser user) + if (!user.Name.IsNullOrWhiteSpace()) { - var principal = await base.CreateAsync(user); - var identity = principal.Identities.First(); - - if (user.TenantId.HasValue) - { - identity.AddIfNotContains(new Claim(AbpClaimTypes.TenantId, user.TenantId.ToString())); - } - - if (!user.Name.IsNullOrWhiteSpace()) - { - identity.AddIfNotContains(new Claim(AbpClaimTypes.Name, user.Name)); - } - - if (!user.Surname.IsNullOrWhiteSpace()) - { - identity.AddIfNotContains(new Claim(AbpClaimTypes.SurName, user.Surname)); - } + identity.AddIfNotContains(new Claim(AbpClaimTypes.Name, user.Name)); + } - if (!user.PhoneNumber.IsNullOrWhiteSpace()) - { - identity.AddIfNotContains(new Claim(AbpClaimTypes.PhoneNumber, user.PhoneNumber)); - } + if (!user.Surname.IsNullOrWhiteSpace()) + { + identity.AddIfNotContains(new Claim(AbpClaimTypes.SurName, user.Surname)); + } - identity.AddIfNotContains( - new Claim(AbpClaimTypes.PhoneNumberVerified, user.PhoneNumberConfirmed.ToString())); + if (!user.PhoneNumber.IsNullOrWhiteSpace()) + { + identity.AddIfNotContains(new Claim(AbpClaimTypes.PhoneNumber, user.PhoneNumber)); + } - if (!user.Email.IsNullOrWhiteSpace()) - { - identity.AddIfNotContains(new Claim(AbpClaimTypes.Email, user.Email)); - } + identity.AddIfNotContains( + new Claim(AbpClaimTypes.PhoneNumberVerified, user.PhoneNumberConfirmed.ToString())); - identity.AddIfNotContains(new Claim(AbpClaimTypes.EmailVerified, user.EmailConfirmed.ToString())); + if (!user.Email.IsNullOrWhiteSpace()) + { + identity.AddIfNotContains(new Claim(AbpClaimTypes.Email, user.Email)); + } - using (CurrentPrincipalAccessor.Change(identity)) - { - await AbpClaimsPrincipalFactory.CreateAsync(principal); - } + identity.AddIfNotContains(new Claim(AbpClaimTypes.EmailVerified, user.EmailConfirmed.ToString())); - return principal; + using (CurrentPrincipalAccessor.Change(identity)) + { + await AbpClaimsPrincipalFactory.CreateAsync(principal); } + + return principal; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderBase.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderBase.cs index 307fb1e72b..d129ba917e 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderBase.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderBase.cs @@ -7,158 +7,157 @@ using Volo.Abp.Domain.Repositories; using Volo.Abp.Guids; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class ExternalLoginProviderBase : IExternalLoginProvider { - public abstract class ExternalLoginProviderBase : IExternalLoginProvider + protected IGuidGenerator GuidGenerator { get; } + protected ICurrentTenant CurrentTenant { get; } + protected IdentityUserManager UserManager { get; } + protected IIdentityUserRepository IdentityUserRepository { get; } + protected IOptions IdentityOptions { get; } + + protected ExternalLoginProviderBase( + IGuidGenerator guidGenerator, + ICurrentTenant currentTenant, + IdentityUserManager userManager, + IIdentityUserRepository identityUserRepository, + IOptions identityOptions) { - protected IGuidGenerator GuidGenerator { get; } - protected ICurrentTenant CurrentTenant { get; } - protected IdentityUserManager UserManager { get; } - protected IIdentityUserRepository IdentityUserRepository { get; } - protected IOptions IdentityOptions { get; } - - protected ExternalLoginProviderBase( - IGuidGenerator guidGenerator, - ICurrentTenant currentTenant, - IdentityUserManager userManager, - IIdentityUserRepository identityUserRepository, - IOptions identityOptions) - { - GuidGenerator = guidGenerator; - CurrentTenant = currentTenant; - UserManager = userManager; - IdentityUserRepository = identityUserRepository; - IdentityOptions = identityOptions; - } + GuidGenerator = guidGenerator; + CurrentTenant = currentTenant; + UserManager = userManager; + IdentityUserRepository = identityUserRepository; + IdentityOptions = identityOptions; + } - public abstract Task TryAuthenticateAsync(string userName, string plainPassword); + public abstract Task TryAuthenticateAsync(string userName, string plainPassword); - public virtual async Task CreateUserAsync(string userName, string providerName) - { - await IdentityOptions.SetAsync(); + public virtual async Task CreateUserAsync(string userName, string providerName) + { + await IdentityOptions.SetAsync(); - var externalUser = await GetUserInfoAsync(userName); - NormalizeExternalLoginUserInfo(externalUser, userName); + var externalUser = await GetUserInfoAsync(userName); + NormalizeExternalLoginUserInfo(externalUser, userName); - var user = new IdentityUser( - GuidGenerator.Create(), - userName, - externalUser.Email, - tenantId: CurrentTenant.Id - ); + var user = new IdentityUser( + GuidGenerator.Create(), + userName, + externalUser.Email, + tenantId: CurrentTenant.Id + ); - user.Name = externalUser.Name; - user.Surname = externalUser.Surname; + user.Name = externalUser.Name; + user.Surname = externalUser.Surname; - user.IsExternal = true; + user.IsExternal = true; - user.SetEmailConfirmed(externalUser.EmailConfirmed ?? false); - user.SetPhoneNumber(externalUser.PhoneNumber, externalUser.PhoneNumberConfirmed ?? false); + user.SetEmailConfirmed(externalUser.EmailConfirmed ?? false); + user.SetPhoneNumber(externalUser.PhoneNumber, externalUser.PhoneNumberConfirmed ?? false); - (await UserManager.CreateAsync(user)).CheckErrors(); + (await UserManager.CreateAsync(user)).CheckErrors(); - if (externalUser.TwoFactorEnabled != null) - { - (await UserManager.SetTwoFactorEnabledAsync(user, externalUser.TwoFactorEnabled.Value)).CheckErrors(); - } + if (externalUser.TwoFactorEnabled != null) + { + (await UserManager.SetTwoFactorEnabledAsync(user, externalUser.TwoFactorEnabled.Value)).CheckErrors(); + } - (await UserManager.AddDefaultRolesAsync(user)).CheckErrors(); - (await UserManager.AddLoginAsync( - user, - new UserLoginInfo( - providerName, - externalUser.ProviderKey , - providerName - ) + (await UserManager.AddDefaultRolesAsync(user)).CheckErrors(); + (await UserManager.AddLoginAsync( + user, + new UserLoginInfo( + providerName, + externalUser.ProviderKey, + providerName ) - ).CheckErrors(); + ) + ).CheckErrors(); - return user; - } + return user; + } - public virtual async Task UpdateUserAsync(IdentityUser user, string providerName) - { - await IdentityOptions.SetAsync(); + public virtual async Task UpdateUserAsync(IdentityUser user, string providerName) + { + await IdentityOptions.SetAsync(); - var externalUser = await GetUserInfoAsync(user); - NormalizeExternalLoginUserInfo(externalUser, user.UserName); + var externalUser = await GetUserInfoAsync(user); + NormalizeExternalLoginUserInfo(externalUser, user.UserName); - if (!externalUser.Name.IsNullOrWhiteSpace()) - { - user.Name = externalUser.Name; - } + if (!externalUser.Name.IsNullOrWhiteSpace()) + { + user.Name = externalUser.Name; + } - if (!externalUser.Surname.IsNullOrWhiteSpace()) - { - user.Surname = externalUser.Surname; - } + if (!externalUser.Surname.IsNullOrWhiteSpace()) + { + user.Surname = externalUser.Surname; + } - if (user.PhoneNumber != externalUser.PhoneNumber) + if (user.PhoneNumber != externalUser.PhoneNumber) + { + if (!externalUser.PhoneNumber.IsNullOrWhiteSpace()) { - if (!externalUser.PhoneNumber.IsNullOrWhiteSpace()) - { - await UserManager.SetPhoneNumberAsync(user, externalUser.PhoneNumber); - user.SetPhoneNumberConfirmed(externalUser.PhoneNumberConfirmed == true); - } + await UserManager.SetPhoneNumberAsync(user, externalUser.PhoneNumber); + user.SetPhoneNumberConfirmed(externalUser.PhoneNumberConfirmed == true); } - else + } + else + { + if (!user.PhoneNumber.IsNullOrWhiteSpace() && + user.PhoneNumberConfirmed == false && + externalUser.PhoneNumberConfirmed == true) { - if (!user.PhoneNumber.IsNullOrWhiteSpace() && - user.PhoneNumberConfirmed == false && - externalUser.PhoneNumberConfirmed == true) - { - user.SetPhoneNumberConfirmed(true); - } + user.SetPhoneNumberConfirmed(true); } + } - if (!string.Equals(user.Email, externalUser.Email, StringComparison.OrdinalIgnoreCase)) - { - (await UserManager.SetEmailAsync(user, externalUser.Email)).CheckErrors(); - user.SetEmailConfirmed(externalUser.EmailConfirmed ?? false); - } + if (!string.Equals(user.Email, externalUser.Email, StringComparison.OrdinalIgnoreCase)) + { + (await UserManager.SetEmailAsync(user, externalUser.Email)).CheckErrors(); + user.SetEmailConfirmed(externalUser.EmailConfirmed ?? false); + } - if (externalUser.TwoFactorEnabled != null) - { - (await UserManager.SetTwoFactorEnabledAsync(user, externalUser.TwoFactorEnabled.Value)).CheckErrors(); - } + if (externalUser.TwoFactorEnabled != null) + { + (await UserManager.SetTwoFactorEnabledAsync(user, externalUser.TwoFactorEnabled.Value)).CheckErrors(); + } - await IdentityUserRepository.EnsureCollectionLoadedAsync(user, u => u.Logins); + await IdentityUserRepository.EnsureCollectionLoadedAsync(user, u => u.Logins); - var userLogin = user.Logins.FirstOrDefault(l => l.LoginProvider == providerName); - if (userLogin != null) - { - if (userLogin.ProviderKey != externalUser.ProviderKey) - { - (await UserManager.RemoveLoginAsync(user, providerName, userLogin.ProviderKey)).CheckErrors(); - (await UserManager.AddLoginAsync(user, new UserLoginInfo(providerName, externalUser.ProviderKey, providerName))).CheckErrors(); - } - } - else + var userLogin = user.Logins.FirstOrDefault(l => l.LoginProvider == providerName); + if (userLogin != null) + { + if (userLogin.ProviderKey != externalUser.ProviderKey) { + (await UserManager.RemoveLoginAsync(user, providerName, userLogin.ProviderKey)).CheckErrors(); (await UserManager.AddLoginAsync(user, new UserLoginInfo(providerName, externalUser.ProviderKey, providerName))).CheckErrors(); } + } + else + { + (await UserManager.AddLoginAsync(user, new UserLoginInfo(providerName, externalUser.ProviderKey, providerName))).CheckErrors(); + } - user.IsExternal = true; + user.IsExternal = true; - (await UserManager.UpdateAsync(user)).CheckErrors(); - } + (await UserManager.UpdateAsync(user)).CheckErrors(); + } - protected abstract Task GetUserInfoAsync(string userName); + protected abstract Task GetUserInfoAsync(string userName); - protected virtual Task GetUserInfoAsync(IdentityUser user) - { - return GetUserInfoAsync(user.UserName); - } + protected virtual Task GetUserInfoAsync(IdentityUser user) + { + return GetUserInfoAsync(user.UserName); + } - private static void NormalizeExternalLoginUserInfo( - ExternalLoginUserInfo externalUser, - string userName - ) + private static void NormalizeExternalLoginUserInfo( + ExternalLoginUserInfo externalUser, + string userName + ) + { + if (externalUser.ProviderKey.IsNullOrWhiteSpace()) { - if (externalUser.ProviderKey.IsNullOrWhiteSpace()) - { - externalUser.ProviderKey = userName; - } + externalUser.ProviderKey = userName; } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderDictionary.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderDictionary.cs index 822971efb0..4b8317d756 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderDictionary.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderDictionary.cs @@ -1,17 +1,16 @@ using System.Collections.Generic; using JetBrains.Annotations; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class ExternalLoginProviderDictionary : Dictionary { - public class ExternalLoginProviderDictionary : Dictionary + /// + /// Adds or replaces a provider. + /// + public void Add([NotNull] string name) + where TProvider : IExternalLoginProvider { - /// - /// Adds or replaces a provider. - /// - public void Add([NotNull] string name) - where TProvider : IExternalLoginProvider - { - this[name] = new ExternalLoginProviderInfo(name, typeof(TProvider)); - } + this[name] = new ExternalLoginProviderInfo(name, typeof(TProvider)); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderInfo.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderInfo.cs index 4d1989d5dc..d2b79cb119 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderInfo.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderInfo.cs @@ -1,25 +1,23 @@ using System; using JetBrains.Annotations; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class ExternalLoginProviderInfo { - public class ExternalLoginProviderInfo - { - public string Name { get; } + public string Name { get; } - public Type Type - { - get => _type; - set => _type = Check.NotNull(value, nameof(value)); - } - private Type _type; + public Type Type { + get => _type; + set => _type = Check.NotNull(value, nameof(value)); + } + private Type _type; - public ExternalLoginProviderInfo( - [NotNull] string name, - [NotNull] Type type) - { - Name = Check.NotNullOrWhiteSpace(name, nameof(name)); - Type = Check.AssignableTo(type, nameof(type)); - } + public ExternalLoginProviderInfo( + [NotNull] string name, + [NotNull] Type type) + { + Name = Check.NotNullOrWhiteSpace(name, nameof(name)); + Type = Check.AssignableTo(type, nameof(type)); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginUserInfo.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginUserInfo.cs index 65e4a2c776..0736089873 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginUserInfo.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginUserInfo.cs @@ -1,36 +1,35 @@ using JetBrains.Annotations; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class ExternalLoginUserInfo { - public class ExternalLoginUserInfo - { - [CanBeNull] - public string Name { get; set; } + [CanBeNull] + public string Name { get; set; } - [CanBeNull] - public string Surname { get; set; } + [CanBeNull] + public string Surname { get; set; } - [CanBeNull] - public string PhoneNumber { get; set; } + [CanBeNull] + public string PhoneNumber { get; set; } - [NotNull] - public string Email { get; private set; } + [NotNull] + public string Email { get; private set; } - [CanBeNull] - public bool? PhoneNumberConfirmed { get; set; } + [CanBeNull] + public bool? PhoneNumberConfirmed { get; set; } - [CanBeNull] - public bool? EmailConfirmed { get; set; } + [CanBeNull] + public bool? EmailConfirmed { get; set; } - [CanBeNull] - public bool? TwoFactorEnabled { get; set; } + [CanBeNull] + public bool? TwoFactorEnabled { get; set; } - [CanBeNull] - public string ProviderKey { get; set; } + [CanBeNull] + public string ProviderKey { get; set; } - public ExternalLoginUserInfo([NotNull] string email) - { - Email = Check.NotNullOrWhiteSpace(email, nameof(email)); - } + public ExternalLoginUserInfo([NotNull] string email) + { + Email = Check.NotNullOrWhiteSpace(email, nameof(email)); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IExternalLoginProvider.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IExternalLoginProvider.cs index 79e730d901..56d6c643fb 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IExternalLoginProvider.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IExternalLoginProvider.cs @@ -1,32 +1,31 @@ using System.Threading.Tasks; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IExternalLoginProvider { - public interface IExternalLoginProvider - { - /// - /// Used to try authenticate a user by this source. - /// - /// User name or email address - /// Plain password of the user - /// True, indicates that this used has authenticated by this source - Task TryAuthenticateAsync(string userName, string plainPassword); + /// + /// Used to try authenticate a user by this source. + /// + /// User name or email address + /// Plain password of the user + /// True, indicates that this used has authenticated by this source + Task TryAuthenticateAsync(string userName, string plainPassword); - /// - /// This method is called when a user is authenticated by this source but the user does not exists yet. - /// So, the source should create the user and fill the properties. - /// - /// User name - /// The name of this provider - /// Newly created user - Task CreateUserAsync(string userName, string providerName); + /// + /// This method is called when a user is authenticated by this source but the user does not exists yet. + /// So, the source should create the user and fill the properties. + /// + /// User name + /// The name of this provider + /// Newly created user + Task CreateUserAsync(string userName, string providerName); - /// - /// This method is called after an existing user is authenticated by this source. - /// It can be used to update some properties of the user by the source. - /// - /// The name of this provider - /// The user that can be updated - Task UpdateUserAsync(IdentityUser user, string providerName); - } + /// + /// This method is called after an existing user is authenticated by this source. + /// It can be used to update some properties of the user by the source. + /// + /// The name of this provider + /// The user that can be updated + Task UpdateUserAsync(IdentityUser user, string providerName); } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIDentityClaimTypeRepository.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIDentityClaimTypeRepository.cs index 0b803760fb..398bc618c7 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIDentityClaimTypeRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIDentityClaimTypeRepository.cs @@ -4,36 +4,35 @@ using System.Threading; using System.Threading.Tasks; using Volo.Abp.Domain.Repositories; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IIdentityClaimTypeRepository : IBasicRepository { - public interface IIdentityClaimTypeRepository : IBasicRepository - { - /// - /// Checks if there is a entity with given name. - /// - /// Name to check - /// - /// An Id value to ignore on checking. - /// If there is an entity with given it's ignored. - /// - /// Cancel token - Task AnyAsync( - string name, - Guid? ignoredId = null, - CancellationToken cancellationToken = default - ); + /// + /// Checks if there is a entity with given name. + /// + /// Name to check + /// + /// An Id value to ignore on checking. + /// If there is an entity with given it's ignored. + /// + /// Cancel token + Task AnyAsync( + string name, + Guid? ignoredId = null, + CancellationToken cancellationToken = default + ); - Task> GetListAsync( - string sorting, - int maxResultCount, - int skipCount, - string filter, - CancellationToken cancellationToken = default - ); + Task> GetListAsync( + string sorting, + int maxResultCount, + int skipCount, + string filter, + CancellationToken cancellationToken = default + ); - Task GetCountAsync( - string filter = null, - CancellationToken cancellationToken = default - ); - } -} \ No newline at end of file + Task GetCountAsync( + string filter = null, + CancellationToken cancellationToken = default + ); +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityDataSeeder.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityDataSeeder.cs index 16e00c55d6..dffe51120a 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityDataSeeder.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityDataSeeder.cs @@ -2,13 +2,12 @@ using System.Threading.Tasks; using JetBrains.Annotations; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IIdentityDataSeeder { - public interface IIdentityDataSeeder - { - Task SeedAsync( - [NotNull] string adminEmail, - [NotNull] string adminPassword, - Guid? tenantId = null); - } -} \ No newline at end of file + Task SeedAsync( + [NotNull] string adminEmail, + [NotNull] string adminPassword, + Guid? tenantId = null); +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityLinkUserRepository.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityLinkUserRepository.cs index 9e86d4b34b..fb96806b9b 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityLinkUserRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityLinkUserRepository.cs @@ -4,22 +4,21 @@ using System.Threading; using System.Threading.Tasks; using Volo.Abp.Domain.Repositories; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IIdentityLinkUserRepository : IBasicRepository { - public interface IIdentityLinkUserRepository : IBasicRepository - { - Task FindAsync( - IdentityLinkUserInfo sourceLinkUserInfo, - IdentityLinkUserInfo targetLinkUserInfo, - CancellationToken cancellationToken = default); + Task FindAsync( + IdentityLinkUserInfo sourceLinkUserInfo, + IdentityLinkUserInfo targetLinkUserInfo, + CancellationToken cancellationToken = default); - Task> GetListAsync( - IdentityLinkUserInfo linkUserInfo, - List excludes = null, - CancellationToken cancellationToken = default); + Task> GetListAsync( + IdentityLinkUserInfo linkUserInfo, + List excludes = null, + CancellationToken cancellationToken = default); - Task DeleteAsync( - IdentityLinkUserInfo linkUserInfo, - CancellationToken cancellationToken = default); - } + Task DeleteAsync( + IdentityLinkUserInfo linkUserInfo, + CancellationToken cancellationToken = default); } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityRoleRepository.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityRoleRepository.cs index e4d9ed55de..25b33936ba 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityRoleRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityRoleRepository.cs @@ -4,37 +4,36 @@ using System.Threading; using System.Threading.Tasks; using Volo.Abp.Domain.Repositories; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IIdentityRoleRepository : IBasicRepository { - public interface IIdentityRoleRepository : IBasicRepository - { - Task FindByNormalizedNameAsync( - string normalizedRoleName, - bool includeDetails = true, - CancellationToken cancellationToken = default - ); + Task FindByNormalizedNameAsync( + string normalizedRoleName, + bool includeDetails = true, + CancellationToken cancellationToken = default + ); - Task> GetListAsync( - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); - Task> GetListAsync( - IEnumerable ids, - CancellationToken cancellationToken = default - ); + Task> GetListAsync( + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); + Task> GetListAsync( + IEnumerable ids, + CancellationToken cancellationToken = default + ); - Task> GetDefaultOnesAsync( - bool includeDetails = false, - CancellationToken cancellationToken = default - ); + Task> GetDefaultOnesAsync( + bool includeDetails = false, + CancellationToken cancellationToken = default + ); - Task GetCountAsync( - string filter = null, - CancellationToken cancellationToken = default - ); - } -} \ No newline at end of file + Task GetCountAsync( + string filter = null, + CancellationToken cancellationToken = default + ); +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentitySecurityLogRepository.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentitySecurityLogRepository.cs index f68f289b4f..2ceaa8ed4c 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentitySecurityLogRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentitySecurityLogRepository.cs @@ -4,42 +4,41 @@ using System.Threading; using System.Threading.Tasks; using Volo.Abp.Domain.Repositories; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IIdentitySecurityLogRepository : IBasicRepository { - public interface IIdentitySecurityLogRepository : IBasicRepository - { - Task> GetListAsync( - string sorting = null, - int maxResultCount = 50, - int skipCount = 0, - DateTime? startTime = null, - DateTime? endTime = null, - string applicationName = null, - string identity = null, - string action = null, - Guid? userId = null, - string userName = null, - string clientId = null, - string correlationId = null, - bool includeDetails = false, - CancellationToken cancellationToken = default); + Task> GetListAsync( + string sorting = null, + int maxResultCount = 50, + int skipCount = 0, + DateTime? startTime = null, + DateTime? endTime = null, + string applicationName = null, + string identity = null, + string action = null, + Guid? userId = null, + string userName = null, + string clientId = null, + string correlationId = null, + bool includeDetails = false, + CancellationToken cancellationToken = default); - Task GetCountAsync( - DateTime? startTime = null, - DateTime? endTime = null, - string applicationName = null, - string identity = null, - string action = null, - Guid? userId = null, - string userName = null, - string clientId = null, - string correlationId = null, - CancellationToken cancellationToken = default); + Task GetCountAsync( + DateTime? startTime = null, + DateTime? endTime = null, + string applicationName = null, + string identity = null, + string action = null, + Guid? userId = null, + string userName = null, + string clientId = null, + string correlationId = null, + CancellationToken cancellationToken = default); - Task GetByUserIdAsync( - Guid id, - Guid userId, - bool includeDetails = false, - CancellationToken cancellationToken = default); - } + Task GetByUserIdAsync( + Guid id, + Guid userId, + bool includeDetails = false, + CancellationToken cancellationToken = default); } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityUserRepository.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityUserRepository.cs index 37516c05a7..164d9a1c32 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityUserRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityUserRepository.cs @@ -6,101 +6,100 @@ using System.Threading.Tasks; using JetBrains.Annotations; using Volo.Abp.Domain.Repositories; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IIdentityUserRepository : IBasicRepository { - public interface IIdentityUserRepository : IBasicRepository - { - Task FindByNormalizedUserNameAsync( - [NotNull] string normalizedUserName, - bool includeDetails = true, - CancellationToken cancellationToken = default - ); + Task FindByNormalizedUserNameAsync( + [NotNull] string normalizedUserName, + bool includeDetails = true, + CancellationToken cancellationToken = default + ); - Task> GetRoleNamesAsync( - Guid id, - CancellationToken cancellationToken = default - ); + Task> GetRoleNamesAsync( + Guid id, + CancellationToken cancellationToken = default + ); - Task> GetRoleNamesInOrganizationUnitAsync( - Guid id, - CancellationToken cancellationToken = default); + Task> GetRoleNamesInOrganizationUnitAsync( + Guid id, + CancellationToken cancellationToken = default); - Task FindByLoginAsync( - [NotNull] string loginProvider, - [NotNull] string providerKey, - bool includeDetails = true, - CancellationToken cancellationToken = default - ); + Task FindByLoginAsync( + [NotNull] string loginProvider, + [NotNull] string providerKey, + bool includeDetails = true, + CancellationToken cancellationToken = default + ); - Task FindByNormalizedEmailAsync( - [NotNull] string normalizedEmail, - bool includeDetails = true, - CancellationToken cancellationToken = default - ); + Task FindByNormalizedEmailAsync( + [NotNull] string normalizedEmail, + bool includeDetails = true, + CancellationToken cancellationToken = default + ); - Task> GetListByClaimAsync( - Claim claim, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); + Task> GetListByClaimAsync( + Claim claim, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); - Task> GetListByNormalizedRoleNameAsync( - string normalizedRoleName, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); + Task> GetListByNormalizedRoleNameAsync( + string normalizedRoleName, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); - Task> GetListAsync( - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - Guid? roleId = null, - Guid? organizationUnitId = null, - string userName = null, - string phoneNumber = null, - string emailAddress = null, - bool? isLockedOut = null, - bool? notActive = null, - CancellationToken cancellationToken = default - ); - - Task> GetRolesAsync( - Guid id, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); + Task> GetListAsync( + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + Guid? roleId = null, + Guid? organizationUnitId = null, + string userName = null, + string phoneNumber = null, + string emailAddress = null, + bool? isLockedOut = null, + bool? notActive = null, + CancellationToken cancellationToken = default + ); - Task> GetOrganizationUnitsAsync( - Guid id, - bool includeDetails = false, - CancellationToken cancellationToken = default); + Task> GetRolesAsync( + Guid id, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); - Task> GetUsersInOrganizationUnitAsync( - Guid organizationUnitId, - CancellationToken cancellationToken = default - ); - Task> GetUsersInOrganizationsListAsync( - List organizationUnitIds, - CancellationToken cancellationToken = default - ); + Task> GetOrganizationUnitsAsync( + Guid id, + bool includeDetails = false, + CancellationToken cancellationToken = default); - Task> GetUsersInOrganizationUnitWithChildrenAsync( - string code, - CancellationToken cancellationToken = default - ); + Task> GetUsersInOrganizationUnitAsync( + Guid organizationUnitId, + CancellationToken cancellationToken = default + ); + Task> GetUsersInOrganizationsListAsync( + List organizationUnitIds, + CancellationToken cancellationToken = default + ); - Task GetCountAsync( - string filter = null, - Guid? roleId = null, - Guid? organizationUnitId = null, - string userName = null, - string phoneNumber = null, - string emailAddress = null, - bool? isLockedOut = null, - bool? notActive = null, - CancellationToken cancellationToken = default + Task> GetUsersInOrganizationUnitWithChildrenAsync( + string code, + CancellationToken cancellationToken = default ); - } + + Task GetCountAsync( + string filter = null, + Guid? roleId = null, + Guid? organizationUnitId = null, + string userName = null, + string phoneNumber = null, + string emailAddress = null, + bool? isLockedOut = null, + bool? notActive = null, + CancellationToken cancellationToken = default + ); } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IOrganizationUnitRepository.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IOrganizationUnitRepository.cs index bf39874e00..3e6a3f4f23 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IOrganizationUnitRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IOrganizationUnitRepository.cs @@ -4,113 +4,112 @@ using System.Threading; using System.Threading.Tasks; using Volo.Abp.Domain.Repositories; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public interface IOrganizationUnitRepository : IBasicRepository { - public interface IOrganizationUnitRepository : IBasicRepository - { - Task> GetChildrenAsync( - Guid? parentId, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); - - Task> GetAllChildrenWithParentCodeAsync( - string code, - Guid? parentId, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); - - Task GetAsync( - string displayName, - bool includeDetails = true, - CancellationToken cancellationToken = default - ); - - Task> GetListAsync( - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); - - Task> GetListAsync( - IEnumerable ids, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); - - Task> GetRolesAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); - - Task GetRolesCountAsync( - OrganizationUnit organizationUnit, - CancellationToken cancellationToken = default - ); - - Task> GetUnaddedRolesAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); - - Task GetUnaddedRolesCountAsync( - OrganizationUnit organizationUnit, - string filter = null, - CancellationToken cancellationToken = default - ); - - Task> GetMembersAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); - - Task GetMembersCountAsync( - OrganizationUnit organizationUnit, - string filter = null, - CancellationToken cancellationToken = default - ); - - Task> GetUnaddedUsersAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - CancellationToken cancellationToken = default - ); - - Task GetUnaddedUsersCountAsync( - OrganizationUnit organizationUnit, - string filter = null, - CancellationToken cancellationToken = default - ); - - Task RemoveAllRolesAsync( - OrganizationUnit organizationUnit, - CancellationToken cancellationToken = default - ); - - Task RemoveAllMembersAsync( - OrganizationUnit organizationUnit, - CancellationToken cancellationToken = default - ); - } + Task> GetChildrenAsync( + Guid? parentId, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); + + Task> GetAllChildrenWithParentCodeAsync( + string code, + Guid? parentId, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); + + Task GetAsync( + string displayName, + bool includeDetails = true, + CancellationToken cancellationToken = default + ); + + Task> GetListAsync( + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); + + Task> GetListAsync( + IEnumerable ids, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); + + Task> GetRolesAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); + + Task GetRolesCountAsync( + OrganizationUnit organizationUnit, + CancellationToken cancellationToken = default + ); + + Task> GetUnaddedRolesAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); + + Task GetUnaddedRolesCountAsync( + OrganizationUnit organizationUnit, + string filter = null, + CancellationToken cancellationToken = default + ); + + Task> GetMembersAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); + + Task GetMembersCountAsync( + OrganizationUnit organizationUnit, + string filter = null, + CancellationToken cancellationToken = default + ); + + Task> GetUnaddedUsersAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + CancellationToken cancellationToken = default + ); + + Task GetUnaddedUsersCountAsync( + OrganizationUnit organizationUnit, + string filter = null, + CancellationToken cancellationToken = default + ); + + Task RemoveAllRolesAsync( + OrganizationUnit organizationUnit, + CancellationToken cancellationToken = default + ); + + Task RemoveAllMembersAsync( + OrganizationUnit organizationUnit, + CancellationToken cancellationToken = default + ); } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaim.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaim.cs index d64218a68f..6a8753fadb 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaim.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaim.cs @@ -4,58 +4,57 @@ using JetBrains.Annotations; using Volo.Abp.Domain.Entities; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class IdentityClaim : Entity, IMultiTenant { - public abstract class IdentityClaim : Entity, IMultiTenant + public virtual Guid? TenantId { get; protected set; } + + /// + /// Gets or sets the claim type for this claim. + /// + public virtual string ClaimType { get; protected set; } + + /// + /// Gets or sets the claim value for this claim. + /// + public virtual string ClaimValue { get; protected set; } + + protected IdentityClaim() + { + + } + + protected internal IdentityClaim(Guid id, [NotNull] Claim claim, Guid? tenantId) + : this(id, claim.Type, claim.Value, tenantId) + { + + } + + protected internal IdentityClaim(Guid id, [NotNull] string claimType, string claimValue, Guid? tenantId) + { + Check.NotNull(claimType, nameof(claimType)); + + Id = id; + ClaimType = claimType; + ClaimValue = claimValue; + TenantId = tenantId; + } + + /// + /// Creates a Claim instance from this entity. + /// + /// + public virtual Claim ToClaim() { - public virtual Guid? TenantId { get; protected set; } - - /// - /// Gets or sets the claim type for this claim. - /// - public virtual string ClaimType { get; protected set; } - - /// - /// Gets or sets the claim value for this claim. - /// - public virtual string ClaimValue { get; protected set; } - - protected IdentityClaim() - { - - } - - protected internal IdentityClaim(Guid id, [NotNull] Claim claim, Guid? tenantId) - : this(id, claim.Type, claim.Value, tenantId) - { - - } - - protected internal IdentityClaim(Guid id, [NotNull] string claimType, string claimValue, Guid? tenantId) - { - Check.NotNull(claimType, nameof(claimType)); - - Id = id; - ClaimType = claimType; - ClaimValue = claimValue; - TenantId = tenantId; - } - - /// - /// Creates a Claim instance from this entity. - /// - /// - public virtual Claim ToClaim() - { - return new Claim(ClaimType, ClaimValue); - } - - public virtual void SetClaim([NotNull] Claim claim) - { - Check.NotNull(claim, nameof(claim)); - - ClaimType = claim.Type; - ClaimValue = claim.Value; - } + return new Claim(ClaimType, ClaimValue); + } + + public virtual void SetClaim([NotNull] Claim claim) + { + Check.NotNull(claim, nameof(claim)); + + ClaimType = claim.Type; + ClaimValue = claim.Value; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimType.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimType.cs index df3c139c53..2f988948a3 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimType.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimType.cs @@ -2,52 +2,51 @@ using System; using Volo.Abp.Domain.Entities; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityClaimType : AggregateRoot { - public class IdentityClaimType : AggregateRoot - { - public virtual string Name { get; protected set; } + public virtual string Name { get; protected set; } - public virtual bool Required { get; set; } + public virtual bool Required { get; set; } - public virtual bool IsStatic { get; protected set; } + public virtual bool IsStatic { get; protected set; } - public virtual string Regex { get; set; } + public virtual string Regex { get; set; } - public virtual string RegexDescription { get; set; } + public virtual string RegexDescription { get; set; } - public virtual string Description { get; set; } + public virtual string Description { get; set; } - public virtual IdentityClaimValueType ValueType { get; set; } + public virtual IdentityClaimValueType ValueType { get; set; } - protected IdentityClaimType() - { + protected IdentityClaimType() + { - } + } - public IdentityClaimType( - Guid id, - [NotNull] string name, - bool required = false, - bool isStatic = false, - [CanBeNull] string regex = null, - [CanBeNull] string regexDescription = null, - [CanBeNull] string description = null, - IdentityClaimValueType valueType = IdentityClaimValueType.String) - { - Id = id; - SetName(name); - Required = required; - IsStatic = isStatic; - Regex = regex; - RegexDescription = regexDescription; - Description = description; - ValueType = valueType; - } + public IdentityClaimType( + Guid id, + [NotNull] string name, + bool required = false, + bool isStatic = false, + [CanBeNull] string regex = null, + [CanBeNull] string regexDescription = null, + [CanBeNull] string description = null, + IdentityClaimValueType valueType = IdentityClaimValueType.String) + { + Id = id; + SetName(name); + Required = required; + IsStatic = isStatic; + Regex = regex; + RegexDescription = regexDescription; + Description = description; + ValueType = valueType; + } - public void SetName([NotNull] string name) - { - Name = Check.NotNull(name, nameof(name)); - } + public void SetName([NotNull] string name) + { + Name = Check.NotNull(name, nameof(name)); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimTypeManager.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimTypeManager.cs index 9978cdd88a..2785e317b4 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimTypeManager.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimTypeManager.cs @@ -1,41 +1,40 @@ using System.Threading.Tasks; using Volo.Abp.Domain.Services; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityClaimTypeManager : DomainService { - public class IdentityClaimTypeManager : DomainService + protected IIdentityClaimTypeRepository IdentityClaimTypeRepository { get; } + + public IdentityClaimTypeManager(IIdentityClaimTypeRepository identityClaimTypeRepository) { - protected IIdentityClaimTypeRepository IdentityClaimTypeRepository { get; } + IdentityClaimTypeRepository = identityClaimTypeRepository; + } - public IdentityClaimTypeManager(IIdentityClaimTypeRepository identityClaimTypeRepository) + public virtual async Task CreateAsync(IdentityClaimType claimType) + { + if (await IdentityClaimTypeRepository.AnyAsync(claimType.Name)) { - IdentityClaimTypeRepository = identityClaimTypeRepository; + throw new AbpException($"Name Exist: {claimType.Name}"); } - public virtual async Task CreateAsync(IdentityClaimType claimType) - { - if (await IdentityClaimTypeRepository.AnyAsync(claimType.Name)) - { - throw new AbpException($"Name Exist: {claimType.Name}"); - } + return await IdentityClaimTypeRepository.InsertAsync(claimType); + } - return await IdentityClaimTypeRepository.InsertAsync(claimType); + public virtual async Task UpdateAsync(IdentityClaimType claimType) + { + if (await IdentityClaimTypeRepository.AnyAsync(claimType.Name, claimType.Id)) + { + throw new AbpException($"Name Exist: {claimType.Name}"); } - public virtual async Task UpdateAsync(IdentityClaimType claimType) + if (claimType.IsStatic) { - if (await IdentityClaimTypeRepository.AnyAsync(claimType.Name, claimType.Id)) - { - throw new AbpException($"Name Exist: {claimType.Name}"); - } - - if (claimType.IsStatic) - { - throw new AbpException($"Can not update a static ClaimType."); - } - - - return await IdentityClaimTypeRepository.UpdateAsync(claimType); + throw new AbpException($"Can not update a static ClaimType."); } + + + return await IdentityClaimTypeRepository.UpdateAsync(claimType); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeedContributor.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeedContributor.cs index 82677d74e4..b14ace4b05 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeedContributor.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeedContributor.cs @@ -2,29 +2,28 @@ using Volo.Abp.Data; using Volo.Abp.DependencyInjection; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityDataSeedContributor : IDataSeedContributor, ITransientDependency { - public class IdentityDataSeedContributor : IDataSeedContributor, ITransientDependency - { - public const string AdminEmailPropertyName = "AdminEmail"; - public const string AdminEmailDefaultValue = "admin@abp.io"; - public const string AdminPasswordPropertyName = "AdminPassword"; - public const string AdminPasswordDefaultValue = "1q2w3E*"; + public const string AdminEmailPropertyName = "AdminEmail"; + public const string AdminEmailDefaultValue = "admin@abp.io"; + public const string AdminPasswordPropertyName = "AdminPassword"; + public const string AdminPasswordDefaultValue = "1q2w3E*"; - protected IIdentityDataSeeder IdentityDataSeeder { get; } + protected IIdentityDataSeeder IdentityDataSeeder { get; } - public IdentityDataSeedContributor(IIdentityDataSeeder identityDataSeeder) - { - IdentityDataSeeder = identityDataSeeder; - } + public IdentityDataSeedContributor(IIdentityDataSeeder identityDataSeeder) + { + IdentityDataSeeder = identityDataSeeder; + } - public virtual Task SeedAsync(DataSeedContext context) - { - return IdentityDataSeeder.SeedAsync( - context?[AdminEmailPropertyName] as string ?? AdminEmailDefaultValue, - context?[AdminPasswordPropertyName] as string ?? AdminPasswordDefaultValue, - context?.TenantId - ); - } + public virtual Task SeedAsync(DataSeedContext context) + { + return IdentityDataSeeder.SeedAsync( + context?[AdminEmailPropertyName] as string ?? AdminEmailDefaultValue, + context?[AdminPasswordPropertyName] as string ?? AdminPasswordDefaultValue, + context?.TenantId + ); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeedResult.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeedResult.cs index fe6c5bdf17..edf2699e47 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeedResult.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeedResult.cs @@ -1,9 +1,8 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityDataSeedResult { - public class IdentityDataSeedResult - { - public bool CreatedAdminUser { get; set; } + public bool CreatedAdminUser { get; set; } - public bool CreatedAdminRole { get; set; } - } -} \ No newline at end of file + public bool CreatedAdminRole { get; set; } +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeeder.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeeder.cs index 851676b840..c09f2b030f 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeeder.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeeder.cs @@ -7,101 +7,100 @@ using Volo.Abp.Guids; using Volo.Abp.MultiTenancy; using Volo.Abp.Uow; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityDataSeeder : ITransientDependency, IIdentityDataSeeder { - public class IdentityDataSeeder : ITransientDependency, IIdentityDataSeeder + protected IGuidGenerator GuidGenerator { get; } + protected IIdentityRoleRepository RoleRepository { get; } + protected IIdentityUserRepository UserRepository { get; } + protected ILookupNormalizer LookupNormalizer { get; } + protected IdentityUserManager UserManager { get; } + protected IdentityRoleManager RoleManager { get; } + protected ICurrentTenant CurrentTenant { get; } + protected IOptions IdentityOptions { get; } + + public IdentityDataSeeder( + IGuidGenerator guidGenerator, + IIdentityRoleRepository roleRepository, + IIdentityUserRepository userRepository, + ILookupNormalizer lookupNormalizer, + IdentityUserManager userManager, + IdentityRoleManager roleManager, + ICurrentTenant currentTenant, + IOptions identityOptions) { - protected IGuidGenerator GuidGenerator { get; } - protected IIdentityRoleRepository RoleRepository { get; } - protected IIdentityUserRepository UserRepository { get; } - protected ILookupNormalizer LookupNormalizer { get; } - protected IdentityUserManager UserManager { get; } - protected IdentityRoleManager RoleManager { get; } - protected ICurrentTenant CurrentTenant { get; } - protected IOptions IdentityOptions { get; } + GuidGenerator = guidGenerator; + RoleRepository = roleRepository; + UserRepository = userRepository; + LookupNormalizer = lookupNormalizer; + UserManager = userManager; + RoleManager = roleManager; + CurrentTenant = currentTenant; + IdentityOptions = identityOptions; + } - public IdentityDataSeeder( - IGuidGenerator guidGenerator, - IIdentityRoleRepository roleRepository, - IIdentityUserRepository userRepository, - ILookupNormalizer lookupNormalizer, - IdentityUserManager userManager, - IdentityRoleManager roleManager, - ICurrentTenant currentTenant, - IOptions identityOptions) - { - GuidGenerator = guidGenerator; - RoleRepository = roleRepository; - UserRepository = userRepository; - LookupNormalizer = lookupNormalizer; - UserManager = userManager; - RoleManager = roleManager; - CurrentTenant = currentTenant; - IdentityOptions = identityOptions; - } + [UnitOfWork] + public virtual async Task SeedAsync( + string adminEmail, + string adminPassword, + Guid? tenantId = null) + { + Check.NotNullOrWhiteSpace(adminEmail, nameof(adminEmail)); + Check.NotNullOrWhiteSpace(adminPassword, nameof(adminPassword)); - [UnitOfWork] - public virtual async Task SeedAsync( - string adminEmail, - string adminPassword, - Guid? tenantId = null) + using (CurrentTenant.Change(tenantId)) { - Check.NotNullOrWhiteSpace(adminEmail, nameof(adminEmail)); - Check.NotNullOrWhiteSpace(adminPassword, nameof(adminPassword)); + await IdentityOptions.SetAsync(); + + var result = new IdentityDataSeedResult(); + //"admin" user + const string adminUserName = "admin"; + var adminUser = await UserRepository.FindByNormalizedUserNameAsync( + LookupNormalizer.NormalizeName(adminUserName) + ); - using (CurrentTenant.Change(tenantId)) + if (adminUser != null) { - await IdentityOptions.SetAsync(); + return result; + } - var result = new IdentityDataSeedResult(); - //"admin" user - const string adminUserName = "admin"; - var adminUser = await UserRepository.FindByNormalizedUserNameAsync( - LookupNormalizer.NormalizeName(adminUserName) - ); + adminUser = new IdentityUser( + GuidGenerator.Create(), + adminUserName, + adminEmail, + tenantId + ) + { + Name = adminUserName + }; - if (adminUser != null) - { - return result; - } + (await UserManager.CreateAsync(adminUser, adminPassword, validatePassword: false)).CheckErrors(); + result.CreatedAdminUser = true; - adminUser = new IdentityUser( + //"admin" role + const string adminRoleName = "admin"; + var adminRole = + await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName(adminRoleName)); + if (adminRole == null) + { + adminRole = new IdentityRole( GuidGenerator.Create(), - adminUserName, - adminEmail, + adminRoleName, tenantId ) { - Name = adminUserName + IsStatic = true, + IsPublic = true }; - (await UserManager.CreateAsync(adminUser, adminPassword, validatePassword: false)).CheckErrors(); - result.CreatedAdminUser = true; - - //"admin" role - const string adminRoleName = "admin"; - var adminRole = - await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName(adminRoleName)); - if (adminRole == null) - { - adminRole = new IdentityRole( - GuidGenerator.Create(), - adminRoleName, - tenantId - ) - { - IsStatic = true, - IsPublic = true - }; - - (await RoleManager.CreateAsync(adminRole)).CheckErrors(); - result.CreatedAdminRole = true; - } + (await RoleManager.CreateAsync(adminRole)).CheckErrors(); + result.CreatedAdminRole = true; + } - (await UserManager.AddToRoleAsync(adminUser, adminRoleName)).CheckErrors(); + (await UserManager.AddToRoleAsync(adminUser, adminRoleName)).CheckErrors(); - return result; - } + return result; } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDomainMappingProfile.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDomainMappingProfile.cs index 9a5557401d..ae9e5b5065 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDomainMappingProfile.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDomainMappingProfile.cs @@ -1,16 +1,15 @@ using AutoMapper; using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityDomainMappingProfile : Profile { - public class IdentityDomainMappingProfile : Profile + public IdentityDomainMappingProfile() { - public IdentityDomainMappingProfile() - { - CreateMap(); - CreateMap(); - CreateMap(); - CreateMap(); - } + CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUser.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUser.cs index bec5563525..13b52c61f8 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUser.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUser.cs @@ -1,44 +1,43 @@ using System; using Volo.Abp.Domain.Entities; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityLinkUser : BasicAggregateRoot { - public class IdentityLinkUser : BasicAggregateRoot - { - public virtual Guid SourceUserId { get; protected set; } + public virtual Guid SourceUserId { get; protected set; } - public virtual Guid? SourceTenantId { get; protected set; } + public virtual Guid? SourceTenantId { get; protected set; } - public virtual Guid TargetUserId { get; protected set; } + public virtual Guid TargetUserId { get; protected set; } - public virtual Guid? TargetTenantId { get; protected set; } + public virtual Guid? TargetTenantId { get; protected set; } - /// - /// Initializes a new instance of . - /// - protected IdentityLinkUser() - { + /// + /// Initializes a new instance of . + /// + protected IdentityLinkUser() + { - } + } - public IdentityLinkUser(Guid id, IdentityLinkUserInfo sourceUser, IdentityLinkUserInfo targetUser) - : base(id) - { - SourceUserId = sourceUser.UserId; - SourceTenantId = sourceUser.TenantId; + public IdentityLinkUser(Guid id, IdentityLinkUserInfo sourceUser, IdentityLinkUserInfo targetUser) + : base(id) + { + SourceUserId = sourceUser.UserId; + SourceTenantId = sourceUser.TenantId; - TargetUserId = targetUser.UserId; - TargetTenantId = targetUser.TenantId; - } + TargetUserId = targetUser.UserId; + TargetTenantId = targetUser.TenantId; + } - public IdentityLinkUser(Guid id, Guid sourceUserId, Guid? sourceTenantId, Guid targetUserId, Guid? targetTenantId) - : base(id) - { - SourceUserId = sourceUserId; - SourceTenantId = sourceTenantId; + public IdentityLinkUser(Guid id, Guid sourceUserId, Guid? sourceTenantId, Guid targetUserId, Guid? targetTenantId) + : base(id) + { + SourceUserId = sourceUserId; + SourceTenantId = sourceTenantId; - TargetUserId = targetUserId; - TargetTenantId = targetTenantId; - } + TargetUserId = targetUserId; + TargetTenantId = targetTenantId; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserInfo.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserInfo.cs index 68edd57f4a..250f6f88d6 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserInfo.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserInfo.cs @@ -1,17 +1,16 @@ using System; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityLinkUserInfo { - public class IdentityLinkUserInfo - { - public virtual Guid UserId { get; set; } + public virtual Guid UserId { get; set; } - public virtual Guid? TenantId { get; set; } + public virtual Guid? TenantId { get; set; } - public IdentityLinkUserInfo(Guid userId, Guid? tenantId) - { - UserId = userId; - TenantId = tenantId; - } + public IdentityLinkUserInfo(Guid userId, Guid? tenantId) + { + UserId = userId; + TenantId = tenantId; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserManager.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserManager.cs index 35c76123cd..6c7de47dc0 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserManager.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserManager.cs @@ -6,147 +6,146 @@ using System.Threading.Tasks; using Volo.Abp.Domain.Services; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityLinkUserManager : DomainService { - public class IdentityLinkUserManager : DomainService - { - protected IIdentityLinkUserRepository IdentityLinkUserRepository { get; } + protected IIdentityLinkUserRepository IdentityLinkUserRepository { get; } - protected IdentityUserManager UserManager { get; } + protected IdentityUserManager UserManager { get; } - protected new ICurrentTenant CurrentTenant { get; } + protected new ICurrentTenant CurrentTenant { get; } - public IdentityLinkUserManager(IIdentityLinkUserRepository identityLinkUserRepository, IdentityUserManager userManager, ICurrentTenant currentTenant) - { - IdentityLinkUserRepository = identityLinkUserRepository; - UserManager = userManager; - CurrentTenant = currentTenant; - } + public IdentityLinkUserManager(IIdentityLinkUserRepository identityLinkUserRepository, IdentityUserManager userManager, ICurrentTenant currentTenant) + { + IdentityLinkUserRepository = identityLinkUserRepository; + UserManager = userManager; + CurrentTenant = currentTenant; + } - public async Task> GetListAsync(IdentityLinkUserInfo linkUserInfo, bool includeIndirect = false, CancellationToken cancellationToken = default) + public async Task> GetListAsync(IdentityLinkUserInfo linkUserInfo, bool includeIndirect = false, CancellationToken cancellationToken = default) + { + using (CurrentTenant.Change(null)) { - using (CurrentTenant.Change(null)) + var users = await IdentityLinkUserRepository.GetListAsync(linkUserInfo, cancellationToken: cancellationToken); + if (includeIndirect == false) { - var users = await IdentityLinkUserRepository.GetListAsync(linkUserInfo, cancellationToken: cancellationToken); - if (includeIndirect == false) - { - return users; - } + return users; + } - var userInfos = new List() + var userInfos = new List() { linkUserInfo }; - var allUsers = new List(); - allUsers.AddRange(users); + var allUsers = new List(); + allUsers.AddRange(users); - do + do + { + var nextUsers = new List(); + foreach (var user in users) { - var nextUsers = new List(); - foreach (var user in users) + if (userInfos.Any(x => x.TenantId != user.SourceTenantId || x.UserId != user.SourceUserId)) { - if (userInfos.Any(x => x.TenantId != user.SourceTenantId || x.UserId != user.SourceUserId)) - { - nextUsers.Add(new IdentityLinkUserInfo(user.SourceUserId, user.SourceTenantId)); - } - - if (userInfos.Any(x => x.TenantId != user.TargetTenantId || x.UserId != user.TargetUserId)) - { - nextUsers.Add(new IdentityLinkUserInfo(user.TargetUserId, user.TargetTenantId)); - } + nextUsers.Add(new IdentityLinkUserInfo(user.SourceUserId, user.SourceTenantId)); } - users = new List(); - foreach (var next in nextUsers) + if (userInfos.Any(x => x.TenantId != user.TargetTenantId || x.UserId != user.TargetUserId)) { - users.AddRange(await IdentityLinkUserRepository.GetListAsync(next, userInfos, cancellationToken)); + nextUsers.Add(new IdentityLinkUserInfo(user.TargetUserId, user.TargetTenantId)); } + } + + users = new List(); + foreach (var next in nextUsers) + { + users.AddRange(await IdentityLinkUserRepository.GetListAsync(next, userInfos, cancellationToken)); + } - userInfos.AddRange(nextUsers); - allUsers.AddRange(users); - } while (users.Any()); + userInfos.AddRange(nextUsers); + allUsers.AddRange(users); + } while (users.Any()); - return allUsers; - } + return allUsers; } + } - public virtual async Task LinkAsync(IdentityLinkUserInfo sourceLinkUser, IdentityLinkUserInfo targetLinkUser, CancellationToken cancellationToken = default) + public virtual async Task LinkAsync(IdentityLinkUserInfo sourceLinkUser, IdentityLinkUserInfo targetLinkUser, CancellationToken cancellationToken = default) + { + using (CurrentTenant.Change(null)) { - using (CurrentTenant.Change(null)) + if (sourceLinkUser.UserId == targetLinkUser.UserId && sourceLinkUser.TenantId == targetLinkUser.TenantId) { - if (sourceLinkUser.UserId == targetLinkUser.UserId && sourceLinkUser.TenantId == targetLinkUser.TenantId) - { - return; - } - - if (await IsLinkedAsync(sourceLinkUser, targetLinkUser, cancellationToken: cancellationToken)) - { - return; - } + return; + } - var userLink = new IdentityLinkUser( - GuidGenerator.Create(), - sourceLinkUser, - targetLinkUser); - await IdentityLinkUserRepository.InsertAsync(userLink, true, cancellationToken); + if (await IsLinkedAsync(sourceLinkUser, targetLinkUser, cancellationToken: cancellationToken)) + { + return; } + + var userLink = new IdentityLinkUser( + GuidGenerator.Create(), + sourceLinkUser, + targetLinkUser); + await IdentityLinkUserRepository.InsertAsync(userLink, true, cancellationToken); } + } - public virtual async Task IsLinkedAsync(IdentityLinkUserInfo sourceLinkUser, IdentityLinkUserInfo targetLinkUser, bool includeIndirect = false, CancellationToken cancellationToken = default) + public virtual async Task IsLinkedAsync(IdentityLinkUserInfo sourceLinkUser, IdentityLinkUserInfo targetLinkUser, bool includeIndirect = false, CancellationToken cancellationToken = default) + { + using (CurrentTenant.Change(null)) { - using (CurrentTenant.Change(null)) + if (includeIndirect) { - if (includeIndirect) - { - return (await GetListAsync(sourceLinkUser, true, cancellationToken: cancellationToken)) - .Any(x => x.SourceTenantId == targetLinkUser.TenantId && x.SourceUserId == targetLinkUser.UserId || - x.TargetTenantId == targetLinkUser.TenantId && x.TargetUserId == targetLinkUser.UserId); - } - return await IdentityLinkUserRepository.FindAsync(sourceLinkUser, targetLinkUser, cancellationToken) != null; + return (await GetListAsync(sourceLinkUser, true, cancellationToken: cancellationToken)) + .Any(x => x.SourceTenantId == targetLinkUser.TenantId && x.SourceUserId == targetLinkUser.UserId || + x.TargetTenantId == targetLinkUser.TenantId && x.TargetUserId == targetLinkUser.UserId); } + return await IdentityLinkUserRepository.FindAsync(sourceLinkUser, targetLinkUser, cancellationToken) != null; } + } - public virtual async Task UnlinkAsync(IdentityLinkUserInfo sourceLinkUser, IdentityLinkUserInfo targetLinkUser, CancellationToken cancellationToken = default) + public virtual async Task UnlinkAsync(IdentityLinkUserInfo sourceLinkUser, IdentityLinkUserInfo targetLinkUser, CancellationToken cancellationToken = default) + { + using (CurrentTenant.Change(null)) { - using (CurrentTenant.Change(null)) + if (!await IsLinkedAsync(sourceLinkUser, targetLinkUser, cancellationToken: cancellationToken)) { - if (!await IsLinkedAsync(sourceLinkUser, targetLinkUser, cancellationToken: cancellationToken)) - { - return; - } + return; + } - var linkedUser = await IdentityLinkUserRepository.FindAsync(sourceLinkUser, targetLinkUser, cancellationToken); - if (linkedUser != null) - { - await IdentityLinkUserRepository.DeleteAsync(linkedUser, cancellationToken: cancellationToken); - } + var linkedUser = await IdentityLinkUserRepository.FindAsync(sourceLinkUser, targetLinkUser, cancellationToken); + if (linkedUser != null) + { + await IdentityLinkUserRepository.DeleteAsync(linkedUser, cancellationToken: cancellationToken); } } + } - public virtual async Task GenerateLinkTokenAsync(IdentityLinkUserInfo targetLinkUser, string tokenPurpose, CancellationToken cancellationToken = default) + public virtual async Task GenerateLinkTokenAsync(IdentityLinkUserInfo targetLinkUser, string tokenPurpose, CancellationToken cancellationToken = default) + { + using (CurrentTenant.Change(targetLinkUser.TenantId)) { - using (CurrentTenant.Change(targetLinkUser.TenantId)) - { - var user = await UserManager.GetByIdAsync(targetLinkUser.UserId); - return await UserManager.GenerateUserTokenAsync( - user, - LinkUserTokenProviderConsts.LinkUserTokenProviderName, - tokenPurpose); - } + var user = await UserManager.GetByIdAsync(targetLinkUser.UserId); + return await UserManager.GenerateUserTokenAsync( + user, + LinkUserTokenProviderConsts.LinkUserTokenProviderName, + tokenPurpose); } + } - public virtual async Task VerifyLinkTokenAsync(IdentityLinkUserInfo targetLinkUser, string token, string tokenPurpose, CancellationToken cancellationToken = default) + public virtual async Task VerifyLinkTokenAsync(IdentityLinkUserInfo targetLinkUser, string token, string tokenPurpose, CancellationToken cancellationToken = default) + { + using (CurrentTenant.Change(targetLinkUser.TenantId)) { - using (CurrentTenant.Change(targetLinkUser.TenantId)) - { - var user = await UserManager.GetByIdAsync(targetLinkUser.UserId); - return await UserManager.VerifyUserTokenAsync( - user, - LinkUserTokenProviderConsts.LinkUserTokenProviderName, - tokenPurpose, - token); - } + var user = await UserManager.GetByIdAsync(targetLinkUser.UserId); + return await UserManager.VerifyUserTokenAsync( + user, + LinkUserTokenProviderConsts.LinkUserTokenProviderName, + tokenPurpose, + token); } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRole.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRole.cs index f856ee2277..ce6c7d7049 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRole.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRole.cs @@ -9,105 +9,105 @@ using Volo.Abp.Domain.Entities; using Volo.Abp.Guids; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Represents a role in the identity system +/// +public class IdentityRole : AggregateRoot, IMultiTenant { + public virtual Guid? TenantId { get; protected set; } + + /// + /// Gets or sets the name for this role. + /// + public virtual string Name { get; protected internal set; } + + /// + /// Gets or sets the normalized name for this role. + /// + [DisableAuditing] + public virtual string NormalizedName { get; protected internal set; } + + /// + /// Navigation property for claims in this role. + /// + public virtual ICollection Claims { get; protected set; } + + /// + /// A default role is automatically assigned to a new user + /// + public virtual bool IsDefault { get; set; } + /// - /// Represents a role in the identity system + /// A static role can not be deleted/renamed /// - public class IdentityRole : AggregateRoot, IMultiTenant + public virtual bool IsStatic { get; set; } + + /// + /// A user can see other user's public roles + /// + public virtual bool IsPublic { get; set; } + + /// + /// Initializes a new instance of . + /// + protected IdentityRole() { } + + public IdentityRole(Guid id, [NotNull] string name, Guid? tenantId = null) { - public virtual Guid? TenantId { get; protected set; } - - /// - /// Gets or sets the name for this role. - /// - public virtual string Name { get; protected internal set; } - - /// - /// Gets or sets the normalized name for this role. - /// - [DisableAuditing] - public virtual string NormalizedName { get; protected internal set; } - - /// - /// Navigation property for claims in this role. - /// - public virtual ICollection Claims { get; protected set; } - - /// - /// A default role is automatically assigned to a new user - /// - public virtual bool IsDefault { get; set; } - - /// - /// A static role can not be deleted/renamed - /// - public virtual bool IsStatic { get; set; } - - /// - /// A user can see other user's public roles - /// - public virtual bool IsPublic { get; set; } - - /// - /// Initializes a new instance of . - /// - protected IdentityRole() { } - - public IdentityRole(Guid id, [NotNull] string name, Guid? tenantId = null) - { - Check.NotNull(name, nameof(name)); + Check.NotNull(name, nameof(name)); - Id = id; - Name = name; - TenantId = tenantId; - NormalizedName = name.ToUpperInvariant(); - ConcurrencyStamp = Guid.NewGuid().ToString(); + Id = id; + Name = name; + TenantId = tenantId; + NormalizedName = name.ToUpperInvariant(); + ConcurrencyStamp = Guid.NewGuid().ToString(); - Claims = new Collection(); - } + Claims = new Collection(); + } - public virtual void AddClaim([NotNull] IGuidGenerator guidGenerator, [NotNull] Claim claim) - { - Check.NotNull(guidGenerator, nameof(guidGenerator)); - Check.NotNull(claim, nameof(claim)); + public virtual void AddClaim([NotNull] IGuidGenerator guidGenerator, [NotNull] Claim claim) + { + Check.NotNull(guidGenerator, nameof(guidGenerator)); + Check.NotNull(claim, nameof(claim)); - Claims.Add(new IdentityRoleClaim(guidGenerator.Create(), Id, claim, TenantId)); - } + Claims.Add(new IdentityRoleClaim(guidGenerator.Create(), Id, claim, TenantId)); + } - public virtual void AddClaims([NotNull] IGuidGenerator guidGenerator, [NotNull] IEnumerable claims) - { - Check.NotNull(guidGenerator, nameof(guidGenerator)); - Check.NotNull(claims, nameof(claims)); + public virtual void AddClaims([NotNull] IGuidGenerator guidGenerator, [NotNull] IEnumerable claims) + { + Check.NotNull(guidGenerator, nameof(guidGenerator)); + Check.NotNull(claims, nameof(claims)); - foreach (var claim in claims) - { - AddClaim(guidGenerator, claim); - } + foreach (var claim in claims) + { + AddClaim(guidGenerator, claim); } + } - public virtual IdentityRoleClaim FindClaim([NotNull] Claim claim) - { - Check.NotNull(claim, nameof(claim)); + public virtual IdentityRoleClaim FindClaim([NotNull] Claim claim) + { + Check.NotNull(claim, nameof(claim)); - return Claims.FirstOrDefault(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value); - } + return Claims.FirstOrDefault(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value); + } - public virtual void RemoveClaim([NotNull] Claim claim) - { - Check.NotNull(claim, nameof(claim)); + public virtual void RemoveClaim([NotNull] Claim claim) + { + Check.NotNull(claim, nameof(claim)); - Claims.RemoveAll(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value); - } + Claims.RemoveAll(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value); + } - public virtual void ChangeName(string name) - { - Check.NotNullOrWhiteSpace(name, nameof(name)); + public virtual void ChangeName(string name) + { + Check.NotNullOrWhiteSpace(name, nameof(name)); - var oldName = Name; - Name = name; + var oldName = Name; + Name = name; - AddLocalEvent( + AddLocalEvent( #pragma warning disable 618 new IdentityRoleNameChangedEvent #pragma warning restore 618 @@ -115,22 +115,21 @@ namespace Volo.Abp.Identity IdentityRole = this, OldName = oldName } - ); + ); - AddDistributedEvent( - new IdentityRoleNameChangedEto - { - Id = Id, - Name = Name, - OldName = oldName, - TenantId = TenantId - } - ); - } + AddDistributedEvent( + new IdentityRoleNameChangedEto + { + Id = Id, + Name = Name, + OldName = oldName, + TenantId = TenantId + } + ); + } - public override string ToString() - { - return $"{base.ToString()}, Name = {Name}"; - } + public override string ToString() + { + return $"{base.ToString()}, Name = {Name}"; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleClaim.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleClaim.cs index 83f5416f9d..327acee0e4 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleClaim.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleClaim.cs @@ -2,49 +2,48 @@ using System; using System.Security.Claims; using JetBrains.Annotations; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Represents a claim that is granted to all users within a role. +/// +public class IdentityRoleClaim : IdentityClaim { /// - /// Represents a claim that is granted to all users within a role. + /// Gets or sets the of the primary key of the role associated with this claim. /// - public class IdentityRoleClaim : IdentityClaim - { - /// - /// Gets or sets the of the primary key of the role associated with this claim. - /// - public virtual Guid RoleId { get; protected set; } + public virtual Guid RoleId { get; protected set; } - protected IdentityRoleClaim() - { + protected IdentityRoleClaim() + { - } + } - protected internal IdentityRoleClaim( - Guid id, - Guid roleId, - [NotNull] Claim claim, - Guid? tenantId) - : base( - id, - claim, - tenantId) - { - RoleId = roleId; - } + protected internal IdentityRoleClaim( + Guid id, + Guid roleId, + [NotNull] Claim claim, + Guid? tenantId) + : base( + id, + claim, + tenantId) + { + RoleId = roleId; + } - public IdentityRoleClaim( - Guid id, - Guid roleId, - [NotNull] string claimType, - string claimValue, - Guid? tenantId) - : base( - id, - claimType, - claimValue, - tenantId) - { - RoleId = roleId; - } + public IdentityRoleClaim( + Guid id, + Guid roleId, + [NotNull] string claimType, + string claimValue, + Guid? tenantId) + : base( + id, + claimType, + claimValue, + tenantId) + { + RoleId = roleId; } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleManager.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleManager.cs index 7522b96159..e6f8919c17 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleManager.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleManager.cs @@ -11,63 +11,62 @@ using Volo.Abp.Domain.Services; using Volo.Abp.Identity.Localization; using Volo.Abp.Threading; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityRoleManager : RoleManager, IDomainService { - public class IdentityRoleManager : RoleManager, IDomainService - { - protected override CancellationToken CancellationToken => CancellationTokenProvider.Token; + protected override CancellationToken CancellationToken => CancellationTokenProvider.Token; - protected IStringLocalizer Localizer { get; } - protected ICancellationTokenProvider CancellationTokenProvider { get; } + protected IStringLocalizer Localizer { get; } + protected ICancellationTokenProvider CancellationTokenProvider { get; } - public IdentityRoleManager( - IdentityRoleStore store, - IEnumerable> roleValidators, - ILookupNormalizer keyNormalizer, - IdentityErrorDescriber errors, - ILogger logger, - IStringLocalizer localizer, - ICancellationTokenProvider cancellationTokenProvider) - : base( - store, - roleValidators, - keyNormalizer, - errors, - logger) - { - Localizer = localizer; - CancellationTokenProvider = cancellationTokenProvider; - } + public IdentityRoleManager( + IdentityRoleStore store, + IEnumerable> roleValidators, + ILookupNormalizer keyNormalizer, + IdentityErrorDescriber errors, + ILogger logger, + IStringLocalizer localizer, + ICancellationTokenProvider cancellationTokenProvider) + : base( + store, + roleValidators, + keyNormalizer, + errors, + logger) + { + Localizer = localizer; + CancellationTokenProvider = cancellationTokenProvider; + } - public virtual async Task GetByIdAsync(Guid id) + public virtual async Task GetByIdAsync(Guid id) + { + var role = await Store.FindByIdAsync(id.ToString(), CancellationToken); + if (role == null) { - var role = await Store.FindByIdAsync(id.ToString(), CancellationToken); - if (role == null) - { - throw new EntityNotFoundException(typeof(IdentityRole), id); - } - - return role; + throw new EntityNotFoundException(typeof(IdentityRole), id); } - public async override Task SetRoleNameAsync(IdentityRole role, string name) - { - if (role.IsStatic && role.Name != name) - { - throw new BusinessException(IdentityErrorCodes.StaticRoleRenaming); - } + return role; + } - return await base.SetRoleNameAsync(role, name); + public async override Task SetRoleNameAsync(IdentityRole role, string name) + { + if (role.IsStatic && role.Name != name) + { + throw new BusinessException(IdentityErrorCodes.StaticRoleRenaming); } - public async override Task DeleteAsync(IdentityRole role) - { - if (role.IsStatic) - { - throw new BusinessException(IdentityErrorCodes.StaticRoleDeletion); - } + return await base.SetRoleNameAsync(role, name); + } - return await base.DeleteAsync(role); + public async override Task DeleteAsync(IdentityRole role) + { + if (role.IsStatic) + { + throw new BusinessException(IdentityErrorCodes.StaticRoleDeletion); } + + return await base.DeleteAsync(role); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleNameChangedEvent.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleNameChangedEvent.cs index 86fc5eab3e..7754d8f077 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleNameChangedEvent.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleNameChangedEvent.cs @@ -1,11 +1,10 @@ using System; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[Obsolete("Use the distributed event (IdentityRoleNameChangedEto) instead.")] +public class IdentityRoleNameChangedEvent { - [Obsolete("Use the distributed event (IdentityRoleNameChangedEto) instead.")] - public class IdentityRoleNameChangedEvent - { - public IdentityRole IdentityRole { get; set; } - public string OldName { get; set; } - } + public IdentityRole IdentityRole { get; set; } + public string OldName { get; set; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleStore.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleStore.cs index c21b839b00..4e268b6c07 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleStore.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleStore.cs @@ -12,282 +12,281 @@ using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Repositories; using Volo.Abp.Guids; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Creates a new instance of a persistence store for roles. +/// +public class IdentityRoleStore : + IRoleStore, + IRoleClaimStore, + ITransientDependency { + protected IIdentityRoleRepository RoleRepository { get; } + protected ILogger Logger { get; } + protected IGuidGenerator GuidGenerator { get; } + /// - /// Creates a new instance of a persistence store for roles. + /// Constructs a new instance of . /// - public class IdentityRoleStore : - IRoleStore, - IRoleClaimStore, - ITransientDependency + public IdentityRoleStore( + IIdentityRoleRepository roleRepository, + ILogger logger, + IGuidGenerator guidGenerator, + IdentityErrorDescriber describer = null) { - protected IIdentityRoleRepository RoleRepository { get; } - protected ILogger Logger { get; } - protected IGuidGenerator GuidGenerator { get; } - - /// - /// Constructs a new instance of . - /// - public IdentityRoleStore( - IIdentityRoleRepository roleRepository, - ILogger logger, - IGuidGenerator guidGenerator, - IdentityErrorDescriber describer = null) - { - RoleRepository = roleRepository; - Logger = logger; - GuidGenerator = guidGenerator; + RoleRepository = roleRepository; + Logger = logger; + GuidGenerator = guidGenerator; - ErrorDescriber = describer ?? new IdentityErrorDescriber(); - } + ErrorDescriber = describer ?? new IdentityErrorDescriber(); + } - /// - /// Gets or sets the for any error that occurred with the current operation. - /// - public IdentityErrorDescriber ErrorDescriber { get; set; } - - /// - /// Gets or sets a flag indicating if changes should be persisted after CreateAsync, UpdateAsync and DeleteAsync are called. - /// - /// - /// True if changes should be automatically persisted, otherwise false. - /// - public bool AutoSaveChanges { get; set; } = true; - - /// - /// Creates a new role in a store as an asynchronous operation. - /// - /// The role to create in the store. - /// The used to propagate notifications that the operation should be canceled. - /// A that represents the of the asynchronous query. - public virtual async Task CreateAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Gets or sets the for any error that occurred with the current operation. + /// + public IdentityErrorDescriber ErrorDescriber { get; set; } - Check.NotNull(role, nameof(role)); + /// + /// Gets or sets a flag indicating if changes should be persisted after CreateAsync, UpdateAsync and DeleteAsync are called. + /// + /// + /// True if changes should be automatically persisted, otherwise false. + /// + public bool AutoSaveChanges { get; set; } = true; - await RoleRepository.InsertAsync(role, AutoSaveChanges, cancellationToken); + /// + /// Creates a new role in a store as an asynchronous operation. + /// + /// The role to create in the store. + /// The used to propagate notifications that the operation should be canceled. + /// A that represents the of the asynchronous query. + public virtual async Task CreateAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return IdentityResult.Success; - } + Check.NotNull(role, nameof(role)); - /// - /// Updates a role in a store as an asynchronous operation. - /// - /// The role to update in the store. - /// The used to propagate notifications that the operation should be canceled. - /// A that represents the of the asynchronous query. - public virtual async Task UpdateAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + await RoleRepository.InsertAsync(role, AutoSaveChanges, cancellationToken); - Check.NotNull(role, nameof(role)); + return IdentityResult.Success; + } - try - { - await RoleRepository.UpdateAsync(role, AutoSaveChanges, cancellationToken); - } - catch (AbpDbConcurrencyException ex) - { - Logger.LogWarning(ex.ToString()); //Trigger some AbpHandledException event - return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); - } + /// + /// Updates a role in a store as an asynchronous operation. + /// + /// The role to update in the store. + /// The used to propagate notifications that the operation should be canceled. + /// A that represents the of the asynchronous query. + public virtual async Task UpdateAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return IdentityResult.Success; - } + Check.NotNull(role, nameof(role)); - /// - /// Deletes a role from the store as an asynchronous operation. - /// - /// The role to delete from the store. - /// The used to propagate notifications that the operation should be canceled. - /// A that represents the of the asynchronous query. - public virtual async Task DeleteAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) + try { - cancellationToken.ThrowIfCancellationRequested(); + await RoleRepository.UpdateAsync(role, AutoSaveChanges, cancellationToken); + } + catch (AbpDbConcurrencyException ex) + { + Logger.LogWarning(ex.ToString()); //Trigger some AbpHandledException event + return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); + } - Check.NotNull(role, nameof(role)); + return IdentityResult.Success; + } - try - { - await RoleRepository.DeleteAsync(role, AutoSaveChanges, cancellationToken); - } - catch (AbpDbConcurrencyException ex) - { - Logger.LogWarning(ex.ToString()); //Trigger some AbpHandledException event - return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); - } + /// + /// Deletes a role from the store as an asynchronous operation. + /// + /// The role to delete from the store. + /// The used to propagate notifications that the operation should be canceled. + /// A that represents the of the asynchronous query. + public virtual async Task DeleteAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return IdentityResult.Success; - } + Check.NotNull(role, nameof(role)); - /// - /// Gets the ID for a role from the store as an asynchronous operation. - /// - /// The role whose ID should be returned. - /// The used to propagate notifications that the operation should be canceled. - /// A that contains the ID of the role. - public virtual Task GetRoleIdAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) + try + { + await RoleRepository.DeleteAsync(role, AutoSaveChanges, cancellationToken); + } + catch (AbpDbConcurrencyException ex) { - cancellationToken.ThrowIfCancellationRequested(); + Logger.LogWarning(ex.ToString()); //Trigger some AbpHandledException event + return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); + } - Check.NotNull(role, nameof(role)); + return IdentityResult.Success; + } - return Task.FromResult(role.Id.ToString()); - } + /// + /// Gets the ID for a role from the store as an asynchronous operation. + /// + /// The role whose ID should be returned. + /// The used to propagate notifications that the operation should be canceled. + /// A that contains the ID of the role. + public virtual Task GetRoleIdAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Gets the name of a role from the store as an asynchronous operation. - /// - /// The role whose name should be returned. - /// The used to propagate notifications that the operation should be canceled. - /// A that contains the name of the role. - public virtual Task GetRoleNameAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(role, nameof(role)); - Check.NotNull(role, nameof(role)); + return Task.FromResult(role.Id.ToString()); + } - return Task.FromResult(role.Name); - } + /// + /// Gets the name of a role from the store as an asynchronous operation. + /// + /// The role whose name should be returned. + /// The used to propagate notifications that the operation should be canceled. + /// A that contains the name of the role. + public virtual Task GetRoleNameAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Sets the name of a role in the store as an asynchronous operation. - /// - /// The role whose name should be set. - /// The name of the role. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual Task SetRoleNameAsync([NotNull] IdentityRole role, string roleName, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(role, nameof(role)); - Check.NotNull(role, nameof(role)); + return Task.FromResult(role.Name); + } - role.ChangeName(roleName); - return Task.CompletedTask; - } + /// + /// Sets the name of a role in the store as an asynchronous operation. + /// + /// The role whose name should be set. + /// The name of the role. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual Task SetRoleNameAsync([NotNull] IdentityRole role, string roleName, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Finds the role who has the specified ID as an asynchronous operation. - /// - /// The role ID to look for. - /// The used to propagate notifications that the operation should be canceled. - /// A that result of the look up. - public virtual Task FindByIdAsync(string id, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(role, nameof(role)); - return RoleRepository.FindAsync(Guid.Parse(id), cancellationToken: cancellationToken); - } + role.ChangeName(roleName); + return Task.CompletedTask; + } - /// - /// Finds the role who has the specified normalized name as an asynchronous operation. - /// - /// The normalized role name to look for. - /// The used to propagate notifications that the operation should be canceled. - /// A that result of the look up. - public virtual Task FindByNameAsync([NotNull] string normalizedName, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Finds the role who has the specified ID as an asynchronous operation. + /// + /// The role ID to look for. + /// The used to propagate notifications that the operation should be canceled. + /// A that result of the look up. + public virtual Task FindByIdAsync(string id, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(normalizedName, nameof(normalizedName)); + return RoleRepository.FindAsync(Guid.Parse(id), cancellationToken: cancellationToken); + } - return RoleRepository.FindByNormalizedNameAsync(normalizedName, cancellationToken: cancellationToken); - } + /// + /// Finds the role who has the specified normalized name as an asynchronous operation. + /// + /// The normalized role name to look for. + /// The used to propagate notifications that the operation should be canceled. + /// A that result of the look up. + public virtual Task FindByNameAsync([NotNull] string normalizedName, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Get a role's normalized name as an asynchronous operation. - /// - /// The role whose normalized name should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// A that contains the name of the role. - public virtual Task GetNormalizedRoleNameAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(normalizedName, nameof(normalizedName)); - Check.NotNull(role, nameof(role)); + return RoleRepository.FindByNormalizedNameAsync(normalizedName, cancellationToken: cancellationToken); + } - return Task.FromResult(role.NormalizedName); - } + /// + /// Get a role's normalized name as an asynchronous operation. + /// + /// The role whose normalized name should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// A that contains the name of the role. + public virtual Task GetNormalizedRoleNameAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Set a role's normalized name as an asynchronous operation. - /// - /// The role whose normalized name should be set. - /// The normalized name to set - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual Task SetNormalizedRoleNameAsync([NotNull] IdentityRole role, string normalizedName, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(role, nameof(role)); - Check.NotNull(role, nameof(role)); + return Task.FromResult(role.NormalizedName); + } - role.NormalizedName = normalizedName; + /// + /// Set a role's normalized name as an asynchronous operation. + /// + /// The role whose normalized name should be set. + /// The normalized name to set + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual Task SetNormalizedRoleNameAsync([NotNull] IdentityRole role, string normalizedName, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return Task.CompletedTask; - } + Check.NotNull(role, nameof(role)); - /// - /// Dispose the stores - /// - public virtual void Dispose() - { - } + role.NormalizedName = normalizedName; - /// - /// Get the claims associated with the specified as an asynchronous operation. - /// - /// The role whose claims should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// A that contains the claims granted to a role. - public virtual async Task> GetClaimsAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return Task.CompletedTask; + } + + /// + /// Dispose the stores + /// + public virtual void Dispose() + { + } - Check.NotNull(role, nameof(role)); + /// + /// Get the claims associated with the specified as an asynchronous operation. + /// + /// The role whose claims should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// A that contains the claims granted to a role. + public virtual async Task> GetClaimsAsync([NotNull] IdentityRole role, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - await RoleRepository.EnsureCollectionLoadedAsync(role, r => r.Claims, cancellationToken); + Check.NotNull(role, nameof(role)); - return role.Claims.Select(c => c.ToClaim()).ToList(); - } + await RoleRepository.EnsureCollectionLoadedAsync(role, r => r.Claims, cancellationToken); - /// - /// Adds the given to the specified . - /// - /// The role to add the claim to. - /// The claim to add to the role. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task AddClaimAsync([NotNull] IdentityRole role, [NotNull] Claim claim, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return role.Claims.Select(c => c.ToClaim()).ToList(); + } - Check.NotNull(role, nameof(role)); - Check.NotNull(claim, nameof(claim)); + /// + /// Adds the given to the specified . + /// + /// The role to add the claim to. + /// The claim to add to the role. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task AddClaimAsync([NotNull] IdentityRole role, [NotNull] Claim claim, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - await RoleRepository.EnsureCollectionLoadedAsync(role, r => r.Claims, cancellationToken); + Check.NotNull(role, nameof(role)); + Check.NotNull(claim, nameof(claim)); - role.AddClaim(GuidGenerator, claim); - } + await RoleRepository.EnsureCollectionLoadedAsync(role, r => r.Claims, cancellationToken); - /// - /// Removes the given from the specified . - /// - /// The role to remove the claim from. - /// The claim to remove from the role. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task RemoveClaimAsync([NotNull] IdentityRole role, [NotNull] Claim claim, CancellationToken cancellationToken = default) - { - Check.NotNull(role, nameof(role)); - Check.NotNull(claim, nameof(claim)); + role.AddClaim(GuidGenerator, claim); + } + + /// + /// Removes the given from the specified . + /// + /// The role to remove the claim from. + /// The claim to remove from the role. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task RemoveClaimAsync([NotNull] IdentityRole role, [NotNull] Claim claim, CancellationToken cancellationToken = default) + { + Check.NotNull(role, nameof(role)); + Check.NotNull(claim, nameof(claim)); - await RoleRepository.EnsureCollectionLoadedAsync(role, r => r.Claims, cancellationToken); + await RoleRepository.EnsureCollectionLoadedAsync(role, r => r.Claims, cancellationToken); - role.RemoveClaim(claim); - } + role.RemoveClaim(claim); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLog.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLog.cs index 729b82b7fc..c801c263e6 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLog.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLog.cs @@ -4,63 +4,62 @@ using Volo.Abp.Guids; using Volo.Abp.MultiTenancy; using Volo.Abp.SecurityLog; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentitySecurityLog : AggregateRoot, IMultiTenant { - public class IdentitySecurityLog : AggregateRoot, IMultiTenant - { - public Guid? TenantId { get; protected set; } + public Guid? TenantId { get; protected set; } - public string ApplicationName { get; protected set; } + public string ApplicationName { get; protected set; } - public string Identity { get; protected set; } + public string Identity { get; protected set; } - public string Action { get; protected set; } + public string Action { get; protected set; } - public Guid? UserId { get; protected set; } + public Guid? UserId { get; protected set; } - public string UserName { get; protected set; } + public string UserName { get; protected set; } - public string TenantName { get; protected set; } + public string TenantName { get; protected set; } - public string ClientId { get; protected set; } + public string ClientId { get; protected set; } - public string CorrelationId { get; protected set; } + public string CorrelationId { get; protected set; } - public string ClientIpAddress { get; protected set; } + public string ClientIpAddress { get; protected set; } - public string BrowserInfo { get; protected set; } + public string BrowserInfo { get; protected set; } - public DateTime CreationTime { get; protected set; } + public DateTime CreationTime { get; protected set; } - protected IdentitySecurityLog() - { + protected IdentitySecurityLog() + { - } + } - public IdentitySecurityLog(IGuidGenerator guidGenerator, SecurityLogInfo securityLogInfo) - : base(guidGenerator.Create()) - { - TenantId = securityLogInfo.TenantId; - TenantName = securityLogInfo.TenantName.Truncate(IdentitySecurityLogConsts.MaxTenantNameLength); + public IdentitySecurityLog(IGuidGenerator guidGenerator, SecurityLogInfo securityLogInfo) + : base(guidGenerator.Create()) + { + TenantId = securityLogInfo.TenantId; + TenantName = securityLogInfo.TenantName.Truncate(IdentitySecurityLogConsts.MaxTenantNameLength); - ApplicationName = securityLogInfo.ApplicationName.Truncate(IdentitySecurityLogConsts.MaxApplicationNameLength); - Identity = securityLogInfo.Identity.Truncate(IdentitySecurityLogConsts.MaxIdentityLength); - Action = securityLogInfo.Action.Truncate(IdentitySecurityLogConsts.MaxActionLength); + ApplicationName = securityLogInfo.ApplicationName.Truncate(IdentitySecurityLogConsts.MaxApplicationNameLength); + Identity = securityLogInfo.Identity.Truncate(IdentitySecurityLogConsts.MaxIdentityLength); + Action = securityLogInfo.Action.Truncate(IdentitySecurityLogConsts.MaxActionLength); - UserId = securityLogInfo.UserId; - UserName = securityLogInfo.UserName.Truncate(IdentitySecurityLogConsts.MaxUserNameLength); + UserId = securityLogInfo.UserId; + UserName = securityLogInfo.UserName.Truncate(IdentitySecurityLogConsts.MaxUserNameLength); - CreationTime = securityLogInfo.CreationTime; + CreationTime = securityLogInfo.CreationTime; - ClientIpAddress = securityLogInfo.ClientIpAddress.Truncate(IdentitySecurityLogConsts.MaxClientIpAddressLength); - ClientId = securityLogInfo.ClientId.Truncate(IdentitySecurityLogConsts.MaxClientIdLength); - CorrelationId = securityLogInfo.CorrelationId.Truncate(IdentitySecurityLogConsts.MaxCorrelationIdLength); - BrowserInfo = securityLogInfo.BrowserInfo.Truncate(IdentitySecurityLogConsts.MaxBrowserInfoLength); + ClientIpAddress = securityLogInfo.ClientIpAddress.Truncate(IdentitySecurityLogConsts.MaxClientIpAddressLength); + ClientId = securityLogInfo.ClientId.Truncate(IdentitySecurityLogConsts.MaxClientIdLength); + CorrelationId = securityLogInfo.CorrelationId.Truncate(IdentitySecurityLogConsts.MaxCorrelationIdLength); + BrowserInfo = securityLogInfo.BrowserInfo.Truncate(IdentitySecurityLogConsts.MaxBrowserInfoLength); - foreach (var property in securityLogInfo.ExtraProperties) - { - ExtraProperties.Add(property.Key, property.Value); - } + foreach (var property in securityLogInfo.ExtraProperties) + { + ExtraProperties.Add(property.Key, property.Value); } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogContext.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogContext.cs index 740688ff84..305e9328e0 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogContext.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogContext.cs @@ -1,30 +1,29 @@ using System; using System.Collections.Generic; -namespace Volo.Abp.Identity -{ - public class IdentitySecurityLogContext - { - public string Identity { get; set; } +namespace Volo.Abp.Identity; - public string Action { get; set; } +public class IdentitySecurityLogContext +{ + public string Identity { get; set; } - public string UserName { get; set; } + public string Action { get; set; } - public string ClientId { get; set; } + public string UserName { get; set; } - public Dictionary ExtraProperties { get; } + public string ClientId { get; set; } - public IdentitySecurityLogContext() - { - ExtraProperties = new Dictionary(); - } + public Dictionary ExtraProperties { get; } - public virtual IdentitySecurityLogContext WithProperty(string key, object value) - { - ExtraProperties[key] = value; - return this; - } + public IdentitySecurityLogContext() + { + ExtraProperties = new Dictionary(); + } + public virtual IdentitySecurityLogContext WithProperty(string key, object value) + { + ExtraProperties[key] = value; + return this; } + } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogManager.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogManager.cs index bdad21df13..b04baeeeb0 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogManager.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogManager.cs @@ -6,78 +6,77 @@ using Volo.Abp.Security.Claims; using Volo.Abp.SecurityLog; using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentitySecurityLogManager : ITransientDependency { - public class IdentitySecurityLogManager : ITransientDependency + protected ISecurityLogManager SecurityLogManager { get; } + protected IdentityUserManager UserManager { get; } + protected ICurrentPrincipalAccessor CurrentPrincipalAccessor { get; } + protected IUserClaimsPrincipalFactory UserClaimsPrincipalFactory { get; } + protected ICurrentUser CurrentUser { get; } + + public IdentitySecurityLogManager( + ISecurityLogManager securityLogManager, + IdentityUserManager userManager, + ICurrentPrincipalAccessor currentPrincipalAccessor, + IUserClaimsPrincipalFactory userClaimsPrincipalFactory, + ICurrentUser currentUser) { - protected ISecurityLogManager SecurityLogManager { get; } - protected IdentityUserManager UserManager { get; } - protected ICurrentPrincipalAccessor CurrentPrincipalAccessor { get; } - protected IUserClaimsPrincipalFactory UserClaimsPrincipalFactory { get; } - protected ICurrentUser CurrentUser { get; } + SecurityLogManager = securityLogManager; + UserManager = userManager; + CurrentPrincipalAccessor = currentPrincipalAccessor; + UserClaimsPrincipalFactory = userClaimsPrincipalFactory; + CurrentUser = currentUser; + } - public IdentitySecurityLogManager( - ISecurityLogManager securityLogManager, - IdentityUserManager userManager, - ICurrentPrincipalAccessor currentPrincipalAccessor, - IUserClaimsPrincipalFactory userClaimsPrincipalFactory, - ICurrentUser currentUser) + public async Task SaveAsync(IdentitySecurityLogContext context) + { + Action securityLogAction = securityLog => { - SecurityLogManager = securityLogManager; - UserManager = userManager; - CurrentPrincipalAccessor = currentPrincipalAccessor; - UserClaimsPrincipalFactory = userClaimsPrincipalFactory; - CurrentUser = currentUser; - } + securityLog.Identity = context.Identity; + securityLog.Action = context.Action; - public async Task SaveAsync(IdentitySecurityLogContext context) - { - Action securityLogAction = securityLog => + if (!context.UserName.IsNullOrWhiteSpace()) { - securityLog.Identity = context.Identity; - securityLog.Action = context.Action; - - if (!context.UserName.IsNullOrWhiteSpace()) - { - securityLog.UserName = context.UserName; - } + securityLog.UserName = context.UserName; + } - if (!context.ClientId.IsNullOrWhiteSpace()) - { - securityLog.ClientId = context.ClientId; - } + if (!context.ClientId.IsNullOrWhiteSpace()) + { + securityLog.ClientId = context.ClientId; + } - foreach (var property in context.ExtraProperties) - { - securityLog.ExtraProperties[property.Key] = property.Value; - } - }; + foreach (var property in context.ExtraProperties) + { + securityLog.ExtraProperties[property.Key] = property.Value; + } + }; - if (CurrentUser.IsAuthenticated) + if (CurrentUser.IsAuthenticated) + { + await SecurityLogManager.SaveAsync(securityLogAction); + } + else + { + if (context.UserName.IsNullOrWhiteSpace()) { await SecurityLogManager.SaveAsync(securityLogAction); } else { - if (context.UserName.IsNullOrWhiteSpace()) + var user = await UserManager.FindByNameAsync(context.UserName); + if (user != null) { - await SecurityLogManager.SaveAsync(securityLogAction); - } - else - { - var user = await UserManager.FindByNameAsync(context.UserName); - if (user != null) - { - using (CurrentPrincipalAccessor.Change(await UserClaimsPrincipalFactory.CreateAsync(user))) - { - await SecurityLogManager.SaveAsync(securityLogAction); - } - } - else + using (CurrentPrincipalAccessor.Change(await UserClaimsPrincipalFactory.CreateAsync(user))) { await SecurityLogManager.SaveAsync(securityLogAction); } } + else + { + await SecurityLogManager.SaveAsync(securityLogAction); + } } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogStore.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogStore.cs index 17e3c20794..cf354a72c7 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogStore.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentitySecurityLogStore.cs @@ -6,44 +6,43 @@ using Volo.Abp.Guids; using Volo.Abp.SecurityLog; using Volo.Abp.Uow; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[Dependency(ReplaceServices = true)] +public class IdentitySecurityLogStore : ISecurityLogStore, ITransientDependency { - [Dependency(ReplaceServices = true)] - public class IdentitySecurityLogStore : ISecurityLogStore, ITransientDependency - { - public ILogger Logger { get; set; } + public ILogger Logger { get; set; } - protected AbpSecurityLogOptions SecurityLogOptions { get; } - protected IIdentitySecurityLogRepository IdentitySecurityLogRepository { get; } - protected IGuidGenerator GuidGenerator { get; } - protected IUnitOfWorkManager UnitOfWorkManager { get; } + protected AbpSecurityLogOptions SecurityLogOptions { get; } + protected IIdentitySecurityLogRepository IdentitySecurityLogRepository { get; } + protected IGuidGenerator GuidGenerator { get; } + protected IUnitOfWorkManager UnitOfWorkManager { get; } - public IdentitySecurityLogStore( - ILogger logger, - IOptions securityLogOptions, - IIdentitySecurityLogRepository identitySecurityLogRepository, - IGuidGenerator guidGenerator, - IUnitOfWorkManager unitOfWorkManager) + public IdentitySecurityLogStore( + ILogger logger, + IOptions securityLogOptions, + IIdentitySecurityLogRepository identitySecurityLogRepository, + IGuidGenerator guidGenerator, + IUnitOfWorkManager unitOfWorkManager) + { + Logger = logger; + SecurityLogOptions = securityLogOptions.Value; + IdentitySecurityLogRepository = identitySecurityLogRepository; + GuidGenerator = guidGenerator; + UnitOfWorkManager = unitOfWorkManager; + } + + public async Task SaveAsync(SecurityLogInfo securityLogInfo) + { + if (!SecurityLogOptions.IsEnabled) { - Logger = logger; - SecurityLogOptions = securityLogOptions.Value; - IdentitySecurityLogRepository = identitySecurityLogRepository; - GuidGenerator = guidGenerator; - UnitOfWorkManager = unitOfWorkManager; + return; } - public async Task SaveAsync(SecurityLogInfo securityLogInfo) + using (var uow = UnitOfWorkManager.Begin(requiresNew: true)) { - if (!SecurityLogOptions.IsEnabled) - { - return; - } - - using (var uow = UnitOfWorkManager.Begin(requiresNew: true)) - { - await IdentitySecurityLogRepository.InsertAsync(new IdentitySecurityLog(GuidGenerator, securityLogInfo)); - await uow.CompleteAsync(); - } + await IdentitySecurityLogRepository.InsertAsync(new IdentitySecurityLog(GuidGenerator, securityLogInfo)); + await uow.CompleteAsync(); } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUser.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUser.cs index befa288fda..834f0d8d7a 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUser.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUser.cs @@ -10,362 +10,361 @@ using Volo.Abp.Domain.Entities.Auditing; using Volo.Abp.Guids; using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUser : FullAuditedAggregateRoot, IUser { - public class IdentityUser : FullAuditedAggregateRoot, IUser + public virtual Guid? TenantId { get; protected set; } + + /// + /// Gets or sets the user name for this user. + /// + public virtual string UserName { get; protected internal set; } + + /// + /// Gets or sets the normalized user name for this user. + /// + [DisableAuditing] + public virtual string NormalizedUserName { get; protected internal set; } + + /// + /// Gets or sets the Name for the user. + /// + [CanBeNull] + public virtual string Name { get; set; } + + /// + /// Gets or sets the Surname for the user. + /// + [CanBeNull] + public virtual string Surname { get; set; } + + /// + /// Gets or sets the email address for this user. + /// + public virtual string Email { get; protected internal set; } + + /// + /// Gets or sets the normalized email address for this user. + /// + [DisableAuditing] + public virtual string NormalizedEmail { get; protected internal set; } + + /// + /// Gets or sets a flag indicating if a user has confirmed their email address. + /// + /// True if the email address has been confirmed, otherwise false. + public virtual bool EmailConfirmed { get; protected internal set; } + + /// + /// Gets or sets a salted and hashed representation of the password for this user. + /// + [DisableAuditing] + public virtual string PasswordHash { get; protected internal set; } + + /// + /// A random value that must change whenever a users credentials change (password changed, login removed) + /// + [DisableAuditing] + public virtual string SecurityStamp { get; protected internal set; } + + public virtual bool IsExternal { get; set; } + + /// + /// Gets or sets a telephone number for the user. + /// + [CanBeNull] + public virtual string PhoneNumber { get; protected internal set; } + + /// + /// Gets or sets a flag indicating if a user has confirmed their telephone address. + /// + /// True if the telephone number has been confirmed, otherwise false. + public virtual bool PhoneNumberConfirmed { get; protected internal set; } + + /// + /// Gets or sets a flag indicating if the user is active. + /// + public virtual bool IsActive { get; protected internal set; } + + /// + /// Gets or sets a flag indicating if two factor authentication is enabled for this user. + /// + /// True if 2fa is enabled, otherwise false. + public virtual bool TwoFactorEnabled { get; protected internal set; } + + /// + /// Gets or sets the date and time, in UTC, when any user lockout ends. + /// + /// + /// A value in the past means the user is not locked out. + /// + public virtual DateTimeOffset? LockoutEnd { get; protected internal set; } + + /// + /// Gets or sets a flag indicating if the user could be locked out. + /// + /// True if the user could be locked out, otherwise false. + public virtual bool LockoutEnabled { get; protected internal set; } + + /// + /// Gets or sets the number of failed login attempts for the current user. + /// + public virtual int AccessFailedCount { get; protected internal set; } + + //TODO: Can we make collections readonly collection, which will provide encapsulation. But... can work for all ORMs? + + /// + /// Navigation property for the roles this user belongs to. + /// + public virtual ICollection Roles { get; protected set; } + + /// + /// Navigation property for the claims this user possesses. + /// + public virtual ICollection Claims { get; protected set; } + + /// + /// Navigation property for this users login accounts. + /// + public virtual ICollection Logins { get; protected set; } + + /// + /// Navigation property for this users tokens. + /// + public virtual ICollection Tokens { get; protected set; } + + /// + /// Navigation property for this organization units. + /// + public virtual ICollection OrganizationUnits { get; protected set; } + + protected IdentityUser() { - public virtual Guid? TenantId { get; protected set; } - - /// - /// Gets or sets the user name for this user. - /// - public virtual string UserName { get; protected internal set; } - - /// - /// Gets or sets the normalized user name for this user. - /// - [DisableAuditing] - public virtual string NormalizedUserName { get; protected internal set; } - - /// - /// Gets or sets the Name for the user. - /// - [CanBeNull] - public virtual string Name { get; set; } - - /// - /// Gets or sets the Surname for the user. - /// - [CanBeNull] - public virtual string Surname { get; set; } - - /// - /// Gets or sets the email address for this user. - /// - public virtual string Email { get; protected internal set; } - - /// - /// Gets or sets the normalized email address for this user. - /// - [DisableAuditing] - public virtual string NormalizedEmail { get; protected internal set; } - - /// - /// Gets or sets a flag indicating if a user has confirmed their email address. - /// - /// True if the email address has been confirmed, otherwise false. - public virtual bool EmailConfirmed { get; protected internal set; } - - /// - /// Gets or sets a salted and hashed representation of the password for this user. - /// - [DisableAuditing] - public virtual string PasswordHash { get; protected internal set; } - - /// - /// A random value that must change whenever a users credentials change (password changed, login removed) - /// - [DisableAuditing] - public virtual string SecurityStamp { get; protected internal set; } - - public virtual bool IsExternal { get; set; } - - /// - /// Gets or sets a telephone number for the user. - /// - [CanBeNull] - public virtual string PhoneNumber { get; protected internal set; } - - /// - /// Gets or sets a flag indicating if a user has confirmed their telephone address. - /// - /// True if the telephone number has been confirmed, otherwise false. - public virtual bool PhoneNumberConfirmed { get; protected internal set; } - - /// - /// Gets or sets a flag indicating if the user is active. - /// - public virtual bool IsActive { get; protected internal set; } - - /// - /// Gets or sets a flag indicating if two factor authentication is enabled for this user. - /// - /// True if 2fa is enabled, otherwise false. - public virtual bool TwoFactorEnabled { get; protected internal set; } - - /// - /// Gets or sets the date and time, in UTC, when any user lockout ends. - /// - /// - /// A value in the past means the user is not locked out. - /// - public virtual DateTimeOffset? LockoutEnd { get; protected internal set; } - - /// - /// Gets or sets a flag indicating if the user could be locked out. - /// - /// True if the user could be locked out, otherwise false. - public virtual bool LockoutEnabled { get; protected internal set; } - - /// - /// Gets or sets the number of failed login attempts for the current user. - /// - public virtual int AccessFailedCount { get; protected internal set; } - - //TODO: Can we make collections readonly collection, which will provide encapsulation. But... can work for all ORMs? - - /// - /// Navigation property for the roles this user belongs to. - /// - public virtual ICollection Roles { get; protected set; } - - /// - /// Navigation property for the claims this user possesses. - /// - public virtual ICollection Claims { get; protected set; } - - /// - /// Navigation property for this users login accounts. - /// - public virtual ICollection Logins { get; protected set; } - - /// - /// Navigation property for this users tokens. - /// - public virtual ICollection Tokens { get; protected set; } - - /// - /// Navigation property for this organization units. - /// - public virtual ICollection OrganizationUnits { get; protected set; } - - protected IdentityUser() - { - } + } - public IdentityUser( - Guid id, - [NotNull] string userName, - [NotNull] string email, - Guid? tenantId = null) - : base(id) - { - Check.NotNull(userName, nameof(userName)); - Check.NotNull(email, nameof(email)); - - TenantId = tenantId; - UserName = userName; - NormalizedUserName = userName.ToUpperInvariant(); - Email = email; - NormalizedEmail = email.ToUpperInvariant(); - ConcurrencyStamp = Guid.NewGuid().ToString(); - SecurityStamp = Guid.NewGuid().ToString(); - IsActive = true; - - Roles = new Collection(); - Claims = new Collection(); - Logins = new Collection(); - Tokens = new Collection(); - OrganizationUnits = new Collection(); - } + public IdentityUser( + Guid id, + [NotNull] string userName, + [NotNull] string email, + Guid? tenantId = null) + : base(id) + { + Check.NotNull(userName, nameof(userName)); + Check.NotNull(email, nameof(email)); + + TenantId = tenantId; + UserName = userName; + NormalizedUserName = userName.ToUpperInvariant(); + Email = email; + NormalizedEmail = email.ToUpperInvariant(); + ConcurrencyStamp = Guid.NewGuid().ToString(); + SecurityStamp = Guid.NewGuid().ToString(); + IsActive = true; + + Roles = new Collection(); + Claims = new Collection(); + Logins = new Collection(); + Tokens = new Collection(); + OrganizationUnits = new Collection(); + } + + public virtual void AddRole(Guid roleId) + { + Check.NotNull(roleId, nameof(roleId)); - public virtual void AddRole(Guid roleId) + if (IsInRole(roleId)) { - Check.NotNull(roleId, nameof(roleId)); + return; + } - if (IsInRole(roleId)) - { - return; - } + Roles.Add(new IdentityUserRole(Id, roleId, TenantId)); + } - Roles.Add(new IdentityUserRole(Id, roleId, TenantId)); - } + public virtual void RemoveRole(Guid roleId) + { + Check.NotNull(roleId, nameof(roleId)); - public virtual void RemoveRole(Guid roleId) + if (!IsInRole(roleId)) { - Check.NotNull(roleId, nameof(roleId)); + return; + } - if (!IsInRole(roleId)) - { - return; - } + Roles.RemoveAll(r => r.RoleId == roleId); + } - Roles.RemoveAll(r => r.RoleId == roleId); - } + public virtual bool IsInRole(Guid roleId) + { + Check.NotNull(roleId, nameof(roleId)); - public virtual bool IsInRole(Guid roleId) - { - Check.NotNull(roleId, nameof(roleId)); + return Roles.Any(r => r.RoleId == roleId); + } - return Roles.Any(r => r.RoleId == roleId); - } + public virtual void AddClaim([NotNull] IGuidGenerator guidGenerator, [NotNull] Claim claim) + { + Check.NotNull(guidGenerator, nameof(guidGenerator)); + Check.NotNull(claim, nameof(claim)); - public virtual void AddClaim([NotNull] IGuidGenerator guidGenerator, [NotNull] Claim claim) - { - Check.NotNull(guidGenerator, nameof(guidGenerator)); - Check.NotNull(claim, nameof(claim)); + Claims.Add(new IdentityUserClaim(guidGenerator.Create(), Id, claim, TenantId)); + } - Claims.Add(new IdentityUserClaim(guidGenerator.Create(), Id, claim, TenantId)); - } + public virtual void AddClaims([NotNull] IGuidGenerator guidGenerator, [NotNull] IEnumerable claims) + { + Check.NotNull(guidGenerator, nameof(guidGenerator)); + Check.NotNull(claims, nameof(claims)); - public virtual void AddClaims([NotNull] IGuidGenerator guidGenerator, [NotNull] IEnumerable claims) + foreach (var claim in claims) { - Check.NotNull(guidGenerator, nameof(guidGenerator)); - Check.NotNull(claims, nameof(claims)); - - foreach (var claim in claims) - { - AddClaim(guidGenerator, claim); - } + AddClaim(guidGenerator, claim); } + } - public virtual IdentityUserClaim FindClaim([NotNull] Claim claim) - { - Check.NotNull(claim, nameof(claim)); + public virtual IdentityUserClaim FindClaim([NotNull] Claim claim) + { + Check.NotNull(claim, nameof(claim)); - return Claims.FirstOrDefault(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value); - } + return Claims.FirstOrDefault(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value); + } + + public virtual void ReplaceClaim([NotNull] Claim claim, [NotNull] Claim newClaim) + { + Check.NotNull(claim, nameof(claim)); + Check.NotNull(newClaim, nameof(newClaim)); - public virtual void ReplaceClaim([NotNull] Claim claim, [NotNull] Claim newClaim) + var userClaims = Claims.Where(uc => uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type); + foreach (var userClaim in userClaims) { - Check.NotNull(claim, nameof(claim)); - Check.NotNull(newClaim, nameof(newClaim)); - - var userClaims = Claims.Where(uc => uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type); - foreach (var userClaim in userClaims) - { - userClaim.SetClaim(newClaim); - } + userClaim.SetClaim(newClaim); } + } - public virtual void RemoveClaims([NotNull] IEnumerable claims) - { - Check.NotNull(claims, nameof(claims)); + public virtual void RemoveClaims([NotNull] IEnumerable claims) + { + Check.NotNull(claims, nameof(claims)); - foreach (var claim in claims) - { - RemoveClaim(claim); - } + foreach (var claim in claims) + { + RemoveClaim(claim); } + } - public virtual void RemoveClaim([NotNull] Claim claim) - { - Check.NotNull(claim, nameof(claim)); + public virtual void RemoveClaim([NotNull] Claim claim) + { + Check.NotNull(claim, nameof(claim)); - Claims.RemoveAll(c => c.ClaimValue == claim.Value && c.ClaimType == claim.Type); - } + Claims.RemoveAll(c => c.ClaimValue == claim.Value && c.ClaimType == claim.Type); + } - public virtual void AddLogin([NotNull] UserLoginInfo login) - { - Check.NotNull(login, nameof(login)); + public virtual void AddLogin([NotNull] UserLoginInfo login) + { + Check.NotNull(login, nameof(login)); - Logins.Add(new IdentityUserLogin(Id, login, TenantId)); - } + Logins.Add(new IdentityUserLogin(Id, login, TenantId)); + } - public virtual void RemoveLogin([NotNull] string loginProvider, [NotNull] string providerKey) - { - Check.NotNull(loginProvider, nameof(loginProvider)); - Check.NotNull(providerKey, nameof(providerKey)); + public virtual void RemoveLogin([NotNull] string loginProvider, [NotNull] string providerKey) + { + Check.NotNull(loginProvider, nameof(loginProvider)); + Check.NotNull(providerKey, nameof(providerKey)); - Logins.RemoveAll(userLogin => - userLogin.LoginProvider == loginProvider && userLogin.ProviderKey == providerKey); - } + Logins.RemoveAll(userLogin => + userLogin.LoginProvider == loginProvider && userLogin.ProviderKey == providerKey); + } - [CanBeNull] - public virtual IdentityUserToken FindToken(string loginProvider, string name) - { - return Tokens.FirstOrDefault(t => t.LoginProvider == loginProvider && t.Name == name); - } + [CanBeNull] + public virtual IdentityUserToken FindToken(string loginProvider, string name) + { + return Tokens.FirstOrDefault(t => t.LoginProvider == loginProvider && t.Name == name); + } - public virtual void SetToken(string loginProvider, string name, string value) + public virtual void SetToken(string loginProvider, string name, string value) + { + var token = FindToken(loginProvider, name); + if (token == null) { - var token = FindToken(loginProvider, name); - if (token == null) - { - Tokens.Add(new IdentityUserToken(Id, loginProvider, name, value, TenantId)); - } - else - { - token.Value = value; - } + Tokens.Add(new IdentityUserToken(Id, loginProvider, name, value, TenantId)); } - - public virtual void RemoveToken(string loginProvider, string name) + else { - Tokens.RemoveAll(t => t.LoginProvider == loginProvider && t.Name == name); + token.Value = value; } + } - public virtual void AddOrganizationUnit(Guid organizationUnitId) - { - if (IsInOrganizationUnit(organizationUnitId)) - { - return; - } - - OrganizationUnits.Add( - new IdentityUserOrganizationUnit( - Id, - organizationUnitId, - TenantId - ) - ); - } + public virtual void RemoveToken(string loginProvider, string name) + { + Tokens.RemoveAll(t => t.LoginProvider == loginProvider && t.Name == name); + } - public virtual void RemoveOrganizationUnit(Guid organizationUnitId) + public virtual void AddOrganizationUnit(Guid organizationUnitId) + { + if (IsInOrganizationUnit(organizationUnitId)) { - if (!IsInOrganizationUnit(organizationUnitId)) - { - return; - } - - OrganizationUnits.RemoveAll( - ou => ou.OrganizationUnitId == organizationUnitId - ); + return; } - public virtual bool IsInOrganizationUnit(Guid organizationUnitId) - { - return OrganizationUnits.Any( - ou => ou.OrganizationUnitId == organizationUnitId - ); - } + OrganizationUnits.Add( + new IdentityUserOrganizationUnit( + Id, + organizationUnitId, + TenantId + ) + ); + } - /// - /// Use for regular email confirmation. - /// Using this skips the confirmation process and directly sets the . - /// - public virtual void SetEmailConfirmed(bool confirmed) + public virtual void RemoveOrganizationUnit(Guid organizationUnitId) + { + if (!IsInOrganizationUnit(organizationUnitId)) { - EmailConfirmed = confirmed; + return; } - public virtual void SetPhoneNumberConfirmed(bool confirmed) - { - PhoneNumberConfirmed = confirmed; - } + OrganizationUnits.RemoveAll( + ou => ou.OrganizationUnitId == organizationUnitId + ); + } - /// - /// Normally use to change the phone number - /// in the application code. - /// This method is to directly set it with a confirmation information. - /// - /// - /// - /// - public void SetPhoneNumber(string phoneNumber, bool confirmed) - { - PhoneNumber = phoneNumber; - PhoneNumberConfirmed = !phoneNumber.IsNullOrWhiteSpace() && confirmed; - } + public virtual bool IsInOrganizationUnit(Guid organizationUnitId) + { + return OrganizationUnits.Any( + ou => ou.OrganizationUnitId == organizationUnitId + ); + } - public virtual void SetIsActive(bool isActive) - { - IsActive = isActive; - } + /// + /// Use for regular email confirmation. + /// Using this skips the confirmation process and directly sets the . + /// + public virtual void SetEmailConfirmed(bool confirmed) + { + EmailConfirmed = confirmed; + } - public override string ToString() - { - return $"{base.ToString()}, UserName = {UserName}"; - } + public virtual void SetPhoneNumberConfirmed(bool confirmed) + { + PhoneNumberConfirmed = confirmed; + } + + /// + /// Normally use to change the phone number + /// in the application code. + /// This method is to directly set it with a confirmation information. + /// + /// + /// + /// + public void SetPhoneNumber(string phoneNumber, bool confirmed) + { + PhoneNumber = phoneNumber; + PhoneNumberConfirmed = !phoneNumber.IsNullOrWhiteSpace() && confirmed; + } + + public virtual void SetIsActive(bool isActive) + { + IsActive = isActive; + } + + public override string ToString() + { + return $"{base.ToString()}, UserName = {UserName}"; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserClaim.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserClaim.cs index d91db39b33..c64eec5a5b 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserClaim.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserClaim.cs @@ -2,33 +2,32 @@ using System; using System.Security.Claims; using JetBrains.Annotations; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Represents a claim that a user possesses. +/// +public class IdentityUserClaim : IdentityClaim { /// - /// Represents a claim that a user possesses. + /// Gets or sets the primary key of the user associated with this claim. /// - public class IdentityUserClaim : IdentityClaim - { - /// - /// Gets or sets the primary key of the user associated with this claim. - /// - public virtual Guid UserId { get; protected set; } + public virtual Guid UserId { get; protected set; } - protected IdentityUserClaim() - { + protected IdentityUserClaim() + { - } + } - protected internal IdentityUserClaim(Guid id, Guid userId, [NotNull] Claim claim, Guid? tenantId) - : base(id, claim, tenantId) - { - UserId = userId; - } + protected internal IdentityUserClaim(Guid id, Guid userId, [NotNull] Claim claim, Guid? tenantId) + : base(id, claim, tenantId) + { + UserId = userId; + } - public IdentityUserClaim(Guid id, Guid userId, [NotNull] string claimType, string claimValue, Guid? tenantId) - : base(id, claimType, claimValue, tenantId) - { - UserId = userId; - } + public IdentityUserClaim(Guid id, Guid userId, [NotNull] string claimType, string claimValue, Guid? tenantId) + : base(id, claimType, claimValue, tenantId) + { + UserId = userId; } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserLogin.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserLogin.cs index 8cfbf08879..1f81b620de 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserLogin.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserLogin.cs @@ -4,78 +4,77 @@ using Microsoft.AspNetCore.Identity; using Volo.Abp.Domain.Entities; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Represents a login and its associated provider for a user. +/// +public class IdentityUserLogin : Entity, IMultiTenant { + public virtual Guid? TenantId { get; protected set; } + /// - /// Represents a login and its associated provider for a user. + /// Gets or sets the of the primary key of the user associated with this login. /// - public class IdentityUserLogin : Entity, IMultiTenant - { - public virtual Guid? TenantId { get; protected set; } + public virtual Guid UserId { get; protected set; } - /// - /// Gets or sets the of the primary key of the user associated with this login. - /// - public virtual Guid UserId { get; protected set; } + /// + /// Gets or sets the login provider for the login (e.g. facebook, google) + /// + public virtual string LoginProvider { get; protected set; } - /// - /// Gets or sets the login provider for the login (e.g. facebook, google) - /// - public virtual string LoginProvider { get; protected set; } + /// + /// Gets or sets the unique provider identifier for this login. + /// + public virtual string ProviderKey { get; protected set; } - /// - /// Gets or sets the unique provider identifier for this login. - /// - public virtual string ProviderKey { get; protected set; } + /// + /// Gets or sets the friendly name used in a UI for this login. + /// + public virtual string ProviderDisplayName { get; protected set; } - /// - /// Gets or sets the friendly name used in a UI for this login. - /// - public virtual string ProviderDisplayName { get; protected set; } + protected IdentityUserLogin() + { - protected IdentityUserLogin() - { - - } + } - protected internal IdentityUserLogin( - Guid userId, - [NotNull] string loginProvider, - [NotNull] string providerKey, - string providerDisplayName, - Guid? tenantId) - { - Check.NotNull(loginProvider, nameof(loginProvider)); - Check.NotNull(providerKey, nameof(providerKey)); + protected internal IdentityUserLogin( + Guid userId, + [NotNull] string loginProvider, + [NotNull] string providerKey, + string providerDisplayName, + Guid? tenantId) + { + Check.NotNull(loginProvider, nameof(loginProvider)); + Check.NotNull(providerKey, nameof(providerKey)); - UserId = userId; - LoginProvider = loginProvider; - ProviderKey = providerKey; - ProviderDisplayName = providerDisplayName; - TenantId = tenantId; - } + UserId = userId; + LoginProvider = loginProvider; + ProviderKey = providerKey; + ProviderDisplayName = providerDisplayName; + TenantId = tenantId; + } - protected internal IdentityUserLogin( - Guid userId, - [NotNull] UserLoginInfo login, - Guid? tenantId) - : this( - userId, - login.LoginProvider, - login.ProviderKey, - login.ProviderDisplayName, - tenantId) - { - } + protected internal IdentityUserLogin( + Guid userId, + [NotNull] UserLoginInfo login, + Guid? tenantId) + : this( + userId, + login.LoginProvider, + login.ProviderKey, + login.ProviderDisplayName, + tenantId) + { + } - public virtual UserLoginInfo ToUserLoginInfo() - { - return new UserLoginInfo(LoginProvider, ProviderKey, ProviderDisplayName); - } + public virtual UserLoginInfo ToUserLoginInfo() + { + return new UserLoginInfo(LoginProvider, ProviderKey, ProviderDisplayName); + } - public override object[] GetKeys() - { - return new object[] {UserId, LoginProvider}; - } + public override object[] GetKeys() + { + return new object[] { UserId, LoginProvider }; } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserManager.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserManager.cs index 508728eea1..b1db0e01e5 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserManager.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserManager.cs @@ -15,243 +15,242 @@ using Volo.Abp.Uow; using Volo.Abp.Settings; using Volo.Abp.Identity.Settings; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUserManager : UserManager, IDomainService { - public class IdentityUserManager : UserManager, IDomainService + protected IIdentityRoleRepository RoleRepository { get; } + protected IIdentityUserRepository UserRepository { get; } + protected IOrganizationUnitRepository OrganizationUnitRepository { get; } + protected ISettingProvider SettingProvider { get; } + protected ICancellationTokenProvider CancellationTokenProvider { get; } + + protected override CancellationToken CancellationToken => CancellationTokenProvider.Token; + + public IdentityUserManager( + IdentityUserStore store, + IIdentityRoleRepository roleRepository, + IIdentityUserRepository userRepository, + IOptions optionsAccessor, + IPasswordHasher passwordHasher, + IEnumerable> userValidators, + IEnumerable> passwordValidators, + ILookupNormalizer keyNormalizer, + IdentityErrorDescriber errors, + IServiceProvider services, + ILogger logger, + ICancellationTokenProvider cancellationTokenProvider, + IOrganizationUnitRepository organizationUnitRepository, + ISettingProvider settingProvider) + : base( + store, + optionsAccessor, + passwordHasher, + userValidators, + passwordValidators, + keyNormalizer, + errors, + services, + logger) { - protected IIdentityRoleRepository RoleRepository { get; } - protected IIdentityUserRepository UserRepository { get; } - protected IOrganizationUnitRepository OrganizationUnitRepository { get; } - protected ISettingProvider SettingProvider { get; } - protected ICancellationTokenProvider CancellationTokenProvider { get; } - - protected override CancellationToken CancellationToken => CancellationTokenProvider.Token; - - public IdentityUserManager( - IdentityUserStore store, - IIdentityRoleRepository roleRepository, - IIdentityUserRepository userRepository, - IOptions optionsAccessor, - IPasswordHasher passwordHasher, - IEnumerable> userValidators, - IEnumerable> passwordValidators, - ILookupNormalizer keyNormalizer, - IdentityErrorDescriber errors, - IServiceProvider services, - ILogger logger, - ICancellationTokenProvider cancellationTokenProvider, - IOrganizationUnitRepository organizationUnitRepository, - ISettingProvider settingProvider) - : base( - store, - optionsAccessor, - passwordHasher, - userValidators, - passwordValidators, - keyNormalizer, - errors, - services, - logger) - { - OrganizationUnitRepository = organizationUnitRepository; - SettingProvider = settingProvider; - RoleRepository = roleRepository; - UserRepository = userRepository; - CancellationTokenProvider = cancellationTokenProvider; - } + OrganizationUnitRepository = organizationUnitRepository; + SettingProvider = settingProvider; + RoleRepository = roleRepository; + UserRepository = userRepository; + CancellationTokenProvider = cancellationTokenProvider; + } - public virtual async Task CreateAsync(IdentityUser user, string password, bool validatePassword) + public virtual async Task CreateAsync(IdentityUser user, string password, bool validatePassword) + { + var result = await UpdatePasswordHash(user, password, validatePassword); + if (!result.Succeeded) { - var result = await UpdatePasswordHash(user, password, validatePassword); - if (!result.Succeeded) - { - return result; - } - - return await CreateAsync(user); + return result; } - public virtual async Task GetByIdAsync(Guid id) - { - var user = await Store.FindByIdAsync(id.ToString(), CancellationToken); - if (user == null) - { - throw new EntityNotFoundException(typeof(IdentityUser), id); - } - - return user; - } + return await CreateAsync(user); + } - public virtual async Task SetRolesAsync([NotNull] IdentityUser user, - [NotNull] IEnumerable roleNames) + public virtual async Task GetByIdAsync(Guid id) + { + var user = await Store.FindByIdAsync(id.ToString(), CancellationToken); + if (user == null) { - Check.NotNull(user, nameof(user)); - Check.NotNull(roleNames, nameof(roleNames)); - - var currentRoleNames = await GetRolesAsync(user); + throw new EntityNotFoundException(typeof(IdentityUser), id); + } - var result = await RemoveFromRolesAsync(user, currentRoleNames.Except(roleNames).Distinct()); - if (!result.Succeeded) - { - return result; - } + return user; + } - result = await AddToRolesAsync(user, roleNames.Except(currentRoleNames).Distinct()); - if (!result.Succeeded) - { - return result; - } + public virtual async Task SetRolesAsync([NotNull] IdentityUser user, + [NotNull] IEnumerable roleNames) + { + Check.NotNull(user, nameof(user)); + Check.NotNull(roleNames, nameof(roleNames)); - return IdentityResult.Success; - } + var currentRoleNames = await GetRolesAsync(user); - public virtual async Task IsInOrganizationUnitAsync(Guid userId, Guid ouId) + var result = await RemoveFromRolesAsync(user, currentRoleNames.Except(roleNames).Distinct()); + if (!result.Succeeded) { - var user = await UserRepository.GetAsync(userId, cancellationToken: CancellationToken); - return user.IsInOrganizationUnit(ouId); + return result; } - public virtual async Task IsInOrganizationUnitAsync(IdentityUser user, OrganizationUnit ou) + result = await AddToRolesAsync(user, roleNames.Except(currentRoleNames).Distinct()); + if (!result.Succeeded) { - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.OrganizationUnits, - CancellationTokenProvider.Token); - return user.IsInOrganizationUnit(ou.Id); + return result; } - public virtual async Task AddToOrganizationUnitAsync(Guid userId, Guid ouId) - { - await AddToOrganizationUnitAsync( - await UserRepository.GetAsync(userId, cancellationToken: CancellationToken), - await OrganizationUnitRepository.GetAsync(ouId, cancellationToken: CancellationToken) - ); - } + return IdentityResult.Success; + } - public virtual async Task AddToOrganizationUnitAsync(IdentityUser user, OrganizationUnit ou) - { - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.OrganizationUnits, - CancellationTokenProvider.Token); + public virtual async Task IsInOrganizationUnitAsync(Guid userId, Guid ouId) + { + var user = await UserRepository.GetAsync(userId, cancellationToken: CancellationToken); + return user.IsInOrganizationUnit(ouId); + } - if (user.OrganizationUnits.Any(cou => cou.OrganizationUnitId == ou.Id)) - { - return; - } + public virtual async Task IsInOrganizationUnitAsync(IdentityUser user, OrganizationUnit ou) + { + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.OrganizationUnits, + CancellationTokenProvider.Token); + return user.IsInOrganizationUnit(ou.Id); + } - await CheckMaxUserOrganizationUnitMembershipCountAsync(user.OrganizationUnits.Count + 1); + public virtual async Task AddToOrganizationUnitAsync(Guid userId, Guid ouId) + { + await AddToOrganizationUnitAsync( + await UserRepository.GetAsync(userId, cancellationToken: CancellationToken), + await OrganizationUnitRepository.GetAsync(ouId, cancellationToken: CancellationToken) + ); + } - user.AddOrganizationUnit(ou.Id); - await UserRepository.UpdateAsync(user, cancellationToken: CancellationToken); - } + public virtual async Task AddToOrganizationUnitAsync(IdentityUser user, OrganizationUnit ou) + { + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.OrganizationUnits, + CancellationTokenProvider.Token); - public virtual async Task RemoveFromOrganizationUnitAsync(Guid userId, Guid ouId) + if (user.OrganizationUnits.Any(cou => cou.OrganizationUnitId == ou.Id)) { - var user = await UserRepository.GetAsync(userId, cancellationToken: CancellationToken); - user.RemoveOrganizationUnit(ouId); - await UserRepository.UpdateAsync(user, cancellationToken: CancellationToken); + return; } - public virtual async Task RemoveFromOrganizationUnitAsync(IdentityUser user, OrganizationUnit ou) - { - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.OrganizationUnits, - CancellationTokenProvider.Token); + await CheckMaxUserOrganizationUnitMembershipCountAsync(user.OrganizationUnits.Count + 1); - user.RemoveOrganizationUnit(ou.Id); - await UserRepository.UpdateAsync(user, cancellationToken: CancellationToken); - } + user.AddOrganizationUnit(ou.Id); + await UserRepository.UpdateAsync(user, cancellationToken: CancellationToken); + } - public virtual async Task SetOrganizationUnitsAsync(Guid userId, params Guid[] organizationUnitIds) - { - await SetOrganizationUnitsAsync( - await UserRepository.GetAsync(userId, cancellationToken: CancellationToken), - organizationUnitIds - ); - } + public virtual async Task RemoveFromOrganizationUnitAsync(Guid userId, Guid ouId) + { + var user = await UserRepository.GetAsync(userId, cancellationToken: CancellationToken); + user.RemoveOrganizationUnit(ouId); + await UserRepository.UpdateAsync(user, cancellationToken: CancellationToken); + } - public virtual async Task SetOrganizationUnitsAsync(IdentityUser user, params Guid[] organizationUnitIds) - { - Check.NotNull(user, nameof(user)); - Check.NotNull(organizationUnitIds, nameof(organizationUnitIds)); + public virtual async Task RemoveFromOrganizationUnitAsync(IdentityUser user, OrganizationUnit ou) + { + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.OrganizationUnits, + CancellationTokenProvider.Token); - await CheckMaxUserOrganizationUnitMembershipCountAsync(organizationUnitIds.Length); + user.RemoveOrganizationUnit(ou.Id); + await UserRepository.UpdateAsync(user, cancellationToken: CancellationToken); + } - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.OrganizationUnits, - CancellationTokenProvider.Token); + public virtual async Task SetOrganizationUnitsAsync(Guid userId, params Guid[] organizationUnitIds) + { + await SetOrganizationUnitsAsync( + await UserRepository.GetAsync(userId, cancellationToken: CancellationToken), + organizationUnitIds + ); + } - //Remove from removed OUs - foreach (var ouId in user.OrganizationUnits.Select(uou => uou.OrganizationUnitId).ToArray()) - { - if (!organizationUnitIds.Contains(ouId)) - { - user.RemoveOrganizationUnit(ouId); - } - } + public virtual async Task SetOrganizationUnitsAsync(IdentityUser user, params Guid[] organizationUnitIds) + { + Check.NotNull(user, nameof(user)); + Check.NotNull(organizationUnitIds, nameof(organizationUnitIds)); + + await CheckMaxUserOrganizationUnitMembershipCountAsync(organizationUnitIds.Length); - //Add to added OUs - foreach (var organizationUnitId in organizationUnitIds) + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.OrganizationUnits, + CancellationTokenProvider.Token); + + //Remove from removed OUs + foreach (var ouId in user.OrganizationUnits.Select(uou => uou.OrganizationUnitId).ToArray()) + { + if (!organizationUnitIds.Contains(ouId)) { - if (!user.IsInOrganizationUnit(organizationUnitId)) - { - user.AddOrganizationUnit(organizationUnitId); - } + user.RemoveOrganizationUnit(ouId); } - - await UserRepository.UpdateAsync(user, cancellationToken: CancellationToken); } - private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int requestedCount) + //Add to added OUs + foreach (var organizationUnitId in organizationUnitIds) { - var maxCount = - await SettingProvider.GetAsync(IdentitySettingNames.OrganizationUnit.MaxUserMembershipCount); - if (requestedCount > maxCount) + if (!user.IsInOrganizationUnit(organizationUnitId)) { - throw new BusinessException(IdentityErrorCodes.MaxAllowedOuMembership) - .WithData("MaxUserMembershipCount", maxCount); + user.AddOrganizationUnit(organizationUnitId); } } - [UnitOfWork] - public virtual async Task> GetOrganizationUnitsAsync(IdentityUser user, - bool includeDetails = false) + await UserRepository.UpdateAsync(user, cancellationToken: CancellationToken); + } + + private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int requestedCount) + { + var maxCount = + await SettingProvider.GetAsync(IdentitySettingNames.OrganizationUnit.MaxUserMembershipCount); + if (requestedCount > maxCount) { - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.OrganizationUnits, - CancellationTokenProvider.Token); - - return await OrganizationUnitRepository.GetListAsync( - user.OrganizationUnits.Select(t => t.OrganizationUnitId), - includeDetails, - cancellationToken: CancellationToken - ); + throw new BusinessException(IdentityErrorCodes.MaxAllowedOuMembership) + .WithData("MaxUserMembershipCount", maxCount); } + } + + [UnitOfWork] + public virtual async Task> GetOrganizationUnitsAsync(IdentityUser user, + bool includeDetails = false) + { + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.OrganizationUnits, + CancellationTokenProvider.Token); + + return await OrganizationUnitRepository.GetListAsync( + user.OrganizationUnits.Select(t => t.OrganizationUnitId), + includeDetails, + cancellationToken: CancellationToken + ); + } - [UnitOfWork] - public virtual async Task> GetUsersInOrganizationUnitAsync( - OrganizationUnit organizationUnit, - bool includeChildren = false) + [UnitOfWork] + public virtual async Task> GetUsersInOrganizationUnitAsync( + OrganizationUnit organizationUnit, + bool includeChildren = false) + { + if (includeChildren) { - if (includeChildren) - { - return await UserRepository - .GetUsersInOrganizationUnitWithChildrenAsync(organizationUnit.Code, CancellationToken); - } - else - { - return await UserRepository - .GetUsersInOrganizationUnitAsync(organizationUnit.Id, CancellationToken); - } + return await UserRepository + .GetUsersInOrganizationUnitWithChildrenAsync(organizationUnit.Code, CancellationToken); } - - public virtual async Task AddDefaultRolesAsync([NotNull] IdentityUser user) + else { - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles, CancellationToken); + return await UserRepository + .GetUsersInOrganizationUnitAsync(organizationUnit.Id, CancellationToken); + } + } - foreach (var role in await RoleRepository.GetDefaultOnesAsync(cancellationToken: CancellationToken)) + public virtual async Task AddDefaultRolesAsync([NotNull] IdentityUser user) + { + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles, CancellationToken); + + foreach (var role in await RoleRepository.GetDefaultOnesAsync(cancellationToken: CancellationToken)) + { + if (!user.IsInRole(role.Id)) { - if (!user.IsInRole(role.Id)) - { - user.AddRole(role.Id); - } + user.AddRole(role.Id); } - - return await UpdateUserAsync(user); } + + return await UpdateUserAsync(user); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserOrganizationUnit.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserOrganizationUnit.cs index 5bb0ed790d..24cecf1eed 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserOrganizationUnit.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserOrganizationUnit.cs @@ -2,43 +2,42 @@ using Volo.Abp.Domain.Entities.Auditing; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Represents membership of a User to an OU. +/// +public class IdentityUserOrganizationUnit : CreationAuditedEntity, IMultiTenant { /// - /// Represents membership of a User to an OU. + /// TenantId of this entity. + /// + public virtual Guid? TenantId { get; protected set; } + + /// + /// Id of the User. /// - public class IdentityUserOrganizationUnit : CreationAuditedEntity, IMultiTenant + public virtual Guid UserId { get; protected set; } + + /// + /// Id of the related . + /// + public virtual Guid OrganizationUnitId { get; protected set; } + + protected IdentityUserOrganizationUnit() + { + + } + + public IdentityUserOrganizationUnit(Guid userId, Guid organizationUnitId, Guid? tenantId = null) + { + UserId = userId; + OrganizationUnitId = organizationUnitId; + TenantId = tenantId; + } + + public override object[] GetKeys() { - /// - /// TenantId of this entity. - /// - public virtual Guid? TenantId { get; protected set; } - - /// - /// Id of the User. - /// - public virtual Guid UserId { get; protected set; } - - /// - /// Id of the related . - /// - public virtual Guid OrganizationUnitId { get; protected set; } - - protected IdentityUserOrganizationUnit() - { - - } - - public IdentityUserOrganizationUnit(Guid userId, Guid organizationUnitId, Guid? tenantId = null) - { - UserId = userId; - OrganizationUnitId = organizationUnitId; - TenantId = tenantId; - } - - public override object[] GetKeys() - { - return new object[] { UserId, OrganizationUnitId }; - } + return new object[] { UserId, OrganizationUnitId }; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRepositoryExternalUserLookupServiceProvider.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRepositoryExternalUserLookupServiceProvider.cs index 40b4575afe..4584466572 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRepositoryExternalUserLookupServiceProvider.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRepositoryExternalUserLookupServiceProvider.cs @@ -7,71 +7,70 @@ using Microsoft.AspNetCore.Identity; using Volo.Abp.DependencyInjection; using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUserRepositoryExternalUserLookupServiceProvider : IExternalUserLookupServiceProvider, ITransientDependency { - public class IdentityUserRepositoryExternalUserLookupServiceProvider : IExternalUserLookupServiceProvider, ITransientDependency - { - protected IIdentityUserRepository UserRepository { get; } - protected ILookupNormalizer LookupNormalizer { get; } + protected IIdentityUserRepository UserRepository { get; } + protected ILookupNormalizer LookupNormalizer { get; } - public IdentityUserRepositoryExternalUserLookupServiceProvider( - IIdentityUserRepository userRepository, - ILookupNormalizer lookupNormalizer) - { - UserRepository = userRepository; - LookupNormalizer = lookupNormalizer; - } + public IdentityUserRepositoryExternalUserLookupServiceProvider( + IIdentityUserRepository userRepository, + ILookupNormalizer lookupNormalizer) + { + UserRepository = userRepository; + LookupNormalizer = lookupNormalizer; + } - public virtual async Task FindByIdAsync( - Guid id, - CancellationToken cancellationToken = default) - { - return ( - await UserRepository.FindAsync( - id, - includeDetails: false, - cancellationToken: cancellationToken - ) - )?.ToAbpUserData(); - } + public virtual async Task FindByIdAsync( + Guid id, + CancellationToken cancellationToken = default) + { + return ( + await UserRepository.FindAsync( + id, + includeDetails: false, + cancellationToken: cancellationToken + ) + )?.ToAbpUserData(); + } - public virtual async Task FindByUserNameAsync( - string userName, - CancellationToken cancellationToken = default) - { - return ( - await UserRepository.FindByNormalizedUserNameAsync( - LookupNormalizer.NormalizeName(userName), - includeDetails: false, - cancellationToken: cancellationToken - ) - )?.ToAbpUserData(); - } + public virtual async Task FindByUserNameAsync( + string userName, + CancellationToken cancellationToken = default) + { + return ( + await UserRepository.FindByNormalizedUserNameAsync( + LookupNormalizer.NormalizeName(userName), + includeDetails: false, + cancellationToken: cancellationToken + ) + )?.ToAbpUserData(); + } - public virtual async Task> SearchAsync( - string sorting = null, - string filter = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - CancellationToken cancellationToken = default) - { - var users = await UserRepository.GetListAsync( - sorting: sorting, - maxResultCount: maxResultCount, - skipCount: skipCount, - filter: filter, - includeDetails: false, - cancellationToken: cancellationToken - ); + public virtual async Task> SearchAsync( + string sorting = null, + string filter = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + CancellationToken cancellationToken = default) + { + var users = await UserRepository.GetListAsync( + sorting: sorting, + maxResultCount: maxResultCount, + skipCount: skipCount, + filter: filter, + includeDetails: false, + cancellationToken: cancellationToken + ); - return users.Select(u => u.ToAbpUserData()).ToList(); - } + return users.Select(u => u.ToAbpUserData()).ToList(); + } - public async Task GetCountAsync( - string filter = null, - CancellationToken cancellationToken = new CancellationToken()) - { - return await UserRepository.GetCountAsync(filter, cancellationToken: cancellationToken); - } + public async Task GetCountAsync( + string filter = null, + CancellationToken cancellationToken = new CancellationToken()) + { + return await UserRepository.GetCountAsync(filter, cancellationToken: cancellationToken); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRole.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRole.cs index 88fe6a594f..73dd4889fb 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRole.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRole.cs @@ -2,40 +2,39 @@ using System; using Volo.Abp.Domain.Entities; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Represents the link between a user and a role. +/// +public class IdentityUserRole : Entity, IMultiTenant { + public virtual Guid? TenantId { get; protected set; } + /// - /// Represents the link between a user and a role. + /// Gets or sets the primary key of the user that is linked to a role. /// - public class IdentityUserRole : Entity, IMultiTenant + public virtual Guid UserId { get; protected set; } + + /// + /// Gets or sets the primary key of the role that is linked to the user. + /// + public virtual Guid RoleId { get; protected set; } + + protected IdentityUserRole() + { + + } + + protected internal IdentityUserRole(Guid userId, Guid roleId, Guid? tenantId) + { + UserId = userId; + RoleId = roleId; + TenantId = tenantId; + } + + public override object[] GetKeys() { - public virtual Guid? TenantId { get; protected set; } - - /// - /// Gets or sets the primary key of the user that is linked to a role. - /// - public virtual Guid UserId { get; protected set; } - - /// - /// Gets or sets the primary key of the role that is linked to the user. - /// - public virtual Guid RoleId { get; protected set; } - - protected IdentityUserRole() - { - - } - - protected internal IdentityUserRole(Guid userId, Guid roleId, Guid? tenantId) - { - UserId = userId; - RoleId = roleId; - TenantId = tenantId; - } - - public override object[] GetKeys() - { - return new object[] { UserId, RoleId }; - } + return new object[] { UserId, RoleId }; } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserStore.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserStore.cs index 17a0fbd39d..c8c8fd45a9 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserStore.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserStore.cs @@ -13,1101 +13,1100 @@ using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Repositories; using Volo.Abp.Guids; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Represents a new instance of a persistence store for the specified user and role types. +/// +public class IdentityUserStore : + IUserLoginStore, + IUserRoleStore, + IUserClaimStore, + IUserPasswordStore, + IUserSecurityStampStore, + IUserEmailStore, + IUserLockoutStore, + IUserPhoneNumberStore, + IUserTwoFactorStore, + IUserAuthenticationTokenStore, + IUserAuthenticatorKeyStore, + IUserTwoFactorRecoveryCodeStore, + ITransientDependency { + private const string InternalLoginProvider = "[AspNetUserStore]"; + private const string AuthenticatorKeyTokenName = "AuthenticatorKey"; + private const string RecoveryCodeTokenName = "RecoveryCodes"; + /// - /// Represents a new instance of a persistence store for the specified user and role types. + /// Gets or sets the for any error that occurred with the current operation. /// - public class IdentityUserStore : - IUserLoginStore, - IUserRoleStore, - IUserClaimStore, - IUserPasswordStore, - IUserSecurityStampStore, - IUserEmailStore, - IUserLockoutStore, - IUserPhoneNumberStore, - IUserTwoFactorStore, - IUserAuthenticationTokenStore, - IUserAuthenticatorKeyStore, - IUserTwoFactorRecoveryCodeStore, - ITransientDependency - { - private const string InternalLoginProvider = "[AspNetUserStore]"; - private const string AuthenticatorKeyTokenName = "AuthenticatorKey"; - private const string RecoveryCodeTokenName = "RecoveryCodes"; - - /// - /// Gets or sets the for any error that occurred with the current operation. - /// - public IdentityErrorDescriber ErrorDescriber { get; set; } - - /// - /// Gets or sets a flag indicating if changes should be persisted after CreateAsync, UpdateAsync and DeleteAsync are called. - /// - /// - /// True if changes should be automatically persisted, otherwise false. - /// - public bool AutoSaveChanges { get; set; } = true; - - protected IIdentityRoleRepository RoleRepository { get; } - protected IGuidGenerator GuidGenerator { get; } - protected ILogger Logger { get; } - protected ILookupNormalizer LookupNormalizer { get; } - protected IIdentityUserRepository UserRepository { get; } - - public IdentityUserStore( - IIdentityUserRepository userRepository, - IIdentityRoleRepository roleRepository, - IGuidGenerator guidGenerator, - ILogger logger, - ILookupNormalizer lookupNormalizer, - IdentityErrorDescriber describer = null) - { - UserRepository = userRepository; - RoleRepository = roleRepository; - GuidGenerator = guidGenerator; - Logger = logger; - LookupNormalizer = lookupNormalizer; + public IdentityErrorDescriber ErrorDescriber { get; set; } - ErrorDescriber = describer ?? new IdentityErrorDescriber(); - } + /// + /// Gets or sets a flag indicating if changes should be persisted after CreateAsync, UpdateAsync and DeleteAsync are called. + /// + /// + /// True if changes should be automatically persisted, otherwise false. + /// + public bool AutoSaveChanges { get; set; } = true; + + protected IIdentityRoleRepository RoleRepository { get; } + protected IGuidGenerator GuidGenerator { get; } + protected ILogger Logger { get; } + protected ILookupNormalizer LookupNormalizer { get; } + protected IIdentityUserRepository UserRepository { get; } + + public IdentityUserStore( + IIdentityUserRepository userRepository, + IIdentityRoleRepository roleRepository, + IGuidGenerator guidGenerator, + ILogger logger, + ILookupNormalizer lookupNormalizer, + IdentityErrorDescriber describer = null) + { + UserRepository = userRepository; + RoleRepository = roleRepository; + GuidGenerator = guidGenerator; + Logger = logger; + LookupNormalizer = lookupNormalizer; - /// - /// Gets the user identifier for the specified . - /// - /// The user whose identifier should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation, containing the identifier for the specified . - public virtual Task GetUserIdAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + ErrorDescriber = describer ?? new IdentityErrorDescriber(); + } - Check.NotNull(user, nameof(user)); + /// + /// Gets the user identifier for the specified . + /// + /// The user whose identifier should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation, containing the identifier for the specified . + public virtual Task GetUserIdAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return Task.FromResult(user.Id.ToString()); - } + Check.NotNull(user, nameof(user)); - /// - /// Gets the user name for the specified . - /// - /// The user whose name should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation, containing the name for the specified . - public virtual Task GetUserNameAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(user.Id.ToString()); + } - Check.NotNull(user, nameof(user)); + /// + /// Gets the user name for the specified . + /// + /// The user whose name should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation, containing the name for the specified . + public virtual Task GetUserNameAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return Task.FromResult(user.UserName); - } + Check.NotNull(user, nameof(user)); - /// - /// Sets the given for the specified . - /// - /// The user whose name should be set. - /// The user name to set. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual Task SetUserNameAsync([NotNull] IdentityUser user, string userName, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(user.UserName); + } - Check.NotNull(user, nameof(user)); + /// + /// Sets the given for the specified . + /// + /// The user whose name should be set. + /// The user name to set. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual Task SetUserNameAsync([NotNull] IdentityUser user, string userName, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - user.UserName = userName; + Check.NotNull(user, nameof(user)); - return Task.CompletedTask; - } + user.UserName = userName; - /// - /// Gets the normalized user name for the specified . - /// - /// The user whose normalized name should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation, containing the normalized user name for the specified . - public virtual Task GetNormalizedUserNameAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return Task.CompletedTask; + } - Check.NotNull(user, nameof(user)); + /// + /// Gets the normalized user name for the specified . + /// + /// The user whose normalized name should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation, containing the normalized user name for the specified . + public virtual Task GetNormalizedUserNameAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return Task.FromResult(user.NormalizedUserName); - } + Check.NotNull(user, nameof(user)); - /// - /// Sets the given normalized name for the specified . - /// - /// The user whose name should be set. - /// The normalized name to set. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual Task SetNormalizedUserNameAsync([NotNull] IdentityUser user, string normalizedName, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(user.NormalizedUserName); + } - Check.NotNull(user, nameof(user)); + /// + /// Sets the given normalized name for the specified . + /// + /// The user whose name should be set. + /// The normalized name to set. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual Task SetNormalizedUserNameAsync([NotNull] IdentityUser user, string normalizedName, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - user.NormalizedUserName = normalizedName; + Check.NotNull(user, nameof(user)); - return Task.CompletedTask; - } + user.NormalizedUserName = normalizedName; - /// - /// Creates the specified in the user store. - /// - /// The user to create. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation, containing the of the creation operation. - public virtual async Task CreateAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return Task.CompletedTask; + } - Check.NotNull(user, nameof(user)); + /// + /// Creates the specified in the user store. + /// + /// The user to create. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation, containing the of the creation operation. + public virtual async Task CreateAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - await UserRepository.InsertAsync(user, AutoSaveChanges, cancellationToken); + Check.NotNull(user, nameof(user)); - return IdentityResult.Success; - } + await UserRepository.InsertAsync(user, AutoSaveChanges, cancellationToken); - /// - /// Updates the specified in the user store. - /// - /// The user to update. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation, containing the of the update operation. - public virtual async Task UpdateAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return IdentityResult.Success; + } - Check.NotNull(user, nameof(user)); + /// + /// Updates the specified in the user store. + /// + /// The user to update. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation, containing the of the update operation. + public virtual async Task UpdateAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - try - { - await UserRepository.UpdateAsync(user, AutoSaveChanges, cancellationToken); - } - catch (AbpDbConcurrencyException ex) - { - Logger.LogWarning(ex.ToString()); //Trigger some AbpHandledException event - return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); - } + Check.NotNull(user, nameof(user)); - return IdentityResult.Success; + try + { + await UserRepository.UpdateAsync(user, AutoSaveChanges, cancellationToken); } - - /// - /// Deletes the specified from the user store. - /// - /// The user to delete. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation, containing the of the update operation. - public virtual async Task DeleteAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + catch (AbpDbConcurrencyException ex) { - cancellationToken.ThrowIfCancellationRequested(); + Logger.LogWarning(ex.ToString()); //Trigger some AbpHandledException event + return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); + } - Check.NotNull(user, nameof(user)); + return IdentityResult.Success; + } - try - { - await UserRepository.DeleteAsync(user, AutoSaveChanges, cancellationToken); - } - catch (AbpDbConcurrencyException ex) - { - Logger.LogWarning(ex.ToString()); //Trigger some AbpHandledException event - return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); - } + /// + /// Deletes the specified from the user store. + /// + /// The user to delete. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation, containing the of the update operation. + public virtual async Task DeleteAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return IdentityResult.Success; - } + Check.NotNull(user, nameof(user)); - /// - /// Finds and returns a user, if any, who has the specified . - /// - /// The user ID to search for. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The that represents the asynchronous operation, containing the user matching the specified if it exists. - /// - public virtual Task FindByIdAsync(string userId, CancellationToken cancellationToken = default) + try { - cancellationToken.ThrowIfCancellationRequested(); - - return UserRepository.FindAsync(Guid.Parse(userId), cancellationToken: cancellationToken); + await UserRepository.DeleteAsync(user, AutoSaveChanges, cancellationToken); } - - /// - /// Finds and returns a user, if any, who has the specified normalized user name. - /// - /// The normalized user name to search for. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The that represents the asynchronous operation, containing the user matching the specified if it exists. - /// - public virtual Task FindByNameAsync([NotNull] string normalizedUserName, CancellationToken cancellationToken = default) + catch (AbpDbConcurrencyException ex) { - cancellationToken.ThrowIfCancellationRequested(); + Logger.LogWarning(ex.ToString()); //Trigger some AbpHandledException event + return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); + } - Check.NotNull(normalizedUserName, nameof(normalizedUserName)); + return IdentityResult.Success; + } - return UserRepository.FindByNormalizedUserNameAsync(normalizedUserName, includeDetails: false, cancellationToken: cancellationToken); - } + /// + /// Finds and returns a user, if any, who has the specified . + /// + /// The user ID to search for. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The that represents the asynchronous operation, containing the user matching the specified if it exists. + /// + public virtual Task FindByIdAsync(string userId, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Sets the password hash for a user. - /// - /// The user to set the password hash for. - /// The password hash to set. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual Task SetPasswordHashAsync([NotNull] IdentityUser user, string passwordHash, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return UserRepository.FindAsync(Guid.Parse(userId), cancellationToken: cancellationToken); + } - Check.NotNull(user, nameof(user)); + /// + /// Finds and returns a user, if any, who has the specified normalized user name. + /// + /// The normalized user name to search for. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The that represents the asynchronous operation, containing the user matching the specified if it exists. + /// + public virtual Task FindByNameAsync([NotNull] string normalizedUserName, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - user.PasswordHash = passwordHash; + Check.NotNull(normalizedUserName, nameof(normalizedUserName)); - return Task.CompletedTask; - } + return UserRepository.FindByNormalizedUserNameAsync(normalizedUserName, includeDetails: false, cancellationToken: cancellationToken); + } - /// - /// Gets the password hash for a user. - /// - /// The user to retrieve the password hash for. - /// The used to propagate notifications that the operation should be canceled. - /// A that contains the password hash for the user. - public virtual Task GetPasswordHashAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Sets the password hash for a user. + /// + /// The user to set the password hash for. + /// The password hash to set. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual Task SetPasswordHashAsync([NotNull] IdentityUser user, string passwordHash, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); + Check.NotNull(user, nameof(user)); - return Task.FromResult(user.PasswordHash); - } + user.PasswordHash = passwordHash; - /// - /// Returns a flag indicating if the specified user has a password. - /// - /// The user to retrieve the password hash for. - /// The used to propagate notifications that the operation should be canceled. - /// A containing a flag indicating if the specified user has a password. If the - /// user has a password the returned value with be true, otherwise it will be false. - public virtual Task HasPasswordAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return Task.CompletedTask; + } - Check.NotNull(user, nameof(user)); + /// + /// Gets the password hash for a user. + /// + /// The user to retrieve the password hash for. + /// The used to propagate notifications that the operation should be canceled. + /// A that contains the password hash for the user. + public virtual Task GetPasswordHashAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return Task.FromResult(user.PasswordHash != null); - } + Check.NotNull(user, nameof(user)); - /// - /// Adds the given to the specified . - /// - /// The user to add the role to. - /// The role to add. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task AddToRoleAsync([NotNull] IdentityUser user, [NotNull] string normalizedRoleName, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(user.PasswordHash); + } + + /// + /// Returns a flag indicating if the specified user has a password. + /// + /// The user to retrieve the password hash for. + /// The used to propagate notifications that the operation should be canceled. + /// A containing a flag indicating if the specified user has a password. If the + /// user has a password the returned value with be true, otherwise it will be false. + public virtual Task HasPasswordAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); - Check.NotNull(normalizedRoleName, nameof(normalizedRoleName)); + Check.NotNull(user, nameof(user)); - if (await IsInRoleAsync(user, normalizedRoleName, cancellationToken)) - { - return; - } + return Task.FromResult(user.PasswordHash != null); + } - var role = await RoleRepository.FindByNormalizedNameAsync(normalizedRoleName, cancellationToken: cancellationToken); - if (role == null) - { - throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Role {0} does not exist!", normalizedRoleName)); - } + /// + /// Adds the given to the specified . + /// + /// The user to add the role to. + /// The role to add. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task AddToRoleAsync([NotNull] IdentityUser user, [NotNull] string normalizedRoleName, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles, cancellationToken); + Check.NotNull(user, nameof(user)); + Check.NotNull(normalizedRoleName, nameof(normalizedRoleName)); - user.AddRole(role.Id); + if (await IsInRoleAsync(user, normalizedRoleName, cancellationToken)) + { + return; } - /// - /// Removes the given from the specified . - /// - /// The user to remove the role from. - /// The role to remove. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task RemoveFromRoleAsync([NotNull] IdentityUser user, [NotNull] string normalizedRoleName, CancellationToken cancellationToken = default) + var role = await RoleRepository.FindByNormalizedNameAsync(normalizedRoleName, cancellationToken: cancellationToken); + if (role == null) { - cancellationToken.ThrowIfCancellationRequested(); + throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Role {0} does not exist!", normalizedRoleName)); + } - Check.NotNull(user, nameof(user)); - Check.NotNullOrWhiteSpace(normalizedRoleName, nameof(normalizedRoleName)); + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles, cancellationToken); - var role = await RoleRepository.FindByNormalizedNameAsync(normalizedRoleName, cancellationToken: cancellationToken); - if (role == null) - { - return; - } + user.AddRole(role.Id); + } - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles, cancellationToken); + /// + /// Removes the given from the specified . + /// + /// The user to remove the role from. + /// The role to remove. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task RemoveFromRoleAsync([NotNull] IdentityUser user, [NotNull] string normalizedRoleName, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - user.RemoveRole(role.Id); - } + Check.NotNull(user, nameof(user)); + Check.NotNullOrWhiteSpace(normalizedRoleName, nameof(normalizedRoleName)); - /// - /// Retrieves the roles the specified is a member of. - /// - /// The user whose roles should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// A that contains the roles the user is a member of. - public virtual async Task> GetRolesAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + var role = await RoleRepository.FindByNormalizedNameAsync(normalizedRoleName, cancellationToken: cancellationToken); + if (role == null) { - cancellationToken.ThrowIfCancellationRequested(); + return; + } - Check.NotNull(user, nameof(user)); + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles, cancellationToken); - var userRoles = await UserRepository - .GetRoleNamesAsync(user.Id, cancellationToken: cancellationToken); + user.RemoveRole(role.Id); + } - var userOrganizationUnitRoles = await UserRepository - .GetRoleNamesInOrganizationUnitAsync(user.Id, cancellationToken: cancellationToken); + /// + /// Retrieves the roles the specified is a member of. + /// + /// The user whose roles should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// A that contains the roles the user is a member of. + public virtual async Task> GetRolesAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return userRoles.Union(userOrganizationUnitRoles).ToList(); - } + Check.NotNull(user, nameof(user)); - /// - /// Returns a flag indicating if the specified user is a member of the give . - /// - /// The user whose role membership should be checked. - /// The role to check membership of - /// The used to propagate notifications that the operation should be canceled. - /// A containing a flag indicating if the specified user is a member of the given group. If the - /// user is a member of the group the returned value with be true, otherwise it will be false. - public virtual async Task IsInRoleAsync( - [NotNull] IdentityUser user, - [NotNull] string normalizedRoleName, - CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + var userRoles = await UserRepository + .GetRoleNamesAsync(user.Id, cancellationToken: cancellationToken); - Check.NotNull(user, nameof(user)); - Check.NotNullOrWhiteSpace(normalizedRoleName, nameof(normalizedRoleName)); + var userOrganizationUnitRoles = await UserRepository + .GetRoleNamesInOrganizationUnitAsync(user.Id, cancellationToken: cancellationToken); - var roles = await GetRolesAsync(user, cancellationToken); + return userRoles.Union(userOrganizationUnitRoles).ToList(); + } - return roles - .Select(r => LookupNormalizer.NormalizeName(r)) - .Contains(normalizedRoleName); - } + /// + /// Returns a flag indicating if the specified user is a member of the give . + /// + /// The user whose role membership should be checked. + /// The role to check membership of + /// The used to propagate notifications that the operation should be canceled. + /// A containing a flag indicating if the specified user is a member of the given group. If the + /// user is a member of the group the returned value with be true, otherwise it will be false. + public virtual async Task IsInRoleAsync( + [NotNull] IdentityUser user, + [NotNull] string normalizedRoleName, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Get the claims associated with the specified as an asynchronous operation. - /// - /// The user whose claims should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// A that contains the claims granted to a user. - public virtual async Task> GetClaimsAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); + Check.NotNullOrWhiteSpace(normalizedRoleName, nameof(normalizedRoleName)); - Check.NotNull(user, nameof(user)); + var roles = await GetRolesAsync(user, cancellationToken); - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken); + return roles + .Select(r => LookupNormalizer.NormalizeName(r)) + .Contains(normalizedRoleName); + } - return user.Claims.Select(c => c.ToClaim()).ToList(); - } + /// + /// Get the claims associated with the specified as an asynchronous operation. + /// + /// The user whose claims should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// A that contains the claims granted to a user. + public virtual async Task> GetClaimsAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Adds the given to the specified . - /// - /// The user to add the claim to. - /// The claim to add to the user. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task AddClaimsAsync([NotNull] IdentityUser user, [NotNull] IEnumerable claims, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - Check.NotNull(user, nameof(user)); - Check.NotNull(claims, nameof(claims)); + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken); - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken); + return user.Claims.Select(c => c.ToClaim()).ToList(); + } - user.AddClaims(GuidGenerator, claims); - } + /// + /// Adds the given to the specified . + /// + /// The user to add the claim to. + /// The claim to add to the user. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task AddClaimsAsync([NotNull] IdentityUser user, [NotNull] IEnumerable claims, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Replaces the on the specified , with the . - /// - /// The user to replace the claim on. - /// The claim replace. - /// The new claim replacing the . - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task ReplaceClaimAsync([NotNull] IdentityUser user, [NotNull] Claim claim, [NotNull] Claim newClaim, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); + Check.NotNull(claims, nameof(claims)); - Check.NotNull(user, nameof(user)); - Check.NotNull(claim, nameof(claim)); - Check.NotNull(newClaim, nameof(newClaim)); + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken); - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken); + user.AddClaims(GuidGenerator, claims); + } - user.ReplaceClaim(claim, newClaim); - } + /// + /// Replaces the on the specified , with the . + /// + /// The user to replace the claim on. + /// The claim replace. + /// The new claim replacing the . + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task ReplaceClaimAsync([NotNull] IdentityUser user, [NotNull] Claim claim, [NotNull] Claim newClaim, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Removes the given from the specified . - /// - /// The user to remove the claims from. - /// The claim to remove. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task RemoveClaimsAsync([NotNull] IdentityUser user, [NotNull] IEnumerable claims, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); + Check.NotNull(claim, nameof(claim)); + Check.NotNull(newClaim, nameof(newClaim)); - Check.NotNull(user, nameof(user)); - Check.NotNull(claims, nameof(claims)); + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken); - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken); + user.ReplaceClaim(claim, newClaim); + } - user.RemoveClaims(claims); - } + /// + /// Removes the given from the specified . + /// + /// The user to remove the claims from. + /// The claim to remove. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task RemoveClaimsAsync([NotNull] IdentityUser user, [NotNull] IEnumerable claims, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Adds the given to the specified . - /// - /// The user to add the login to. - /// The login to add to the user. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task AddLoginAsync([NotNull] IdentityUser user, [NotNull] UserLoginInfo login, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); + Check.NotNull(claims, nameof(claims)); - Check.NotNull(user, nameof(user)); - Check.NotNull(login, nameof(login)); + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Claims, cancellationToken); - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Logins, cancellationToken); + user.RemoveClaims(claims); + } - user.AddLogin(login); - } + /// + /// Adds the given to the specified . + /// + /// The user to add the login to. + /// The login to add to the user. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task AddLoginAsync([NotNull] IdentityUser user, [NotNull] UserLoginInfo login, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Removes the given from the specified . - /// - /// The user to remove the login from. - /// The login to remove from the user. - /// The key provided by the to identify a user. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task RemoveLoginAsync([NotNull] IdentityUser user, [NotNull] string loginProvider, [NotNull] string providerKey, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); + Check.NotNull(login, nameof(login)); - Check.NotNull(user, nameof(user)); - Check.NotNull(loginProvider, nameof(loginProvider)); - Check.NotNull(providerKey, nameof(providerKey)); + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Logins, cancellationToken); - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Logins, cancellationToken); + user.AddLogin(login); + } - user.RemoveLogin(loginProvider, providerKey); - } + /// + /// Removes the given from the specified . + /// + /// The user to remove the login from. + /// The login to remove from the user. + /// The key provided by the to identify a user. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task RemoveLoginAsync([NotNull] IdentityUser user, [NotNull] string loginProvider, [NotNull] string providerKey, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Retrieves the associated logins for the specified . - /// - /// The user whose associated logins to retrieve. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The for the asynchronous operation, containing a list of for the specified , if any. - /// - public virtual async Task> GetLoginsAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); + Check.NotNull(loginProvider, nameof(loginProvider)); + Check.NotNull(providerKey, nameof(providerKey)); - Check.NotNull(user, nameof(user)); + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Logins, cancellationToken); - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Logins, cancellationToken); + user.RemoveLogin(loginProvider, providerKey); + } - return user.Logins.Select(l => l.ToUserLoginInfo()).ToList(); - } + /// + /// Retrieves the associated logins for the specified . + /// + /// The user whose associated logins to retrieve. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The for the asynchronous operation, containing a list of for the specified , if any. + /// + public virtual async Task> GetLoginsAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Retrieves the user associated with the specified login provider and login provider key.. - /// - /// The login provider who provided the . - /// The key provided by the to identify a user. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The for the asynchronous operation, containing the user, if any which matched the specified login provider and key. - /// - public virtual Task FindByLoginAsync([NotNull] string loginProvider, [NotNull] string providerKey, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - Check.NotNull(loginProvider, nameof(loginProvider)); - Check.NotNull(providerKey, nameof(providerKey)); + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Logins, cancellationToken); - return UserRepository.FindByLoginAsync(loginProvider, providerKey, cancellationToken: cancellationToken); - } + return user.Logins.Select(l => l.ToUserLoginInfo()).ToList(); + } - /// - /// Gets a flag indicating whether the email address for the specified has been verified, true if the email address is verified otherwise - /// false. - /// - /// The user whose email confirmation status should be returned. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The task object containing the results of the asynchronous operation, a flag indicating whether the email address for the specified - /// has been confirmed or not. - /// - public virtual Task GetEmailConfirmedAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Retrieves the user associated with the specified login provider and login provider key.. + /// + /// The login provider who provided the . + /// The key provided by the to identify a user. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The for the asynchronous operation, containing the user, if any which matched the specified login provider and key. + /// + public virtual Task FindByLoginAsync([NotNull] string loginProvider, [NotNull] string providerKey, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); + Check.NotNull(loginProvider, nameof(loginProvider)); + Check.NotNull(providerKey, nameof(providerKey)); - return Task.FromResult(user.EmailConfirmed); - } + return UserRepository.FindByLoginAsync(loginProvider, providerKey, cancellationToken: cancellationToken); + } - /// - /// Sets the flag indicating whether the specified 's email address has been confirmed or not. - /// - /// The user whose email confirmation status should be set. - /// A flag indicating if the email address has been confirmed, true if the address is confirmed otherwise false. - /// The used to propagate notifications that the operation should be canceled. - /// The task object representing the asynchronous operation. - public virtual Task SetEmailConfirmedAsync([NotNull] IdentityUser user, bool confirmed, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Gets a flag indicating whether the email address for the specified has been verified, true if the email address is verified otherwise + /// false. + /// + /// The user whose email confirmation status should be returned. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The task object containing the results of the asynchronous operation, a flag indicating whether the email address for the specified + /// has been confirmed or not. + /// + public virtual Task GetEmailConfirmedAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); + Check.NotNull(user, nameof(user)); - user.SetEmailConfirmed(confirmed); + return Task.FromResult(user.EmailConfirmed); + } - return Task.CompletedTask; - } + /// + /// Sets the flag indicating whether the specified 's email address has been confirmed or not. + /// + /// The user whose email confirmation status should be set. + /// A flag indicating if the email address has been confirmed, true if the address is confirmed otherwise false. + /// The used to propagate notifications that the operation should be canceled. + /// The task object representing the asynchronous operation. + public virtual Task SetEmailConfirmedAsync([NotNull] IdentityUser user, bool confirmed, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Sets the address for a . - /// - /// The user whose email should be set. - /// The email to set. - /// The used to propagate notifications that the operation should be canceled. - /// The task object representing the asynchronous operation. - public virtual Task SetEmailAsync([NotNull] IdentityUser user, [NotNull] string email, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - Check.NotNull(user, nameof(user)); - Check.NotNull(email, nameof(email)); + user.SetEmailConfirmed(confirmed); - user.Email = email; + return Task.CompletedTask; + } - return Task.CompletedTask; - } + /// + /// Sets the address for a . + /// + /// The user whose email should be set. + /// The email to set. + /// The used to propagate notifications that the operation should be canceled. + /// The task object representing the asynchronous operation. + public virtual Task SetEmailAsync([NotNull] IdentityUser user, [NotNull] string email, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Gets the email address for the specified . - /// - /// The user whose email should be returned. - /// The used to propagate notifications that the operation should be canceled. - /// The task object containing the results of the asynchronous operation, the email address for the specified . - public virtual Task GetEmailAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); + Check.NotNull(email, nameof(email)); - Check.NotNull(user, nameof(user)); + user.Email = email; - return Task.FromResult(user.Email); - } + return Task.CompletedTask; + } - /// - /// Returns the normalized email for the specified . - /// - /// The user whose email address to retrieve. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The task object containing the results of the asynchronous lookup operation, the normalized email address if any associated with the specified user. - /// - public virtual Task GetNormalizedEmailAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Gets the email address for the specified . + /// + /// The user whose email should be returned. + /// The used to propagate notifications that the operation should be canceled. + /// The task object containing the results of the asynchronous operation, the email address for the specified . + public virtual Task GetEmailAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); + Check.NotNull(user, nameof(user)); - return Task.FromResult(user.NormalizedEmail); - } + return Task.FromResult(user.Email); + } - /// - /// Sets the normalized email for the specified . - /// - /// The user whose email address to set. - /// The normalized email to set for the specified . - /// The used to propagate notifications that the operation should be canceled. - /// The task object representing the asynchronous operation. - public virtual Task SetNormalizedEmailAsync([NotNull] IdentityUser user, string normalizedEmail, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Returns the normalized email for the specified . + /// + /// The user whose email address to retrieve. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The task object containing the results of the asynchronous lookup operation, the normalized email address if any associated with the specified user. + /// + public virtual Task GetNormalizedEmailAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); + Check.NotNull(user, nameof(user)); - user.NormalizedEmail = normalizedEmail; + return Task.FromResult(user.NormalizedEmail); + } - return Task.CompletedTask; - } + /// + /// Sets the normalized email for the specified . + /// + /// The user whose email address to set. + /// The normalized email to set for the specified . + /// The used to propagate notifications that the operation should be canceled. + /// The task object representing the asynchronous operation. + public virtual Task SetNormalizedEmailAsync([NotNull] IdentityUser user, string normalizedEmail, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Gets the user, if any, associated with the specified, normalized email address. - /// - /// The normalized email address to return the user for. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The task object containing the results of the asynchronous lookup operation, the user if any associated with the specified normalized email address. - /// - public virtual Task FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - return UserRepository.FindByNormalizedEmailAsync(normalizedEmail, includeDetails: false, cancellationToken: cancellationToken); - } + user.NormalizedEmail = normalizedEmail; - /// - /// Gets the last a user's last lockout expired, if any. - /// Any time in the past should be indicates a user is not locked out. - /// - /// The user whose lockout date should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// - /// A that represents the result of the asynchronous query, a containing the last time - /// a user's lockout expired, if any. - /// - public virtual Task GetLockoutEndDateAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + return Task.CompletedTask; + } - Check.NotNull(user, nameof(user)); + /// + /// Gets the user, if any, associated with the specified, normalized email address. + /// + /// The normalized email address to return the user for. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The task object containing the results of the asynchronous lookup operation, the user if any associated with the specified normalized email address. + /// + public virtual Task FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return Task.FromResult(user.LockoutEnd); - } + return UserRepository.FindByNormalizedEmailAsync(normalizedEmail, includeDetails: false, cancellationToken: cancellationToken); + } - /// - /// Locks out a user until the specified end date has passed. Setting a end date in the past immediately unlocks a user. - /// - /// The user whose lockout date should be set. - /// The after which the 's lockout should end. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual Task SetLockoutEndDateAsync([NotNull] IdentityUser user, DateTimeOffset? lockoutEnd, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Gets the last a user's last lockout expired, if any. + /// Any time in the past should be indicates a user is not locked out. + /// + /// The user whose lockout date should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// + /// A that represents the result of the asynchronous query, a containing the last time + /// a user's lockout expired, if any. + /// + public virtual Task GetLockoutEndDateAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); + Check.NotNull(user, nameof(user)); - user.LockoutEnd = lockoutEnd; + return Task.FromResult(user.LockoutEnd); + } - return Task.CompletedTask; - } + /// + /// Locks out a user until the specified end date has passed. Setting a end date in the past immediately unlocks a user. + /// + /// The user whose lockout date should be set. + /// The after which the 's lockout should end. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual Task SetLockoutEndDateAsync([NotNull] IdentityUser user, DateTimeOffset? lockoutEnd, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Records that a failed access has occurred, incrementing the failed access count. - /// - /// The user whose cancellation count should be incremented. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation, containing the incremented failed access count. - public virtual Task IncrementAccessFailedCountAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - Check.NotNull(user, nameof(user)); + user.LockoutEnd = lockoutEnd; - user.AccessFailedCount++; + return Task.CompletedTask; + } - return Task.FromResult(user.AccessFailedCount); - } + /// + /// Records that a failed access has occurred, incrementing the failed access count. + /// + /// The user whose cancellation count should be incremented. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation, containing the incremented failed access count. + public virtual Task IncrementAccessFailedCountAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Resets a user's failed access count. - /// - /// The user whose failed access count should be reset. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - /// This is typically called after the account is successfully accessed. - public virtual Task ResetAccessFailedCountAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - Check.NotNull(user, nameof(user)); + user.AccessFailedCount++; - user.AccessFailedCount = 0; + return Task.FromResult(user.AccessFailedCount); + } - return Task.CompletedTask; - } + /// + /// Resets a user's failed access count. + /// + /// The user whose failed access count should be reset. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + /// This is typically called after the account is successfully accessed. + public virtual Task ResetAccessFailedCountAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Retrieves the current failed access count for the specified .. - /// - /// The user whose failed access count should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation, containing the failed access count. - public virtual Task GetAccessFailedCountAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - Check.NotNull(user, nameof(user)); + user.AccessFailedCount = 0; - return Task.FromResult(user.AccessFailedCount); - } + return Task.CompletedTask; + } - /// - /// Retrieves a flag indicating whether user lockout can enabled for the specified user. - /// - /// The user whose ability to be locked out should be returned. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The that represents the asynchronous operation, true if a user can be locked out, otherwise false. - /// - public virtual Task GetLockoutEnabledAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Retrieves the current failed access count for the specified .. + /// + /// The user whose failed access count should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation, containing the failed access count. + public virtual Task GetAccessFailedCountAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); + Check.NotNull(user, nameof(user)); - return Task.FromResult(user.LockoutEnabled); - } + return Task.FromResult(user.AccessFailedCount); + } - /// - /// Set the flag indicating if the specified can be locked out.. - /// - /// The user whose ability to be locked out should be set. - /// A flag indicating if lock out can be enabled for the specified . - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual Task SetLockoutEnabledAsync([NotNull] IdentityUser user, bool enabled, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Retrieves a flag indicating whether user lockout can enabled for the specified user. + /// + /// The user whose ability to be locked out should be returned. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The that represents the asynchronous operation, true if a user can be locked out, otherwise false. + /// + public virtual Task GetLockoutEnabledAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); + Check.NotNull(user, nameof(user)); - user.LockoutEnabled = enabled; + return Task.FromResult(user.LockoutEnabled); + } - return Task.CompletedTask; - } + /// + /// Set the flag indicating if the specified can be locked out.. + /// + /// The user whose ability to be locked out should be set. + /// A flag indicating if lock out can be enabled for the specified . + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual Task SetLockoutEnabledAsync([NotNull] IdentityUser user, bool enabled, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Sets the telephone number for the specified . - /// - /// The user whose telephone number should be set. - /// The telephone number to set. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual Task SetPhoneNumberAsync([NotNull] IdentityUser user, string phoneNumber, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - Check.NotNull(user, nameof(user)); + user.LockoutEnabled = enabled; - user.PhoneNumber = phoneNumber; + return Task.CompletedTask; + } - return Task.CompletedTask; - } + /// + /// Sets the telephone number for the specified . + /// + /// The user whose telephone number should be set. + /// The telephone number to set. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual Task SetPhoneNumberAsync([NotNull] IdentityUser user, string phoneNumber, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Gets the telephone number, if any, for the specified . - /// - /// The user whose telephone number should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation, containing the user's telephone number, if any. - public virtual Task GetPhoneNumberAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - Check.NotNull(user, nameof(user)); + user.PhoneNumber = phoneNumber; - return Task.FromResult(user.PhoneNumber); - } + return Task.CompletedTask; + } - /// - /// Gets a flag indicating whether the specified 's telephone number has been confirmed. - /// - /// The user to return a flag for, indicating whether their telephone number is confirmed. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The that represents the asynchronous operation, returning true if the specified has a confirmed - /// telephone number otherwise false. - /// - public virtual Task GetPhoneNumberConfirmedAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Gets the telephone number, if any, for the specified . + /// + /// The user whose telephone number should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation, containing the user's telephone number, if any. + public virtual Task GetPhoneNumberAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); + Check.NotNull(user, nameof(user)); - return Task.FromResult(user.PhoneNumberConfirmed); - } + return Task.FromResult(user.PhoneNumber); + } - /// - /// Sets a flag indicating if the specified 's phone number has been confirmed.. - /// - /// The user whose telephone number confirmation status should be set. - /// A flag indicating whether the user's telephone number has been confirmed. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual Task SetPhoneNumberConfirmedAsync([NotNull] IdentityUser user, bool confirmed, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Gets a flag indicating whether the specified 's telephone number has been confirmed. + /// + /// The user to return a flag for, indicating whether their telephone number is confirmed. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The that represents the asynchronous operation, returning true if the specified has a confirmed + /// telephone number otherwise false. + /// + public virtual Task GetPhoneNumberConfirmedAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); + Check.NotNull(user, nameof(user)); - user.SetPhoneNumberConfirmed(confirmed); + return Task.FromResult(user.PhoneNumberConfirmed); + } - return Task.CompletedTask; - } + /// + /// Sets a flag indicating if the specified 's phone number has been confirmed.. + /// + /// The user whose telephone number confirmation status should be set. + /// A flag indicating whether the user's telephone number has been confirmed. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual Task SetPhoneNumberConfirmedAsync([NotNull] IdentityUser user, bool confirmed, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Sets the provided security for the specified . - /// - /// The user whose security stamp should be set. - /// The security stamp to set. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual Task SetSecurityStampAsync([NotNull] IdentityUser user, string stamp, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - Check.NotNull(user, nameof(user)); + user.SetPhoneNumberConfirmed(confirmed); - user.SecurityStamp = stamp; + return Task.CompletedTask; + } - return Task.CompletedTask; - } + /// + /// Sets the provided security for the specified . + /// + /// The user whose security stamp should be set. + /// The security stamp to set. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual Task SetSecurityStampAsync([NotNull] IdentityUser user, string stamp, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Get the security stamp for the specified . - /// - /// The user whose security stamp should be set. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation, containing the security stamp for the specified . - public virtual Task GetSecurityStampAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - Check.NotNull(user, nameof(user)); + user.SecurityStamp = stamp; - return Task.FromResult(user.SecurityStamp); - } + return Task.CompletedTask; + } - /// - /// Sets a flag indicating whether the specified has two factor authentication enabled or not, - /// as an asynchronous operation. - /// - /// The user whose two factor authentication enabled status should be set. - /// A flag indicating whether the specified has two factor authentication enabled. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual Task SetTwoFactorEnabledAsync([NotNull] IdentityUser user, bool enabled, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Get the security stamp for the specified . + /// + /// The user whose security stamp should be set. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation, containing the security stamp for the specified . + public virtual Task GetSecurityStampAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(user, nameof(user)); + Check.NotNull(user, nameof(user)); - user.TwoFactorEnabled = enabled; + return Task.FromResult(user.SecurityStamp); + } - return Task.CompletedTask; - } + /// + /// Sets a flag indicating whether the specified has two factor authentication enabled or not, + /// as an asynchronous operation. + /// + /// The user whose two factor authentication enabled status should be set. + /// A flag indicating whether the specified has two factor authentication enabled. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual Task SetTwoFactorEnabledAsync([NotNull] IdentityUser user, bool enabled, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - /// - /// Returns a flag indicating whether the specified has two factor authentication enabled or not, - /// as an asynchronous operation. - /// - /// The user whose two factor authentication enabled status should be set. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The that represents the asynchronous operation, containing a flag indicating whether the specified - /// has two factor authentication enabled or not. - /// - public virtual Task GetTwoFactorEnabledAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + Check.NotNull(user, nameof(user)); - Check.NotNull(user, nameof(user)); + user.TwoFactorEnabled = enabled; - return Task.FromResult(user.TwoFactorEnabled); - } + return Task.CompletedTask; + } - /// - /// Retrieves all users with the specified claim. - /// - /// The claim whose users should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The contains a list of users, if any, that contain the specified claim. - /// - public virtual async Task> GetUsersForClaimAsync([NotNull] Claim claim, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Returns a flag indicating whether the specified has two factor authentication enabled or not, + /// as an asynchronous operation. + /// + /// The user whose two factor authentication enabled status should be set. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The that represents the asynchronous operation, containing a flag indicating whether the specified + /// has two factor authentication enabled or not. + /// + public virtual Task GetTwoFactorEnabledAsync([NotNull] IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - Check.NotNull(claim, nameof(claim)); + Check.NotNull(user, nameof(user)); - return await UserRepository.GetListByClaimAsync(claim, cancellationToken: cancellationToken); - } + return Task.FromResult(user.TwoFactorEnabled); + } - /// - /// Retrieves all users in the specified role. - /// - /// The role whose users should be retrieved. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The contains a list of users, if any, that are in the specified role. - /// - public virtual async Task> GetUsersInRoleAsync([NotNull] string normalizedRoleName, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + /// + /// Retrieves all users with the specified claim. + /// + /// The claim whose users should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The contains a list of users, if any, that contain the specified claim. + /// + public virtual async Task> GetUsersForClaimAsync([NotNull] Claim claim, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - if (string.IsNullOrEmpty(normalizedRoleName)) - { - throw new ArgumentNullException(nameof(normalizedRoleName)); - } + Check.NotNull(claim, nameof(claim)); - return await UserRepository.GetListByNormalizedRoleNameAsync(normalizedRoleName, cancellationToken: cancellationToken); - } + return await UserRepository.GetListByClaimAsync(claim, cancellationToken: cancellationToken); + } - /// - /// Sets the token value for a particular user. - /// - /// The user. - /// The authentication provider for the token. - /// The name of the token. - /// The value of the token. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task SetTokenAsync([NotNull] IdentityUser user, string loginProvider, string name, string value, CancellationToken cancellationToken = default) + /// + /// Retrieves all users in the specified role. + /// + /// The role whose users should be retrieved. + /// The used to propagate notifications that the operation should be canceled. + /// + /// The contains a list of users, if any, that are in the specified role. + /// + public virtual async Task> GetUsersInRoleAsync([NotNull] string normalizedRoleName, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (string.IsNullOrEmpty(normalizedRoleName)) { - cancellationToken.ThrowIfCancellationRequested(); + throw new ArgumentNullException(nameof(normalizedRoleName)); + } - Check.NotNull(user, nameof(user)); + return await UserRepository.GetListByNormalizedRoleNameAsync(normalizedRoleName, cancellationToken: cancellationToken); + } - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Tokens, cancellationToken); + /// + /// Sets the token value for a particular user. + /// + /// The user. + /// The authentication provider for the token. + /// The name of the token. + /// The value of the token. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task SetTokenAsync([NotNull] IdentityUser user, string loginProvider, string name, string value, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - user.SetToken(loginProvider, name, value); - } + Check.NotNull(user, nameof(user)); - /// - /// Deletes a token for a user. - /// - /// The user. - /// The authentication provider for the token. - /// The name of the token. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task RemoveTokenAsync(IdentityUser user, string loginProvider, string name, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Tokens, cancellationToken); - Check.NotNull(user, nameof(user)); + user.SetToken(loginProvider, name, value); + } - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Tokens, cancellationToken); + /// + /// Deletes a token for a user. + /// + /// The user. + /// The authentication provider for the token. + /// The name of the token. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task RemoveTokenAsync(IdentityUser user, string loginProvider, string name, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - user.RemoveToken(loginProvider, name); - } + Check.NotNull(user, nameof(user)); - /// - /// Returns the token value. - /// - /// The user. - /// The authentication provider for the token. - /// The name of the token. - /// The used to propagate notifications that the operation should be canceled. - /// The that represents the asynchronous operation. - public virtual async Task GetTokenAsync(IdentityUser user, string loginProvider, string name, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Tokens, cancellationToken); - Check.NotNull(user, nameof(user)); + user.RemoveToken(loginProvider, name); + } - await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Tokens, cancellationToken); + /// + /// Returns the token value. + /// + /// The user. + /// The authentication provider for the token. + /// The name of the token. + /// The used to propagate notifications that the operation should be canceled. + /// The that represents the asynchronous operation. + public virtual async Task GetTokenAsync(IdentityUser user, string loginProvider, string name, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return user.FindToken(loginProvider, name)?.Value; - } + Check.NotNull(user, nameof(user)); - public virtual Task SetAuthenticatorKeyAsync(IdentityUser user, string key, CancellationToken cancellationToken = default) - { - return SetTokenAsync(user, InternalLoginProvider, AuthenticatorKeyTokenName, key, cancellationToken); - } + await UserRepository.EnsureCollectionLoadedAsync(user, u => u.Tokens, cancellationToken); - public virtual Task GetAuthenticatorKeyAsync(IdentityUser user, CancellationToken cancellationToken = default) - { - return GetTokenAsync(user, InternalLoginProvider, AuthenticatorKeyTokenName, cancellationToken); - } + return user.FindToken(loginProvider, name)?.Value; + } - /// - /// Returns how many recovery code are still valid for a user. - /// - /// The user who owns the recovery code. - /// The used to propagate notifications that the operation should be canceled. - /// The number of valid recovery codes for the user.. - public virtual async Task CountCodesAsync(IdentityUser user, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + public virtual Task SetAuthenticatorKeyAsync(IdentityUser user, string key, CancellationToken cancellationToken = default) + { + return SetTokenAsync(user, InternalLoginProvider, AuthenticatorKeyTokenName, key, cancellationToken); + } - Check.NotNull(user, nameof(user)); + public virtual Task GetAuthenticatorKeyAsync(IdentityUser user, CancellationToken cancellationToken = default) + { + return GetTokenAsync(user, InternalLoginProvider, AuthenticatorKeyTokenName, cancellationToken); + } - var mergedCodes = await GetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, cancellationToken) ?? ""; - if (mergedCodes.Length > 0) - { - return mergedCodes.Split(';').Length; - } + /// + /// Returns how many recovery code are still valid for a user. + /// + /// The user who owns the recovery code. + /// The used to propagate notifications that the operation should be canceled. + /// The number of valid recovery codes for the user.. + public virtual async Task CountCodesAsync(IdentityUser user, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return 0; - } + Check.NotNull(user, nameof(user)); - /// - /// Updates the recovery codes for the user while invalidating any previous recovery codes. - /// - /// The user to store new recovery codes for. - /// The new recovery codes for the user. - /// The used to propagate notifications that the operation should be canceled. - /// The new recovery codes for the user. - public virtual Task ReplaceCodesAsync(IdentityUser user, IEnumerable recoveryCodes, CancellationToken cancellationToken = default) + var mergedCodes = await GetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, cancellationToken) ?? ""; + if (mergedCodes.Length > 0) { - var mergedCodes = string.Join(";", recoveryCodes); - return SetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, mergedCodes, cancellationToken); + return mergedCodes.Split(';').Length; } - /// - /// Returns whether a recovery code is valid for a user. Note: recovery codes are only valid - /// once, and will be invalid after use. - /// - /// The user who owns the recovery code. - /// The recovery code to use. - /// The used to propagate notifications that the operation should be canceled. - /// True if the recovery code was found for the user. - public virtual async Task RedeemCodeAsync(IdentityUser user, string code, CancellationToken cancellationToken = default) + return 0; + } + + /// + /// Updates the recovery codes for the user while invalidating any previous recovery codes. + /// + /// The user to store new recovery codes for. + /// The new recovery codes for the user. + /// The used to propagate notifications that the operation should be canceled. + /// The new recovery codes for the user. + public virtual Task ReplaceCodesAsync(IdentityUser user, IEnumerable recoveryCodes, CancellationToken cancellationToken = default) + { + var mergedCodes = string.Join(";", recoveryCodes); + return SetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, mergedCodes, cancellationToken); + } + + /// + /// Returns whether a recovery code is valid for a user. Note: recovery codes are only valid + /// once, and will be invalid after use. + /// + /// The user who owns the recovery code. + /// The recovery code to use. + /// The used to propagate notifications that the operation should be canceled. + /// True if the recovery code was found for the user. + public virtual async Task RedeemCodeAsync(IdentityUser user, string code, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + Check.NotNull(user, nameof(user)); + Check.NotNull(code, nameof(code)); + + var mergedCodes = await GetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, cancellationToken) ?? ""; + var splitCodes = mergedCodes.Split(';'); + if (splitCodes.Contains(code)) { - cancellationToken.ThrowIfCancellationRequested(); - - Check.NotNull(user, nameof(user)); - Check.NotNull(code, nameof(code)); - - var mergedCodes = await GetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, cancellationToken) ?? ""; - var splitCodes = mergedCodes.Split(';'); - if (splitCodes.Contains(code)) - { - var updatedCodes = new List(splitCodes.Where(s => s != code)); - await ReplaceCodesAsync(user, updatedCodes, cancellationToken); - return true; - } - return false; + var updatedCodes = new List(splitCodes.Where(s => s != code)); + await ReplaceCodesAsync(user, updatedCodes, cancellationToken); + return true; } + return false; + } - public virtual void Dispose() - { + public virtual void Dispose() + { - } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserToken.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserToken.cs index 0431a533b4..e944029c31 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserToken.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserToken.cs @@ -3,60 +3,59 @@ using JetBrains.Annotations; using Volo.Abp.Domain.Entities; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Represents an authentication token for a user. +/// +public class IdentityUserToken : Entity, IMultiTenant { + public virtual Guid? TenantId { get; protected set; } + + /// + /// Gets or sets the primary key of the user that the token belongs to. + /// + public virtual Guid UserId { get; protected set; } + /// - /// Represents an authentication token for a user. + /// Gets or sets the LoginProvider this token is from. /// - public class IdentityUserToken : Entity, IMultiTenant + public virtual string LoginProvider { get; protected set; } + + /// + /// Gets or sets the name of the token. + /// + public virtual string Name { get; protected set; } + + /// + /// Gets or sets the token value. + /// + public virtual string Value { get; set; } + + protected IdentityUserToken() + { + + } + + protected internal IdentityUserToken( + Guid userId, + [NotNull] string loginProvider, + [NotNull] string name, + string value, + Guid? tenantId) + { + Check.NotNull(loginProvider, nameof(loginProvider)); + Check.NotNull(name, nameof(name)); + + UserId = userId; + LoginProvider = loginProvider; + Name = name; + Value = value; + TenantId = tenantId; + } + + public override object[] GetKeys() { - public virtual Guid? TenantId { get; protected set; } - - /// - /// Gets or sets the primary key of the user that the token belongs to. - /// - public virtual Guid UserId { get; protected set; } - - /// - /// Gets or sets the LoginProvider this token is from. - /// - public virtual string LoginProvider { get; protected set; } - - /// - /// Gets or sets the name of the token. - /// - public virtual string Name { get; protected set; } - - /// - /// Gets or sets the token value. - /// - public virtual string Value { get; set; } - - protected IdentityUserToken() - { - - } - - protected internal IdentityUserToken( - Guid userId, - [NotNull] string loginProvider, - [NotNull] string name, - string value, - Guid? tenantId) - { - Check.NotNull(loginProvider, nameof(loginProvider)); - Check.NotNull(name, nameof(name)); - - UserId = userId; - LoginProvider = loginProvider; - Name = name; - Value = value; - TenantId = tenantId; - } - - public override object[] GetKeys() - { - return new object[] { UserId, LoginProvider, Name }; - } + return new object[] { UserId, LoginProvider, Name }; } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnit.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnit.cs index 53411c1849..6bcf49ab55 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnit.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnit.cs @@ -5,209 +5,208 @@ using System.Linq; using Volo.Abp.Domain.Entities.Auditing; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Represents an organization unit (OU). +/// +public class OrganizationUnit : FullAuditedAggregateRoot, IMultiTenant { + public virtual Guid? TenantId { get; protected set; } + + /// + /// Parent Id. + /// Null, if this OU is a root. + /// + public virtual Guid? ParentId { get; internal set; } + + /// + /// Hierarchical Code of this organization unit. + /// Example: "00001.00042.00005". + /// This is a unique code for an OrganizationUnit. + /// It's changeable if OU hierarchy is changed. + /// + public virtual string Code { get; internal set; } + + /// + /// Display name of this OrganizationUnit. + /// + public virtual string DisplayName { get; set; } + + /// + /// Roles of this OU. + /// + public virtual ICollection Roles { get; protected set; } + /// - /// Represents an organization unit (OU). + /// Initializes a new instance of the class. /// - public class OrganizationUnit : FullAuditedAggregateRoot, IMultiTenant + public OrganizationUnit() { - public virtual Guid? TenantId { get; protected set; } - - /// - /// Parent Id. - /// Null, if this OU is a root. - /// - public virtual Guid? ParentId { get; internal set; } - - /// - /// Hierarchical Code of this organization unit. - /// Example: "00001.00042.00005". - /// This is a unique code for an OrganizationUnit. - /// It's changeable if OU hierarchy is changed. - /// - public virtual string Code { get; internal set; } - - /// - /// Display name of this OrganizationUnit. - /// - public virtual string DisplayName { get; set; } - - /// - /// Roles of this OU. - /// - public virtual ICollection Roles { get; protected set; } - - /// - /// Initializes a new instance of the class. - /// - public OrganizationUnit() - { - } + } - /// - /// Initializes a new instance of the class. - /// - /// id - /// Display name. - /// Parent's Id or null if OU is a root. - /// Tenant's Id or null for host. - public OrganizationUnit(Guid id, string displayName, Guid? parentId = null, Guid? tenantId = null) - : base(id) + /// + /// Initializes a new instance of the class. + /// + /// id + /// Display name. + /// Parent's Id or null if OU is a root. + /// Tenant's Id or null for host. + public OrganizationUnit(Guid id, string displayName, Guid? parentId = null, Guid? tenantId = null) + : base(id) + { + TenantId = tenantId; + DisplayName = displayName; + ParentId = parentId; + Roles = new Collection(); + } + + /// + /// Creates code for given numbers. + /// Example: if numbers are 4,2 then returns "00004.00002"; + /// + /// Numbers + public static string CreateCode(params int[] numbers) + { + if (numbers.IsNullOrEmpty()) { - TenantId = tenantId; - DisplayName = displayName; - ParentId = parentId; - Roles = new Collection(); + return null; } - /// - /// Creates code for given numbers. - /// Example: if numbers are 4,2 then returns "00004.00002"; - /// - /// Numbers - public static string CreateCode(params int[] numbers) - { - if (numbers.IsNullOrEmpty()) - { - return null; - } + return numbers.Select(number => number.ToString(new string('0', OrganizationUnitConsts.CodeUnitLength))).JoinAsString("."); + } - return numbers.Select(number => number.ToString(new string('0', OrganizationUnitConsts.CodeUnitLength))).JoinAsString("."); + /// + /// Appends a child code to a parent code. + /// Example: if parentCode = "00001", childCode = "00042" then returns "00001.00042". + /// + /// Parent code. Can be null or empty if parent is a root. + /// Child code. + public static string AppendCode(string parentCode, string childCode) + { + if (childCode.IsNullOrEmpty()) + { + throw new ArgumentNullException(nameof(childCode), "childCode can not be null or empty."); } - /// - /// Appends a child code to a parent code. - /// Example: if parentCode = "00001", childCode = "00042" then returns "00001.00042". - /// - /// Parent code. Can be null or empty if parent is a root. - /// Child code. - public static string AppendCode(string parentCode, string childCode) + if (parentCode.IsNullOrEmpty()) { - if (childCode.IsNullOrEmpty()) - { - throw new ArgumentNullException(nameof(childCode), "childCode can not be null or empty."); - } + return childCode; + } - if (parentCode.IsNullOrEmpty()) - { - return childCode; - } + return parentCode + "." + childCode; + } - return parentCode + "." + childCode; + /// + /// Gets relative code to the parent. + /// Example: if code = "00019.00055.00001" and parentCode = "00019" then returns "00055.00001". + /// + /// The code. + /// The parent code. + public static string GetRelativeCode(string code, string parentCode) + { + if (code.IsNullOrEmpty()) + { + throw new ArgumentNullException(nameof(code), "code can not be null or empty."); } - /// - /// Gets relative code to the parent. - /// Example: if code = "00019.00055.00001" and parentCode = "00019" then returns "00055.00001". - /// - /// The code. - /// The parent code. - public static string GetRelativeCode(string code, string parentCode) + if (parentCode.IsNullOrEmpty()) { - if (code.IsNullOrEmpty()) - { - throw new ArgumentNullException(nameof(code), "code can not be null or empty."); - } - - if (parentCode.IsNullOrEmpty()) - { - return code; - } - - if (code.Length == parentCode.Length) - { - return null; - } - - return code.Substring(parentCode.Length + 1); + return code; } - /// - /// Calculates next code for given code. - /// Example: if code = "00019.00055.00001" returns "00019.00055.00002". - /// - /// The code. - public static string CalculateNextCode(string code) + if (code.Length == parentCode.Length) { - if (code.IsNullOrEmpty()) - { - throw new ArgumentNullException(nameof(code), "code can not be null or empty."); - } + return null; + } - var parentCode = GetParentCode(code); - var lastUnitCode = GetLastUnitCode(code); + return code.Substring(parentCode.Length + 1); + } - return AppendCode(parentCode, CreateCode(Convert.ToInt32(lastUnitCode) + 1)); + /// + /// Calculates next code for given code. + /// Example: if code = "00019.00055.00001" returns "00019.00055.00002". + /// + /// The code. + public static string CalculateNextCode(string code) + { + if (code.IsNullOrEmpty()) + { + throw new ArgumentNullException(nameof(code), "code can not be null or empty."); } - /// - /// Gets the last unit code. - /// Example: if code = "00019.00055.00001" returns "00001". - /// - /// The code. - public static string GetLastUnitCode(string code) - { - if (code.IsNullOrEmpty()) - { - throw new ArgumentNullException(nameof(code), "code can not be null or empty."); - } + var parentCode = GetParentCode(code); + var lastUnitCode = GetLastUnitCode(code); - var splittedCode = code.Split('.'); - return splittedCode[splittedCode.Length - 1]; + return AppendCode(parentCode, CreateCode(Convert.ToInt32(lastUnitCode) + 1)); + } + + /// + /// Gets the last unit code. + /// Example: if code = "00019.00055.00001" returns "00001". + /// + /// The code. + public static string GetLastUnitCode(string code) + { + if (code.IsNullOrEmpty()) + { + throw new ArgumentNullException(nameof(code), "code can not be null or empty."); } - /// - /// Gets parent code. - /// Example: if code = "00019.00055.00001" returns "00019.00055". - /// - /// The code. - public static string GetParentCode(string code) + var splittedCode = code.Split('.'); + return splittedCode[splittedCode.Length - 1]; + } + + /// + /// Gets parent code. + /// Example: if code = "00019.00055.00001" returns "00019.00055". + /// + /// The code. + public static string GetParentCode(string code) + { + if (code.IsNullOrEmpty()) { - if (code.IsNullOrEmpty()) - { - throw new ArgumentNullException(nameof(code), "code can not be null or empty."); - } - - var splittedCode = code.Split('.'); - if (splittedCode.Length == 1) - { - return null; - } - - return splittedCode.Take(splittedCode.Length - 1).JoinAsString("."); + throw new ArgumentNullException(nameof(code), "code can not be null or empty."); } - public virtual void AddRole(Guid roleId) + var splittedCode = code.Split('.'); + if (splittedCode.Length == 1) { - Check.NotNull(roleId, nameof(roleId)); + return null; + } - if (IsInRole(roleId)) - { - return; - } + return splittedCode.Take(splittedCode.Length - 1).JoinAsString("."); + } - Roles.Add(new OrganizationUnitRole(roleId, Id, TenantId)); - } + public virtual void AddRole(Guid roleId) + { + Check.NotNull(roleId, nameof(roleId)); - public virtual void RemoveRole(Guid roleId) + if (IsInRole(roleId)) { - Check.NotNull(roleId, nameof(roleId)); + return; + } - if (!IsInRole(roleId)) - { - return; - } + Roles.Add(new OrganizationUnitRole(roleId, Id, TenantId)); + } - Roles.RemoveAll(r => r.RoleId == roleId); - } + public virtual void RemoveRole(Guid roleId) + { + Check.NotNull(roleId, nameof(roleId)); - public virtual bool IsInRole(Guid roleId) + if (!IsInRole(roleId)) { - Check.NotNull(roleId, nameof(roleId)); - - return Roles.Any(r => r.RoleId == roleId); + return; } + + Roles.RemoveAll(r => r.RoleId == roleId); + } + + public virtual bool IsInRole(Guid roleId) + { + Check.NotNull(roleId, nameof(roleId)); + + return Roles.Any(r => r.RoleId == roleId); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnitManager.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnitManager.cs index 3dee9a902c..000781d4ef 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnitManager.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnitManager.cs @@ -8,191 +8,190 @@ using Volo.Abp.Identity.Localization; using Volo.Abp.Threading; using Volo.Abp.Uow; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Performs domain logic for Organization Units. +/// +public class OrganizationUnitManager : DomainService { - /// - /// Performs domain logic for Organization Units. - /// - public class OrganizationUnitManager : DomainService + protected IOrganizationUnitRepository OrganizationUnitRepository { get; } + protected IStringLocalizer Localizer { get; } + protected IIdentityRoleRepository IdentityRoleRepository { get; } + protected ICancellationTokenProvider CancellationTokenProvider { get; } + + public OrganizationUnitManager( + IOrganizationUnitRepository organizationUnitRepository, + IStringLocalizer localizer, + IIdentityRoleRepository identityRoleRepository, + ICancellationTokenProvider cancellationTokenProvider) { - protected IOrganizationUnitRepository OrganizationUnitRepository { get; } - protected IStringLocalizer Localizer { get; } - protected IIdentityRoleRepository IdentityRoleRepository { get; } - protected ICancellationTokenProvider CancellationTokenProvider { get; } - - public OrganizationUnitManager( - IOrganizationUnitRepository organizationUnitRepository, - IStringLocalizer localizer, - IIdentityRoleRepository identityRoleRepository, - ICancellationTokenProvider cancellationTokenProvider) - { - OrganizationUnitRepository = organizationUnitRepository; - Localizer = localizer; - IdentityRoleRepository = identityRoleRepository; - CancellationTokenProvider = cancellationTokenProvider; - } - - [UnitOfWork] - public virtual async Task CreateAsync(OrganizationUnit organizationUnit) - { - organizationUnit.Code = await GetNextChildCodeAsync(organizationUnit.ParentId); - await ValidateOrganizationUnitAsync(organizationUnit); - await OrganizationUnitRepository.InsertAsync(organizationUnit); - } + OrganizationUnitRepository = organizationUnitRepository; + Localizer = localizer; + IdentityRoleRepository = identityRoleRepository; + CancellationTokenProvider = cancellationTokenProvider; + } - public virtual async Task UpdateAsync(OrganizationUnit organizationUnit) - { - await ValidateOrganizationUnitAsync(organizationUnit); - await OrganizationUnitRepository.UpdateAsync(organizationUnit); - } + [UnitOfWork] + public virtual async Task CreateAsync(OrganizationUnit organizationUnit) + { + organizationUnit.Code = await GetNextChildCodeAsync(organizationUnit.ParentId); + await ValidateOrganizationUnitAsync(organizationUnit); + await OrganizationUnitRepository.InsertAsync(organizationUnit); + } - public virtual async Task GetNextChildCodeAsync(Guid? parentId) - { - var lastChild = await GetLastChildOrNullAsync(parentId); - if (lastChild != null) - { - return OrganizationUnit.CalculateNextCode(lastChild.Code); - } - - var parentCode = parentId != null - ? await GetCodeOrDefaultAsync(parentId.Value) - : null; - - return OrganizationUnit.AppendCode( - parentCode, - OrganizationUnit.CreateCode(1) - ); - } + public virtual async Task UpdateAsync(OrganizationUnit organizationUnit) + { + await ValidateOrganizationUnitAsync(organizationUnit); + await OrganizationUnitRepository.UpdateAsync(organizationUnit); + } - public virtual async Task GetLastChildOrNullAsync(Guid? parentId) + public virtual async Task GetNextChildCodeAsync(Guid? parentId) + { + var lastChild = await GetLastChildOrNullAsync(parentId); + if (lastChild != null) { - var children = await OrganizationUnitRepository.GetChildrenAsync(parentId); - return children.OrderBy(c => c.Code).LastOrDefault(); + return OrganizationUnit.CalculateNextCode(lastChild.Code); } - [UnitOfWork] - public virtual async Task DeleteAsync(Guid id) - { - var children = await FindChildrenAsync(id, true); + var parentCode = parentId != null + ? await GetCodeOrDefaultAsync(parentId.Value) + : null; - foreach (var child in children) - { - await OrganizationUnitRepository.RemoveAllMembersAsync(child); - await OrganizationUnitRepository.RemoveAllRolesAsync(child); - await OrganizationUnitRepository.DeleteAsync(child); - } + return OrganizationUnit.AppendCode( + parentCode, + OrganizationUnit.CreateCode(1) + ); + } - var organizationUnit = await OrganizationUnitRepository.GetAsync(id); + public virtual async Task GetLastChildOrNullAsync(Guid? parentId) + { + var children = await OrganizationUnitRepository.GetChildrenAsync(parentId); + return children.OrderBy(c => c.Code).LastOrDefault(); + } - await OrganizationUnitRepository.RemoveAllMembersAsync(organizationUnit); - await OrganizationUnitRepository.RemoveAllRolesAsync(organizationUnit); - await OrganizationUnitRepository.DeleteAsync(id); - } + [UnitOfWork] + public virtual async Task DeleteAsync(Guid id) + { + var children = await FindChildrenAsync(id, true); - [UnitOfWork] - public virtual async Task MoveAsync(Guid id, Guid? parentId) + foreach (var child in children) { - var organizationUnit = await OrganizationUnitRepository.GetAsync(id); - if (organizationUnit.ParentId == parentId) - { - return; - } + await OrganizationUnitRepository.RemoveAllMembersAsync(child); + await OrganizationUnitRepository.RemoveAllRolesAsync(child); + await OrganizationUnitRepository.DeleteAsync(child); + } - //Should find children before Code change - var children = await FindChildrenAsync(id, true); + var organizationUnit = await OrganizationUnitRepository.GetAsync(id); - //Store old code of OU - var oldCode = organizationUnit.Code; + await OrganizationUnitRepository.RemoveAllMembersAsync(organizationUnit); + await OrganizationUnitRepository.RemoveAllRolesAsync(organizationUnit); + await OrganizationUnitRepository.DeleteAsync(id); + } - //Move OU - organizationUnit.Code = await GetNextChildCodeAsync(parentId); - organizationUnit.ParentId = parentId; + [UnitOfWork] + public virtual async Task MoveAsync(Guid id, Guid? parentId) + { + var organizationUnit = await OrganizationUnitRepository.GetAsync(id); + if (organizationUnit.ParentId == parentId) + { + return; + } - await ValidateOrganizationUnitAsync(organizationUnit); + //Should find children before Code change + var children = await FindChildrenAsync(id, true); - //Update Children Codes - foreach (var child in children) - { - child.Code = OrganizationUnit.AppendCode(organizationUnit.Code, OrganizationUnit.GetRelativeCode(child.Code, oldCode)); - await OrganizationUnitRepository.UpdateAsync(child); - } + //Store old code of OU + var oldCode = organizationUnit.Code; - await OrganizationUnitRepository.UpdateAsync(organizationUnit); - } + //Move OU + organizationUnit.Code = await GetNextChildCodeAsync(parentId); + organizationUnit.ParentId = parentId; - public virtual async Task GetCodeOrDefaultAsync(Guid id) - { - var ou = await OrganizationUnitRepository.GetAsync(id); - return ou?.Code; - } + await ValidateOrganizationUnitAsync(organizationUnit); - protected virtual async Task ValidateOrganizationUnitAsync(OrganizationUnit organizationUnit) + //Update Children Codes + foreach (var child in children) { - var siblings = (await FindChildrenAsync(organizationUnit.ParentId)) - .Where(ou => ou.Id != organizationUnit.Id) - .ToList(); - - if (siblings.Any(ou => ou.DisplayName == organizationUnit.DisplayName)) - { - throw new BusinessException(IdentityErrorCodes.DuplicateOrganizationUnitDisplayName) - .WithData("0", organizationUnit.DisplayName); - } + child.Code = OrganizationUnit.AppendCode(organizationUnit.Code, OrganizationUnit.GetRelativeCode(child.Code, oldCode)); + await OrganizationUnitRepository.UpdateAsync(child); } - public async Task> FindChildrenAsync(Guid? parentId, bool recursive = false) - { - if (!recursive) - { - return await OrganizationUnitRepository.GetChildrenAsync(parentId, includeDetails: true); - } - - if (!parentId.HasValue) - { - return await OrganizationUnitRepository.GetListAsync(includeDetails: true); - } + await OrganizationUnitRepository.UpdateAsync(organizationUnit); + } - var code = await GetCodeOrDefaultAsync(parentId.Value); + public virtual async Task GetCodeOrDefaultAsync(Guid id) + { + var ou = await OrganizationUnitRepository.GetAsync(id); + return ou?.Code; + } - return await OrganizationUnitRepository.GetAllChildrenWithParentCodeAsync(code, parentId, includeDetails: true); - } + protected virtual async Task ValidateOrganizationUnitAsync(OrganizationUnit organizationUnit) + { + var siblings = (await FindChildrenAsync(organizationUnit.ParentId)) + .Where(ou => ou.Id != organizationUnit.Id) + .ToList(); - public virtual Task IsInOrganizationUnitAsync(IdentityUser user, OrganizationUnit ou) + if (siblings.Any(ou => ou.DisplayName == organizationUnit.DisplayName)) { - return Task.FromResult(user.IsInOrganizationUnit(ou.Id)); + throw new BusinessException(IdentityErrorCodes.DuplicateOrganizationUnitDisplayName) + .WithData("0", organizationUnit.DisplayName); } + } - public virtual async Task AddRoleToOrganizationUnitAsync(Guid roleId, Guid ouId) + public async Task> FindChildrenAsync(Guid? parentId, bool recursive = false) + { + if (!recursive) { - await AddRoleToOrganizationUnitAsync( - await IdentityRoleRepository.GetAsync(roleId), - await OrganizationUnitRepository.GetAsync(ouId, true) - ); + return await OrganizationUnitRepository.GetChildrenAsync(parentId, includeDetails: true); } - public virtual Task AddRoleToOrganizationUnitAsync(IdentityRole role, OrganizationUnit ou) + if (!parentId.HasValue) { - var currentRoles = ou.Roles; - - if (currentRoles.Any(r => r.OrganizationUnitId == ou.Id && r.RoleId == role.Id)) - { - return Task.FromResult(0); - } - ou.AddRole(role.Id); - return OrganizationUnitRepository.UpdateAsync(ou); + return await OrganizationUnitRepository.GetListAsync(includeDetails: true); } - public virtual async Task RemoveRoleFromOrganizationUnitAsync(Guid roleId, Guid ouId) - { - await RemoveRoleFromOrganizationUnitAsync( - await IdentityRoleRepository.GetAsync(roleId), - await OrganizationUnitRepository.GetAsync(ouId, true) - ); - } + var code = await GetCodeOrDefaultAsync(parentId.Value); + + return await OrganizationUnitRepository.GetAllChildrenWithParentCodeAsync(code, parentId, includeDetails: true); + } + + public virtual Task IsInOrganizationUnitAsync(IdentityUser user, OrganizationUnit ou) + { + return Task.FromResult(user.IsInOrganizationUnit(ou.Id)); + } + + public virtual async Task AddRoleToOrganizationUnitAsync(Guid roleId, Guid ouId) + { + await AddRoleToOrganizationUnitAsync( + await IdentityRoleRepository.GetAsync(roleId), + await OrganizationUnitRepository.GetAsync(ouId, true) + ); + } + + public virtual Task AddRoleToOrganizationUnitAsync(IdentityRole role, OrganizationUnit ou) + { + var currentRoles = ou.Roles; - public virtual Task RemoveRoleFromOrganizationUnitAsync(IdentityRole role, OrganizationUnit organizationUnit) + if (currentRoles.Any(r => r.OrganizationUnitId == ou.Id && r.RoleId == role.Id)) { - organizationUnit.RemoveRole(role.Id); - return OrganizationUnitRepository.UpdateAsync(organizationUnit); + return Task.FromResult(0); } + ou.AddRole(role.Id); + return OrganizationUnitRepository.UpdateAsync(ou); + } + + public virtual async Task RemoveRoleFromOrganizationUnitAsync(Guid roleId, Guid ouId) + { + await RemoveRoleFromOrganizationUnitAsync( + await IdentityRoleRepository.GetAsync(roleId), + await OrganizationUnitRepository.GetAsync(ouId, true) + ); + } + + public virtual Task RemoveRoleFromOrganizationUnitAsync(IdentityRole role, OrganizationUnit organizationUnit) + { + organizationUnit.RemoveRole(role.Id); + return OrganizationUnitRepository.UpdateAsync(organizationUnit); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnitRole.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnitRole.cs index 43aca1e272..2f8e9b3baf 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnitRole.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/OrganizationUnitRole.cs @@ -2,52 +2,51 @@ using Volo.Abp.Domain.Entities.Auditing; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +/// +/// Represents membership of a User to an OU. +/// +public class OrganizationUnitRole : CreationAuditedEntity, IMultiTenant { /// - /// Represents membership of a User to an OU. + /// TenantId of this entity. + /// + public virtual Guid? TenantId { get; protected set; } + + /// + /// Id of the Role. + /// + public virtual Guid RoleId { get; protected set; } + + /// + /// Id of the . + /// + public virtual Guid OrganizationUnitId { get; protected set; } + + /// + /// Initializes a new instance of the class. /// - public class OrganizationUnitRole : CreationAuditedEntity, IMultiTenant + protected OrganizationUnitRole() + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// TenantId + /// Id of the User. + /// Id of the . + public OrganizationUnitRole(Guid roleId, Guid organizationUnitId, Guid? tenantId = null) + { + RoleId = roleId; + OrganizationUnitId = organizationUnitId; + TenantId = tenantId; + } + + public override object[] GetKeys() { - /// - /// TenantId of this entity. - /// - public virtual Guid? TenantId { get; protected set; } - - /// - /// Id of the Role. - /// - public virtual Guid RoleId { get; protected set; } - - /// - /// Id of the . - /// - public virtual Guid OrganizationUnitId { get; protected set; } - - /// - /// Initializes a new instance of the class. - /// - protected OrganizationUnitRole() - { - - } - - /// - /// Initializes a new instance of the class. - /// - /// TenantId - /// Id of the User. - /// Id of the . - public OrganizationUnitRole(Guid roleId, Guid organizationUnitId, Guid? tenantId = null) - { - RoleId = roleId; - OrganizationUnitId = organizationUnitId; - TenantId = tenantId; - } - - public override object[] GetKeys() - { - return new object[] { OrganizationUnitId, RoleId }; - } + return new object[] { OrganizationUnitId, RoleId }; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/UserRoleFinder.cs b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/UserRoleFinder.cs index 7886865369..ff19e61988 100644 --- a/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/UserRoleFinder.cs +++ b/modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/UserRoleFinder.cs @@ -2,20 +2,19 @@ using System.Threading.Tasks; using Volo.Abp.DependencyInjection; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class UserRoleFinder : IUserRoleFinder, ITransientDependency { - public class UserRoleFinder : IUserRoleFinder, ITransientDependency - { - protected IIdentityUserRepository IdentityUserRepository { get; } + protected IIdentityUserRepository IdentityUserRepository { get; } - public UserRoleFinder(IIdentityUserRepository identityUserRepository) - { - IdentityUserRepository = identityUserRepository; - } + public UserRoleFinder(IIdentityUserRepository identityUserRepository) + { + IdentityUserRepository = identityUserRepository; + } - public virtual async Task GetRolesAsync(Guid userId) - { - return (await IdentityUserRepository.GetRoleNamesAsync(userId)).ToArray(); - } + public virtual async Task GetRolesAsync(Guid userId) + { + return (await IdentityUserRepository.GetRoleNamesAsync(userId)).ToArray(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreModule.cs b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreModule.cs index 92f248b87a..4bfa96d253 100644 --- a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreModule.cs @@ -2,24 +2,23 @@ using Volo.Abp.Modularity; using Volo.Abp.Users.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +[DependsOn( + typeof(AbpIdentityDomainModule), + typeof(AbpUsersEntityFrameworkCoreModule))] +public class AbpIdentityEntityFrameworkCoreModule : AbpModule { - [DependsOn( - typeof(AbpIdentityDomainModule), - typeof(AbpUsersEntityFrameworkCoreModule))] - public class AbpIdentityEntityFrameworkCoreModule : AbpModule + public override void ConfigureServices(ServiceConfigurationContext context) { - public override void ConfigureServices(ServiceConfigurationContext context) + context.Services.AddAbpDbContext(options => { - context.Services.AddAbpDbContext(options => - { - options.AddRepository(); - options.AddRepository(); - options.AddRepository(); - options.AddRepository(); - options.AddRepository(); - options.AddRepository(); - }); - } + options.AddRepository(); + options.AddRepository(); + options.AddRepository(); + options.AddRepository(); + options.AddRepository(); + options.AddRepository(); + }); } } diff --git a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EFCoreIdentitySecurityLogRepository.cs b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EFCoreIdentitySecurityLogRepository.cs index 97de4c0ecf..0e5c2a9b4c 100644 --- a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EFCoreIdentitySecurityLogRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EFCoreIdentitySecurityLogRepository.cs @@ -8,111 +8,110 @@ using Microsoft.EntityFrameworkCore; using Volo.Abp.Domain.Repositories.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class EFCoreIdentitySecurityLogRepository : EfCoreRepository, IIdentitySecurityLogRepository { - public class EFCoreIdentitySecurityLogRepository : EfCoreRepository, IIdentitySecurityLogRepository + public EFCoreIdentitySecurityLogRepository(IDbContextProvider dbContextProvider) + : base(dbContextProvider) { - public EFCoreIdentitySecurityLogRepository(IDbContextProvider dbContextProvider) - : base(dbContextProvider) - { - } + } - public virtual async Task> GetListAsync( - string sorting = null, - int maxResultCount = 50, - int skipCount = 0, - DateTime? startTime = null, - DateTime? endTime = null, - string applicationName = null, - string identity = null, - string action = null, - Guid? userId = null, - string userName = null, - string clientId = null, - string correlationId = null, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - cancellationToken = GetCancellationToken(cancellationToken); + public virtual async Task> GetListAsync( + string sorting = null, + int maxResultCount = 50, + int skipCount = 0, + DateTime? startTime = null, + DateTime? endTime = null, + string applicationName = null, + string identity = null, + string action = null, + Guid? userId = null, + string userName = null, + string clientId = null, + string correlationId = null, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + cancellationToken = GetCancellationToken(cancellationToken); - var query = await GetListQueryAsync( - startTime, - endTime, - applicationName, - identity, - action, - userId, - userName, - clientId, - correlationId, - cancellationToken - ); + var query = await GetListQueryAsync( + startTime, + endTime, + applicationName, + identity, + action, + userId, + userName, + clientId, + correlationId, + cancellationToken + ); - return await query.OrderBy(sorting.IsNullOrWhiteSpace() ? $"{nameof(IdentitySecurityLog.CreationTime)} desc" : sorting) - .PageBy(skipCount, maxResultCount) - .ToListAsync(cancellationToken); - } + return await query.OrderBy(sorting.IsNullOrWhiteSpace() ? $"{nameof(IdentitySecurityLog.CreationTime)} desc" : sorting) + .PageBy(skipCount, maxResultCount) + .ToListAsync(cancellationToken); + } - public virtual async Task GetCountAsync( - DateTime? startTime = null, - DateTime? endTime = null, - string applicationName = null, - string identity = null, - string action = null, - Guid? userId = null, - string userName = null, - string clientId = null, - string correlationId = null, - CancellationToken cancellationToken = default) - { - cancellationToken = GetCancellationToken(cancellationToken); + public virtual async Task GetCountAsync( + DateTime? startTime = null, + DateTime? endTime = null, + string applicationName = null, + string identity = null, + string action = null, + Guid? userId = null, + string userName = null, + string clientId = null, + string correlationId = null, + CancellationToken cancellationToken = default) + { + cancellationToken = GetCancellationToken(cancellationToken); - var query = await GetListQueryAsync( - startTime, - endTime, - applicationName, - identity, - action, - userId, - userName, - clientId, - correlationId, - cancellationToken - ); + var query = await GetListQueryAsync( + startTime, + endTime, + applicationName, + identity, + action, + userId, + userName, + clientId, + correlationId, + cancellationToken + ); - return await query.LongCountAsync(cancellationToken); - } + return await query.LongCountAsync(cancellationToken); + } - public virtual async Task GetByUserIdAsync(Guid id, Guid userId, bool includeDetails = false, CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .OrderBy(x => x.Id) - .FirstOrDefaultAsync(x => x.Id == id && x.UserId == userId, GetCancellationToken(cancellationToken)); - } + public virtual async Task GetByUserIdAsync(Guid id, Guid userId, bool includeDetails = false, CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync(x => x.Id == id && x.UserId == userId, GetCancellationToken(cancellationToken)); + } - protected virtual async Task> GetListQueryAsync( - DateTime? startTime = null, - DateTime? endTime = null, - string applicationName = null, - string identity = null, - string action = null, - Guid? userId = null, - string userName = null, - string clientId = null, - string correlationId = null, - CancellationToken cancellationToken = default) - { - return (await GetDbSetAsync()).AsNoTracking() - .WhereIf(startTime.HasValue, securityLog => securityLog.CreationTime >= startTime.Value) - .WhereIf(endTime.HasValue, securityLog => securityLog.CreationTime < endTime.Value.AddDays(1).Date) - .WhereIf(!applicationName.IsNullOrWhiteSpace(), securityLog => securityLog.ApplicationName == applicationName) - .WhereIf(!identity.IsNullOrWhiteSpace(), securityLog => securityLog.Identity == identity) - .WhereIf(!action.IsNullOrWhiteSpace(), securityLog => securityLog.Action == action) - .WhereIf(userId.HasValue, securityLog => securityLog.UserId == userId) - .WhereIf(!userName.IsNullOrWhiteSpace(), securityLog => securityLog.UserName == userName) - .WhereIf(!clientId.IsNullOrWhiteSpace(), securityLog => securityLog.ClientId == clientId) - .WhereIf(!correlationId.IsNullOrWhiteSpace(), securityLog => securityLog.CorrelationId == correlationId); - } + protected virtual async Task> GetListQueryAsync( + DateTime? startTime = null, + DateTime? endTime = null, + string applicationName = null, + string identity = null, + string action = null, + Guid? userId = null, + string userName = null, + string clientId = null, + string correlationId = null, + CancellationToken cancellationToken = default) + { + return (await GetDbSetAsync()).AsNoTracking() + .WhereIf(startTime.HasValue, securityLog => securityLog.CreationTime >= startTime.Value) + .WhereIf(endTime.HasValue, securityLog => securityLog.CreationTime < endTime.Value.AddDays(1).Date) + .WhereIf(!applicationName.IsNullOrWhiteSpace(), securityLog => securityLog.ApplicationName == applicationName) + .WhereIf(!identity.IsNullOrWhiteSpace(), securityLog => securityLog.Identity == identity) + .WhereIf(!action.IsNullOrWhiteSpace(), securityLog => securityLog.Action == action) + .WhereIf(userId.HasValue, securityLog => securityLog.UserId == userId) + .WhereIf(!userName.IsNullOrWhiteSpace(), securityLog => securityLog.UserName == userName) + .WhereIf(!clientId.IsNullOrWhiteSpace(), securityLog => securityLog.ClientId == clientId) + .WhereIf(!correlationId.IsNullOrWhiteSpace(), securityLog => securityLog.CorrelationId == correlationId); } } diff --git a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityClaimTypeRepository.cs b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityClaimTypeRepository.cs index 6cef5454f1..d2ebbf79ba 100644 --- a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityClaimTypeRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityClaimTypeRepository.cs @@ -8,55 +8,54 @@ using Microsoft.EntityFrameworkCore; using Volo.Abp.Domain.Repositories.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class EfCoreIdentityClaimTypeRepository : EfCoreRepository, IIdentityClaimTypeRepository { - public class EfCoreIdentityClaimTypeRepository : EfCoreRepository, IIdentityClaimTypeRepository + public EfCoreIdentityClaimTypeRepository(IDbContextProvider dbContextProvider) + : base(dbContextProvider) { - public EfCoreIdentityClaimTypeRepository(IDbContextProvider dbContextProvider) - : base(dbContextProvider) - { - } + } - public virtual async Task AnyAsync( - string name, - Guid? ignoredId = null, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .WhereIf(ignoredId != null, ct => ct.Id != ignoredId) - .CountAsync(ct => ct.Name == name, GetCancellationToken(cancellationToken)) > 0; - } + public virtual async Task AnyAsync( + string name, + Guid? ignoredId = null, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .WhereIf(ignoredId != null, ct => ct.Id != ignoredId) + .CountAsync(ct => ct.Name == name, GetCancellationToken(cancellationToken)) > 0; + } - public virtual async Task> GetListAsync( - string sorting, - int maxResultCount, - int skipCount, - string filter, - CancellationToken cancellationToken = default) - { - var identityClaimTypes = await (await GetDbSetAsync()) - .WhereIf( - !filter.IsNullOrWhiteSpace(), - u => - u.Name.Contains(filter) - ) - .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityClaimType.Name) : sorting) - .PageBy(skipCount, maxResultCount) - .ToListAsync(GetCancellationToken(cancellationToken)); + public virtual async Task> GetListAsync( + string sorting, + int maxResultCount, + int skipCount, + string filter, + CancellationToken cancellationToken = default) + { + var identityClaimTypes = await (await GetDbSetAsync()) + .WhereIf( + !filter.IsNullOrWhiteSpace(), + u => + u.Name.Contains(filter) + ) + .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityClaimType.Name) : sorting) + .PageBy(skipCount, maxResultCount) + .ToListAsync(GetCancellationToken(cancellationToken)); - return identityClaimTypes; - } + return identityClaimTypes; + } - public virtual async Task GetCountAsync( - string filter = null, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .WhereIf( - !filter.IsNullOrWhiteSpace(), - u => - u.Name.Contains(filter) - ).LongCountAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task GetCountAsync( + string filter = null, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .WhereIf( + !filter.IsNullOrWhiteSpace(), + u => + u.Name.Contains(filter) + ).LongCountAsync(GetCancellationToken(cancellationToken)); } } diff --git a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityLinkUserRepository.cs b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityLinkUserRepository.cs index ab76f0cc48..6a0245fa4f 100644 --- a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityLinkUserRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityLinkUserRepository.cs @@ -7,56 +7,55 @@ using Microsoft.EntityFrameworkCore; using Volo.Abp.Domain.Repositories.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class EfCoreIdentityLinkUserRepository : EfCoreRepository, IIdentityLinkUserRepository { - public class EfCoreIdentityLinkUserRepository : EfCoreRepository, IIdentityLinkUserRepository + public EfCoreIdentityLinkUserRepository(IDbContextProvider dbContextProvider) + : base(dbContextProvider) { - public EfCoreIdentityLinkUserRepository(IDbContextProvider dbContextProvider) - : base(dbContextProvider) - { - } + } - public virtual async Task FindAsync(IdentityLinkUserInfo sourceLinkUserInfo, IdentityLinkUserInfo targetLinkUserInfo, CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .OrderBy(x => x.Id).FirstOrDefaultAsync(x => - x.SourceUserId == sourceLinkUserInfo.UserId && x.SourceTenantId == sourceLinkUserInfo.TenantId && - x.TargetUserId == targetLinkUserInfo.UserId && x.TargetTenantId == targetLinkUserInfo.TenantId || - x.TargetUserId == sourceLinkUserInfo.UserId && x.TargetTenantId == sourceLinkUserInfo.TenantId && - x.SourceUserId == targetLinkUserInfo.UserId && x.SourceTenantId == targetLinkUserInfo.TenantId - , cancellationToken: GetCancellationToken(cancellationToken)); - } + public virtual async Task FindAsync(IdentityLinkUserInfo sourceLinkUserInfo, IdentityLinkUserInfo targetLinkUserInfo, CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .OrderBy(x => x.Id).FirstOrDefaultAsync(x => + x.SourceUserId == sourceLinkUserInfo.UserId && x.SourceTenantId == sourceLinkUserInfo.TenantId && + x.TargetUserId == targetLinkUserInfo.UserId && x.TargetTenantId == targetLinkUserInfo.TenantId || + x.TargetUserId == sourceLinkUserInfo.UserId && x.TargetTenantId == sourceLinkUserInfo.TenantId && + x.SourceUserId == targetLinkUserInfo.UserId && x.SourceTenantId == targetLinkUserInfo.TenantId + , cancellationToken: GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListAsync(IdentityLinkUserInfo linkUserInfo, List excludes = null, - CancellationToken cancellationToken = default) - { - IQueryable query = (await GetDbSetAsync()) - .Where(x => - x.SourceUserId == linkUserInfo.UserId && x.SourceTenantId == linkUserInfo.TenantId || - x.TargetUserId == linkUserInfo.UserId && x.TargetTenantId == linkUserInfo.TenantId); + public virtual async Task> GetListAsync(IdentityLinkUserInfo linkUserInfo, List excludes = null, + CancellationToken cancellationToken = default) + { + IQueryable query = (await GetDbSetAsync()) + .Where(x => + x.SourceUserId == linkUserInfo.UserId && x.SourceTenantId == linkUserInfo.TenantId || + x.TargetUserId == linkUserInfo.UserId && x.TargetTenantId == linkUserInfo.TenantId); - if (!excludes.IsNullOrEmpty()) + if (!excludes.IsNullOrEmpty()) + { + foreach (var userInfo in excludes) { - foreach (var userInfo in excludes) - { - query = query.Where(x => - (x.SourceTenantId != userInfo.TenantId || x.SourceUserId != userInfo.UserId) && - (x.TargetTenantId != userInfo.TenantId || x.TargetUserId != userInfo.UserId)); - } + query = query.Where(x => + (x.SourceTenantId != userInfo.TenantId || x.SourceUserId != userInfo.UserId) && + (x.TargetTenantId != userInfo.TenantId || x.TargetUserId != userInfo.UserId)); } - - return await query.ToListAsync(cancellationToken: GetCancellationToken(cancellationToken)); } - public virtual async Task DeleteAsync(IdentityLinkUserInfo linkUserInfo, CancellationToken cancellationToken = default) - { - var linkUsers = await (await GetDbSetAsync()).Where(x => - x.SourceUserId == linkUserInfo.UserId && x.SourceTenantId == linkUserInfo.TenantId || - x.TargetUserId == linkUserInfo.UserId && x.TargetTenantId == linkUserInfo.TenantId) - .ToListAsync(cancellationToken: GetCancellationToken(cancellationToken)); + return await query.ToListAsync(cancellationToken: GetCancellationToken(cancellationToken)); + } - await DeleteManyAsync(linkUsers, cancellationToken: cancellationToken); - } + public virtual async Task DeleteAsync(IdentityLinkUserInfo linkUserInfo, CancellationToken cancellationToken = default) + { + var linkUsers = await (await GetDbSetAsync()).Where(x => + x.SourceUserId == linkUserInfo.UserId && x.SourceTenantId == linkUserInfo.TenantId || + x.TargetUserId == linkUserInfo.UserId && x.TargetTenantId == linkUserInfo.TenantId) + .ToListAsync(cancellationToken: GetCancellationToken(cancellationToken)); + + await DeleteManyAsync(linkUsers, cancellationToken: cancellationToken); } } diff --git a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityRoleRepository.cs b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityRoleRepository.cs index 558744132e..c659dff653 100644 --- a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityRoleRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityRoleRepository.cs @@ -8,82 +8,81 @@ using Microsoft.EntityFrameworkCore; using Volo.Abp.Domain.Repositories.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class EfCoreIdentityRoleRepository : EfCoreRepository, IIdentityRoleRepository { - public class EfCoreIdentityRoleRepository : EfCoreRepository, IIdentityRoleRepository + public EfCoreIdentityRoleRepository(IDbContextProvider dbContextProvider) + : base(dbContextProvider) { - public EfCoreIdentityRoleRepository(IDbContextProvider dbContextProvider) - : base(dbContextProvider) - { - } + } - public virtual async Task FindByNormalizedNameAsync( - string normalizedRoleName, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .OrderBy(x => x.Id) - .FirstOrDefaultAsync(r => r.NormalizedName == normalizedRoleName, GetCancellationToken(cancellationToken)); - } + public virtual async Task FindByNormalizedNameAsync( + string normalizedRoleName, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync(r => r.NormalizedName == normalizedRoleName, GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListAsync( - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .WhereIf(!filter.IsNullOrWhiteSpace(), - x => x.Name.Contains(filter) || - x.NormalizedName.Contains(filter)) - .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityRole.Name) : sorting) - .PageBy(skipCount, maxResultCount) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetListAsync( + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .WhereIf(!filter.IsNullOrWhiteSpace(), + x => x.Name.Contains(filter) || + x.NormalizedName.Contains(filter)) + .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityRole.Name) : sorting) + .PageBy(skipCount, maxResultCount) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListAsync( - IEnumerable ids, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .Where(t => ids.Contains(t.Id)) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetListAsync( + IEnumerable ids, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .Where(t => ids.Contains(t.Id)) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetDefaultOnesAsync( - bool includeDetails = false, CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .Where(r => r.IsDefault) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetDefaultOnesAsync( + bool includeDetails = false, CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .Where(r => r.IsDefault) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task GetCountAsync( - string filter = null, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .WhereIf(!filter.IsNullOrWhiteSpace(), - x => x.Name.Contains(filter) || - x.NormalizedName.Contains(filter)) - .LongCountAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task GetCountAsync( + string filter = null, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .WhereIf(!filter.IsNullOrWhiteSpace(), + x => x.Name.Contains(filter) || + x.NormalizedName.Contains(filter)) + .LongCountAsync(GetCancellationToken(cancellationToken)); + } - [Obsolete("Use WithDetailsAsync")] - public override IQueryable WithDetails() - { - return GetQueryable().IncludeDetails(); - } + [Obsolete("Use WithDetailsAsync")] + public override IQueryable WithDetails() + { + return GetQueryable().IncludeDetails(); + } - public override async Task> WithDetailsAsync() - { - return (await GetQueryableAsync()).IncludeDetails(); - } + public override async Task> WithDetailsAsync() + { + return (await GetQueryableAsync()).IncludeDetails(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityUserRepository.cs b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityUserRepository.cs index 648c999624..9a989a1ad6 100644 --- a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityUserRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreIdentityUserRepository.cs @@ -9,297 +9,296 @@ using Microsoft.EntityFrameworkCore; using Volo.Abp.Domain.Repositories.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class EfCoreIdentityUserRepository : EfCoreRepository, IIdentityUserRepository { - public class EfCoreIdentityUserRepository : EfCoreRepository, IIdentityUserRepository + public EfCoreIdentityUserRepository(IDbContextProvider dbContextProvider) + : base(dbContextProvider) { - public EfCoreIdentityUserRepository(IDbContextProvider dbContextProvider) - : base(dbContextProvider) - { - } - - public virtual async Task FindByNormalizedUserNameAsync( - string normalizedUserName, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .OrderBy(x => x.Id) - .FirstOrDefaultAsync( - u => u.NormalizedUserName == normalizedUserName, - GetCancellationToken(cancellationToken) - ); - } + } - public virtual async Task> GetRoleNamesAsync( - Guid id, - CancellationToken cancellationToken = default) - { - var dbContext = await GetDbContextAsync(); - var query = from userRole in dbContext.Set() - join role in dbContext.Roles on userRole.RoleId equals role.Id - where userRole.UserId == id - select role.Name; - var organizationUnitIds = dbContext.Set().Where(q => q.UserId == id).Select(q => q.OrganizationUnitId).ToArray(); - - var organizationRoleIds = await ( - from ouRole in dbContext.Set() - join ou in dbContext.Set() on ouRole.OrganizationUnitId equals ou.Id - where organizationUnitIds.Contains(ouRole.OrganizationUnitId) - select ouRole.RoleId - ).ToListAsync(GetCancellationToken(cancellationToken)); - - var orgUnitRoleNameQuery = dbContext.Roles.Where(r => organizationRoleIds.Contains(r.Id)).Select(n => n.Name); - var resultQuery = query.Union(orgUnitRoleNameQuery); - return await resultQuery.ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task FindByNormalizedUserNameAsync( + string normalizedUserName, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync( + u => u.NormalizedUserName == normalizedUserName, + GetCancellationToken(cancellationToken) + ); + } - public virtual async Task> GetRoleNamesInOrganizationUnitAsync( - Guid id, - CancellationToken cancellationToken = default) - { - var dbContext = await GetDbContextAsync(); - var query = from userOu in dbContext.Set() - join roleOu in dbContext.Set() on userOu.OrganizationUnitId equals roleOu.OrganizationUnitId - join ou in dbContext.Set() on roleOu.OrganizationUnitId equals ou.Id - join userOuRoles in dbContext.Roles on roleOu.RoleId equals userOuRoles.Id - where userOu.UserId == id - select userOuRoles.Name; + public virtual async Task> GetRoleNamesAsync( + Guid id, + CancellationToken cancellationToken = default) + { + var dbContext = await GetDbContextAsync(); + var query = from userRole in dbContext.Set() + join role in dbContext.Roles on userRole.RoleId equals role.Id + where userRole.UserId == id + select role.Name; + var organizationUnitIds = dbContext.Set().Where(q => q.UserId == id).Select(q => q.OrganizationUnitId).ToArray(); + + var organizationRoleIds = await ( + from ouRole in dbContext.Set() + join ou in dbContext.Set() on ouRole.OrganizationUnitId equals ou.Id + where organizationUnitIds.Contains(ouRole.OrganizationUnitId) + select ouRole.RoleId + ).ToListAsync(GetCancellationToken(cancellationToken)); + + var orgUnitRoleNameQuery = dbContext.Roles.Where(r => organizationRoleIds.Contains(r.Id)).Select(n => n.Name); + var resultQuery = query.Union(orgUnitRoleNameQuery); + return await resultQuery.ToListAsync(GetCancellationToken(cancellationToken)); + } - var result = await query.ToListAsync(GetCancellationToken(cancellationToken)); + public virtual async Task> GetRoleNamesInOrganizationUnitAsync( + Guid id, + CancellationToken cancellationToken = default) + { + var dbContext = await GetDbContextAsync(); + var query = from userOu in dbContext.Set() + join roleOu in dbContext.Set() on userOu.OrganizationUnitId equals roleOu.OrganizationUnitId + join ou in dbContext.Set() on roleOu.OrganizationUnitId equals ou.Id + join userOuRoles in dbContext.Roles on roleOu.RoleId equals userOuRoles.Id + where userOu.UserId == id + select userOuRoles.Name; - return result; - } + var result = await query.ToListAsync(GetCancellationToken(cancellationToken)); - public virtual async Task FindByLoginAsync( - string loginProvider, - string providerKey, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .Where(u => u.Logins.Any(login => login.LoginProvider == loginProvider && login.ProviderKey == providerKey)) - .OrderBy(x=>x.Id) - .FirstOrDefaultAsync(GetCancellationToken(cancellationToken)); - } + return result; + } - public virtual async Task FindByNormalizedEmailAsync( - string normalizedEmail, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .OrderBy(x => x.Id) - .FirstOrDefaultAsync(u => u.NormalizedEmail == normalizedEmail, GetCancellationToken(cancellationToken)); - } + public virtual async Task FindByLoginAsync( + string loginProvider, + string providerKey, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .Where(u => u.Logins.Any(login => login.LoginProvider == loginProvider && login.ProviderKey == providerKey)) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListByClaimAsync( - Claim claim, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .Where(u => u.Claims.Any(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value)) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task FindByNormalizedEmailAsync( + string normalizedEmail, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync(u => u.NormalizedEmail == normalizedEmail, GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListByNormalizedRoleNameAsync( - string normalizedRoleName, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var dbContext = await GetDbContextAsync(); - - var role = await dbContext.Roles - .Where(x => x.NormalizedName == normalizedRoleName) - .OrderBy(x => x.Id) - .FirstOrDefaultAsync(GetCancellationToken(cancellationToken)); - - if (role == null) - { - return new List(); - } - - return await dbContext.Users - .IncludeDetails(includeDetails) - .Where(u => u.Roles.Any(r => r.RoleId == role.Id)) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetListByClaimAsync( + Claim claim, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .Where(u => u.Claims.Any(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value)) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListAsync( - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - Guid? roleId = null, - Guid? organizationUnitId = null, - string userName = null, - string phoneNumber = null, - string emailAddress = null, - bool? isLockedOut = null, - bool? notActive = null, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .WhereIf( - !filter.IsNullOrWhiteSpace(), - u => - u.UserName.Contains(filter) || - u.Email.Contains(filter) || - (u.Name != null && u.Name.Contains(filter)) || - (u.Surname != null && u.Surname.Contains(filter)) || - (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) - ) - .WhereIf(roleId.HasValue, identityUser => identityUser.Roles.Any(x => x.RoleId == roleId.Value)) - .WhereIf(organizationUnitId.HasValue, identityUser => identityUser.OrganizationUnits.Any(x => x.OrganizationUnitId == organizationUnitId.Value)) - .WhereIf(!string.IsNullOrWhiteSpace(userName), x => x.UserName == userName) - .WhereIf(!string.IsNullOrWhiteSpace(phoneNumber), x => x.PhoneNumber == phoneNumber) - .WhereIf(!string.IsNullOrWhiteSpace(emailAddress), x => x.Email == emailAddress) - .WhereIf(isLockedOut == true, x => x.LockoutEnabled && x.LockoutEnd > DateTimeOffset.UtcNow) - .WhereIf(notActive == true, x => !x.IsActive) - .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityUser.UserName) : sorting) - .PageBy(skipCount, maxResultCount) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetListByNormalizedRoleNameAsync( + string normalizedRoleName, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var dbContext = await GetDbContextAsync(); - public virtual async Task> GetRolesAsync( - Guid id, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var dbContext = await GetDbContextAsync(); - - var query = from userRole in dbContext.Set() - join role in dbContext.Roles.IncludeDetails(includeDetails) on userRole.RoleId equals role.Id - where userRole.UserId == id - select role; - - //TODO: Needs improvement - var userOrganizationsQuery = from userOrg in dbContext.Set() - join ou in dbContext.OrganizationUnits.IncludeDetails(includeDetails) on userOrg.OrganizationUnitId equals ou.Id - where userOrg.UserId == id - select ou; - - var orgUserRoleQuery = dbContext.Set() - .Where(q => userOrganizationsQuery - .Select(t => t.Id) - .Contains(q.OrganizationUnitId)) - .Select(t => t.RoleId) - .ToArray(); - - var orgRoles = dbContext.Roles.Where(q => orgUserRoleQuery.Contains(q.Id)); - var resultQuery = query.Union(orgRoles); - - return await resultQuery.ToListAsync(GetCancellationToken(cancellationToken)); - } + var role = await dbContext.Roles + .Where(x => x.NormalizedName == normalizedRoleName) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync(GetCancellationToken(cancellationToken)); - public virtual async Task GetCountAsync( - string filter = null, - Guid? roleId = null, - Guid? organizationUnitId = null, - string userName = null, - string phoneNumber = null, - string emailAddress = null, - bool? isLockedOut = null, - bool? notActive = null, - CancellationToken cancellationToken = default) + if (role == null) { - return await (await GetDbSetAsync()) - .WhereIf( - !filter.IsNullOrWhiteSpace(), - u => - u.UserName.Contains(filter) || - u.Email.Contains(filter) || - (u.Name != null && u.Name.Contains(filter)) || - (u.Surname != null && u.Surname.Contains(filter)) || - (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) - ) - .WhereIf(roleId.HasValue, identityUser => identityUser.Roles.Any(x => x.RoleId == roleId.Value)) - .WhereIf(organizationUnitId.HasValue, identityUser => identityUser.OrganizationUnits.Any(x => x.OrganizationUnitId == organizationUnitId.Value)) - .WhereIf(!string.IsNullOrWhiteSpace(userName), x => x.UserName == userName) - .WhereIf(!string.IsNullOrWhiteSpace(phoneNumber), x => x.PhoneNumber == phoneNumber) - .WhereIf(!string.IsNullOrWhiteSpace(emailAddress), x => x.Email == emailAddress) - .WhereIf(isLockedOut == true, x => x.LockoutEnabled && x.LockoutEnd > DateTimeOffset.UtcNow) - .WhereIf(notActive == true, x => !x.IsActive) - .LongCountAsync(GetCancellationToken(cancellationToken)); + return new List(); } - public virtual async Task> GetOrganizationUnitsAsync( - Guid id, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var dbContext = await GetDbContextAsync(); + return await dbContext.Users + .IncludeDetails(includeDetails) + .Where(u => u.Roles.Any(r => r.RoleId == role.Id)) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - var query = from userOu in dbContext.Set() - join ou in dbContext.OrganizationUnits.IncludeDetails(includeDetails) on userOu.OrganizationUnitId equals ou.Id - where userOu.UserId == id - select ou; + public virtual async Task> GetListAsync( + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + Guid? roleId = null, + Guid? organizationUnitId = null, + string userName = null, + string phoneNumber = null, + string emailAddress = null, + bool? isLockedOut = null, + bool? notActive = null, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .WhereIf( + !filter.IsNullOrWhiteSpace(), + u => + u.UserName.Contains(filter) || + u.Email.Contains(filter) || + (u.Name != null && u.Name.Contains(filter)) || + (u.Surname != null && u.Surname.Contains(filter)) || + (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) + ) + .WhereIf(roleId.HasValue, identityUser => identityUser.Roles.Any(x => x.RoleId == roleId.Value)) + .WhereIf(organizationUnitId.HasValue, identityUser => identityUser.OrganizationUnits.Any(x => x.OrganizationUnitId == organizationUnitId.Value)) + .WhereIf(!string.IsNullOrWhiteSpace(userName), x => x.UserName == userName) + .WhereIf(!string.IsNullOrWhiteSpace(phoneNumber), x => x.PhoneNumber == phoneNumber) + .WhereIf(!string.IsNullOrWhiteSpace(emailAddress), x => x.Email == emailAddress) + .WhereIf(isLockedOut == true, x => x.LockoutEnabled && x.LockoutEnd > DateTimeOffset.UtcNow) + .WhereIf(notActive == true, x => !x.IsActive) + .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityUser.UserName) : sorting) + .PageBy(skipCount, maxResultCount) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - return await query.ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetRolesAsync( + Guid id, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var dbContext = await GetDbContextAsync(); + + var query = from userRole in dbContext.Set() + join role in dbContext.Roles.IncludeDetails(includeDetails) on userRole.RoleId equals role.Id + where userRole.UserId == id + select role; + + //TODO: Needs improvement + var userOrganizationsQuery = from userOrg in dbContext.Set() + join ou in dbContext.OrganizationUnits.IncludeDetails(includeDetails) on userOrg.OrganizationUnitId equals ou.Id + where userOrg.UserId == id + select ou; + + var orgUserRoleQuery = dbContext.Set() + .Where(q => userOrganizationsQuery + .Select(t => t.Id) + .Contains(q.OrganizationUnitId)) + .Select(t => t.RoleId) + .ToArray(); + + var orgRoles = dbContext.Roles.Where(q => orgUserRoleQuery.Contains(q.Id)); + var resultQuery = query.Union(orgRoles); + + return await resultQuery.ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetUsersInOrganizationUnitAsync( - Guid organizationUnitId, - CancellationToken cancellationToken = default + public virtual async Task GetCountAsync( + string filter = null, + Guid? roleId = null, + Guid? organizationUnitId = null, + string userName = null, + string phoneNumber = null, + string emailAddress = null, + bool? isLockedOut = null, + bool? notActive = null, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .WhereIf( + !filter.IsNullOrWhiteSpace(), + u => + u.UserName.Contains(filter) || + u.Email.Contains(filter) || + (u.Name != null && u.Name.Contains(filter)) || + (u.Surname != null && u.Surname.Contains(filter)) || + (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) ) - { - var dbContext = await GetDbContextAsync(); + .WhereIf(roleId.HasValue, identityUser => identityUser.Roles.Any(x => x.RoleId == roleId.Value)) + .WhereIf(organizationUnitId.HasValue, identityUser => identityUser.OrganizationUnits.Any(x => x.OrganizationUnitId == organizationUnitId.Value)) + .WhereIf(!string.IsNullOrWhiteSpace(userName), x => x.UserName == userName) + .WhereIf(!string.IsNullOrWhiteSpace(phoneNumber), x => x.PhoneNumber == phoneNumber) + .WhereIf(!string.IsNullOrWhiteSpace(emailAddress), x => x.Email == emailAddress) + .WhereIf(isLockedOut == true, x => x.LockoutEnabled && x.LockoutEnd > DateTimeOffset.UtcNow) + .WhereIf(notActive == true, x => !x.IsActive) + .LongCountAsync(GetCancellationToken(cancellationToken)); + } - var query = from userOu in dbContext.Set() - join user in dbContext.Users on userOu.UserId equals user.Id - where userOu.OrganizationUnitId == organizationUnitId - select user; + public virtual async Task> GetOrganizationUnitsAsync( + Guid id, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var dbContext = await GetDbContextAsync(); - return await query.ToListAsync(GetCancellationToken(cancellationToken)); - } + var query = from userOu in dbContext.Set() + join ou in dbContext.OrganizationUnits.IncludeDetails(includeDetails) on userOu.OrganizationUnitId equals ou.Id + where userOu.UserId == id + select ou; - public virtual async Task> GetUsersInOrganizationsListAsync( - List organizationUnitIds, - CancellationToken cancellationToken = default - ) - { - var dbContext = await GetDbContextAsync(); + return await query.ToListAsync(GetCancellationToken(cancellationToken)); + } - var query = from userOu in dbContext.Set() - join user in dbContext.Users on userOu.UserId equals user.Id - where organizationUnitIds.Contains(userOu.OrganizationUnitId) - select user; + public virtual async Task> GetUsersInOrganizationUnitAsync( + Guid organizationUnitId, + CancellationToken cancellationToken = default + ) + { + var dbContext = await GetDbContextAsync(); - return await query.ToListAsync(GetCancellationToken(cancellationToken)); - } + var query = from userOu in dbContext.Set() + join user in dbContext.Users on userOu.UserId equals user.Id + where userOu.OrganizationUnitId == organizationUnitId + select user; - public virtual async Task> GetUsersInOrganizationUnitWithChildrenAsync( - string code, - CancellationToken cancellationToken = default - ) - { - var dbContext = await GetDbContextAsync(); + return await query.ToListAsync(GetCancellationToken(cancellationToken)); + } - var query = from userOu in dbContext.Set() - join user in dbContext.Users on userOu.UserId equals user.Id - join ou in dbContext.Set() on userOu.OrganizationUnitId equals ou.Id - where ou.Code.StartsWith(code) - select user; + public virtual async Task> GetUsersInOrganizationsListAsync( + List organizationUnitIds, + CancellationToken cancellationToken = default + ) + { + var dbContext = await GetDbContextAsync(); - return await query.ToListAsync(GetCancellationToken(cancellationToken)); - } + var query = from userOu in dbContext.Set() + join user in dbContext.Users on userOu.UserId equals user.Id + where organizationUnitIds.Contains(userOu.OrganizationUnitId) + select user; - [Obsolete("Use WithDetailsAsync method.")] - public override IQueryable WithDetails() - { - return GetQueryable().IncludeDetails(); - } + return await query.ToListAsync(GetCancellationToken(cancellationToken)); + } - public override async Task> WithDetailsAsync() - { - return (await GetQueryableAsync()).IncludeDetails(); - } + public virtual async Task> GetUsersInOrganizationUnitWithChildrenAsync( + string code, + CancellationToken cancellationToken = default + ) + { + var dbContext = await GetDbContextAsync(); + + var query = from userOu in dbContext.Set() + join user in dbContext.Users on userOu.UserId equals user.Id + join ou in dbContext.Set() on userOu.OrganizationUnitId equals ou.Id + where ou.Code.StartsWith(code) + select user; + + return await query.ToListAsync(GetCancellationToken(cancellationToken)); + } + + [Obsolete("Use WithDetailsAsync method.")] + public override IQueryable WithDetails() + { + return GetQueryable().IncludeDetails(); + } + + public override async Task> WithDetailsAsync() + { + return (await GetQueryableAsync()).IncludeDetails(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreOrganizationUnitRepository.cs b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreOrganizationUnitRepository.cs index 908da0a89b..eae1306975 100644 --- a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreOrganizationUnitRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/EfCoreOrganizationUnitRepository.cs @@ -9,282 +9,281 @@ using System.Threading.Tasks; using Volo.Abp.Domain.Repositories.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class EfCoreOrganizationUnitRepository + : EfCoreRepository, + IOrganizationUnitRepository { - public class EfCoreOrganizationUnitRepository - : EfCoreRepository, - IOrganizationUnitRepository + public EfCoreOrganizationUnitRepository( + IDbContextProvider dbContextProvider) + : base(dbContextProvider) { - public EfCoreOrganizationUnitRepository( - IDbContextProvider dbContextProvider) - : base(dbContextProvider) - { - } + } - public virtual async Task> GetChildrenAsync( - Guid? parentId, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .Where(x => x.ParentId == parentId) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetChildrenAsync( + Guid? parentId, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .Where(x => x.ParentId == parentId) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetAllChildrenWithParentCodeAsync( - string code, - Guid? parentId, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .Where(ou => ou.Code.StartsWith(code) && ou.Id != parentId.Value) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetAllChildrenWithParentCodeAsync( + string code, + Guid? parentId, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .Where(ou => ou.Code.StartsWith(code) && ou.Id != parentId.Value) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListAsync( - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .OrderBy(sorting.IsNullOrEmpty() ? nameof(OrganizationUnit.DisplayName) : sorting) - .PageBy(skipCount, maxResultCount) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetListAsync( + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .OrderBy(sorting.IsNullOrEmpty() ? nameof(OrganizationUnit.DisplayName) : sorting) + .PageBy(skipCount, maxResultCount) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListAsync( - IEnumerable ids, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .Where(t => ids.Contains(t.Id)) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetListAsync( + IEnumerable ids, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .Where(t => ids.Contains(t.Id)) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task GetAsync( - string displayName, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetDbSetAsync()) - .IncludeDetails(includeDetails) - .OrderBy(x => x.Id) - .FirstOrDefaultAsync( - ou => ou.DisplayName == displayName, - GetCancellationToken(cancellationToken) - ); - } + public virtual async Task GetAsync( + string displayName, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetDbSetAsync()) + .IncludeDetails(includeDetails) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync( + ou => ou.DisplayName == displayName, + GetCancellationToken(cancellationToken) + ); + } - public virtual async Task> GetRolesAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var dbContext = await GetDbContextAsync(); + public virtual async Task> GetRolesAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var dbContext = await GetDbContextAsync(); - var query = from organizationRole in dbContext.Set() - join role in dbContext.Roles.IncludeDetails(includeDetails) on organizationRole.RoleId equals role.Id - where organizationRole.OrganizationUnitId == organizationUnit.Id - select role; + var query = from organizationRole in dbContext.Set() + join role in dbContext.Roles.IncludeDetails(includeDetails) on organizationRole.RoleId equals role.Id + where organizationRole.OrganizationUnitId == organizationUnit.Id + select role; - query = query - .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityRole.Name) : sorting) - .PageBy(skipCount, maxResultCount); + query = query + .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityRole.Name) : sorting) + .PageBy(skipCount, maxResultCount); - return await query.ToListAsync(GetCancellationToken(cancellationToken)); - } + return await query.ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task GetRolesCountAsync( - OrganizationUnit organizationUnit, - CancellationToken cancellationToken = default) - { - var dbContext = await GetDbContextAsync(); + public virtual async Task GetRolesCountAsync( + OrganizationUnit organizationUnit, + CancellationToken cancellationToken = default) + { + var dbContext = await GetDbContextAsync(); - var query = from organizationRole in dbContext.Set() - join role in dbContext.Roles on organizationRole.RoleId equals role.Id - where organizationRole.OrganizationUnitId == organizationUnit.Id - select role; + var query = from organizationRole in dbContext.Set() + join role in dbContext.Roles on organizationRole.RoleId equals role.Id + where organizationRole.OrganizationUnitId == organizationUnit.Id + select role; - return await query.CountAsync(GetCancellationToken(cancellationToken)); - } + return await query.CountAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetUnaddedRolesAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToList(); - var dbContext = await GetDbContextAsync(); - - return await dbContext.Roles - .Where(r => !roleIds.Contains(r.Id)) - .IncludeDetails(includeDetails) - .WhereIf(!filter.IsNullOrWhiteSpace(), r => r.Name.Contains(filter)) - .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityRole.Name) : sorting) - .PageBy(skipCount, maxResultCount) - .ToListAsync(cancellationToken); - } + public virtual async Task> GetUnaddedRolesAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToList(); + var dbContext = await GetDbContextAsync(); + + return await dbContext.Roles + .Where(r => !roleIds.Contains(r.Id)) + .IncludeDetails(includeDetails) + .WhereIf(!filter.IsNullOrWhiteSpace(), r => r.Name.Contains(filter)) + .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityRole.Name) : sorting) + .PageBy(skipCount, maxResultCount) + .ToListAsync(cancellationToken); + } - public virtual async Task GetUnaddedRolesCountAsync( - OrganizationUnit organizationUnit, - string filter = null, - CancellationToken cancellationToken = default) - { - var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToList(); - var dbContext = await GetDbContextAsync(); + public virtual async Task GetUnaddedRolesCountAsync( + OrganizationUnit organizationUnit, + string filter = null, + CancellationToken cancellationToken = default) + { + var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToList(); + var dbContext = await GetDbContextAsync(); - return await dbContext.Roles - .Where(r => !roleIds.Contains(r.Id)) - .WhereIf(!filter.IsNullOrWhiteSpace(), r => r.Name.Contains(filter)) - .CountAsync(cancellationToken); - } + return await dbContext.Roles + .Where(r => !roleIds.Contains(r.Id)) + .WhereIf(!filter.IsNullOrWhiteSpace(), r => r.Name.Contains(filter)) + .CountAsync(cancellationToken); + } - public virtual async Task> GetMembersAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var query = await CreateGetMembersFilteredQueryAsync(organizationUnit, filter); + public virtual async Task> GetMembersAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var query = await CreateGetMembersFilteredQueryAsync(organizationUnit, filter); - return await query.IncludeDetails(includeDetails).OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityUser.UserName) : sorting) - .PageBy(skipCount, maxResultCount) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + return await query.IncludeDetails(includeDetails).OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityUser.UserName) : sorting) + .PageBy(skipCount, maxResultCount) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task GetMembersCountAsync( - OrganizationUnit organizationUnit, - string filter = null, - CancellationToken cancellationToken = default) - { - var query = await CreateGetMembersFilteredQueryAsync(organizationUnit, filter); + public virtual async Task GetMembersCountAsync( + OrganizationUnit organizationUnit, + string filter = null, + CancellationToken cancellationToken = default) + { + var query = await CreateGetMembersFilteredQueryAsync(organizationUnit, filter); - return await query.CountAsync(GetCancellationToken(cancellationToken)); - } + return await query.CountAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetUnaddedUsersAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var dbContext = await GetDbContextAsync(); - - var userIdsInOrganizationUnit = dbContext.Set() - .Where(uou => uou.OrganizationUnitId == organizationUnit.Id) - .Select(uou => uou.UserId); - - var query = dbContext.Users - .Where(u => !userIdsInOrganizationUnit.Contains(u.Id)); - - if (!filter.IsNullOrWhiteSpace()) - { - query = query.Where(u => - u.UserName.Contains(filter) || - u.Email.Contains(filter) || - (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) - ); - } - - return await query - .IncludeDetails(includeDetails) - .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityUser.Name) : sorting) - .PageBy(skipCount, maxResultCount) - .ToListAsync(cancellationToken); - } + public virtual async Task> GetUnaddedUsersAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var dbContext = await GetDbContextAsync(); - public virtual async Task GetUnaddedUsersCountAsync( - OrganizationUnit organizationUnit, - string filter = null, - CancellationToken cancellationToken = default) - { - var dbContext = await GetDbContextAsync(); - - var userIdsInOrganizationUnit = dbContext.Set() - .Where(uou => uou.OrganizationUnitId == organizationUnit.Id) - .Select(uou => uou.UserId); - - return await dbContext.Users - .Where(u => !userIdsInOrganizationUnit.Contains(u.Id)) - .WhereIf(!filter.IsNullOrWhiteSpace(), u => - u.UserName.Contains(filter) || - u.Email.Contains(filter) || - (u.PhoneNumber != null && u.PhoneNumber.Contains(filter))) - .CountAsync(cancellationToken); - } + var userIdsInOrganizationUnit = dbContext.Set() + .Where(uou => uou.OrganizationUnitId == organizationUnit.Id) + .Select(uou => uou.UserId); - [Obsolete("Use WithDetailsAsync method.")] - public override IQueryable WithDetails() - { - return GetQueryable().IncludeDetails(); - } + var query = dbContext.Users + .Where(u => !userIdsInOrganizationUnit.Contains(u.Id)); - public override async Task> WithDetailsAsync() + if (!filter.IsNullOrWhiteSpace()) { - return (await GetQueryableAsync()).IncludeDetails(); + query = query.Where(u => + u.UserName.Contains(filter) || + u.Email.Contains(filter) || + (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) + ); } - public virtual Task RemoveAllRolesAsync( - OrganizationUnit organizationUnit, - CancellationToken cancellationToken = default) - { - organizationUnit.Roles.Clear(); - return Task.CompletedTask; - } + return await query + .IncludeDetails(includeDetails) + .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityUser.Name) : sorting) + .PageBy(skipCount, maxResultCount) + .ToListAsync(cancellationToken); + } - public virtual async Task RemoveAllMembersAsync( - OrganizationUnit organizationUnit, - CancellationToken cancellationToken = default) - { - var dbContext = await GetDbContextAsync(); + public virtual async Task GetUnaddedUsersCountAsync( + OrganizationUnit organizationUnit, + string filter = null, + CancellationToken cancellationToken = default) + { + var dbContext = await GetDbContextAsync(); + + var userIdsInOrganizationUnit = dbContext.Set() + .Where(uou => uou.OrganizationUnitId == organizationUnit.Id) + .Select(uou => uou.UserId); + + return await dbContext.Users + .Where(u => !userIdsInOrganizationUnit.Contains(u.Id)) + .WhereIf(!filter.IsNullOrWhiteSpace(), u => + u.UserName.Contains(filter) || + u.Email.Contains(filter) || + (u.PhoneNumber != null && u.PhoneNumber.Contains(filter))) + .CountAsync(cancellationToken); + } - var ouMembersQuery = await dbContext.Set() - .Where(q => q.OrganizationUnitId == organizationUnit.Id) - .ToListAsync(GetCancellationToken(cancellationToken)); + [Obsolete("Use WithDetailsAsync method.")] + public override IQueryable WithDetails() + { + return GetQueryable().IncludeDetails(); + } - dbContext.Set().RemoveRange(ouMembersQuery); - } + public override async Task> WithDetailsAsync() + { + return (await GetQueryableAsync()).IncludeDetails(); + } + + public virtual Task RemoveAllRolesAsync( + OrganizationUnit organizationUnit, + CancellationToken cancellationToken = default) + { + organizationUnit.Roles.Clear(); + return Task.CompletedTask; + } - protected virtual async Task> CreateGetMembersFilteredQueryAsync(OrganizationUnit organizationUnit, string filter = null) + public virtual async Task RemoveAllMembersAsync( + OrganizationUnit organizationUnit, + CancellationToken cancellationToken = default) + { + var dbContext = await GetDbContextAsync(); + + var ouMembersQuery = await dbContext.Set() + .Where(q => q.OrganizationUnitId == organizationUnit.Id) + .ToListAsync(GetCancellationToken(cancellationToken)); + + dbContext.Set().RemoveRange(ouMembersQuery); + } + + protected virtual async Task> CreateGetMembersFilteredQueryAsync(OrganizationUnit organizationUnit, string filter = null) + { + var dbContext = await GetDbContextAsync(); + + var query = from userOu in dbContext.Set() + join user in dbContext.Users on userOu.UserId equals user.Id + where userOu.OrganizationUnitId == organizationUnit.Id + select user; + + if (!filter.IsNullOrWhiteSpace()) { - var dbContext = await GetDbContextAsync(); - - var query = from userOu in dbContext.Set() - join user in dbContext.Users on userOu.UserId equals user.Id - where userOu.OrganizationUnitId == organizationUnit.Id - select user; - - if (!filter.IsNullOrWhiteSpace()) - { - query = query.Where(u => - u.UserName.Contains(filter) || - u.Email.Contains(filter) || - (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) - ); - } - - return query; + query = query.Where(u => + u.UserName.Contains(filter) || + u.Email.Contains(filter) || + (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) + ); } + + return query; } } diff --git a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IIdentityDbContext.cs b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IIdentityDbContext.cs index feae4ddd65..e84b2811c5 100644 --- a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IIdentityDbContext.cs +++ b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IIdentityDbContext.cs @@ -2,21 +2,20 @@ using Microsoft.EntityFrameworkCore; using Volo.Abp.Data; using Volo.Abp.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +[ConnectionStringName(AbpIdentityDbProperties.ConnectionStringName)] +public interface IIdentityDbContext : IEfCoreDbContext { - [ConnectionStringName(AbpIdentityDbProperties.ConnectionStringName)] - public interface IIdentityDbContext : IEfCoreDbContext - { - DbSet Users { get; } + DbSet Users { get; } - DbSet Roles { get; } + DbSet Roles { get; } - DbSet ClaimTypes { get; } + DbSet ClaimTypes { get; } - DbSet OrganizationUnits { get; } + DbSet OrganizationUnits { get; } - DbSet SecurityLogs { get; } + DbSet SecurityLogs { get; } - DbSet LinkUsers { get; } - } + DbSet LinkUsers { get; } } diff --git a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityDbContext.cs b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityDbContext.cs index dd9c2ffea5..bc2b4dd4b0 100644 --- a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityDbContext.cs +++ b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityDbContext.cs @@ -2,37 +2,36 @@ using Microsoft.EntityFrameworkCore; using Volo.Abp.Data; using Volo.Abp.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +/// +/// Base class for the Entity Framework database context used for identity. +/// +[ConnectionStringName(AbpIdentityDbProperties.ConnectionStringName)] +public class IdentityDbContext : AbpDbContext, IIdentityDbContext { - /// - /// Base class for the Entity Framework database context used for identity. - /// - [ConnectionStringName(AbpIdentityDbProperties.ConnectionStringName)] - public class IdentityDbContext : AbpDbContext, IIdentityDbContext - { - public DbSet Users { get; set; } + public DbSet Users { get; set; } - public DbSet Roles { get; set; } + public DbSet Roles { get; set; } - public DbSet ClaimTypes { get; set; } + public DbSet ClaimTypes { get; set; } - public DbSet OrganizationUnits { get; set; } + public DbSet OrganizationUnits { get; set; } - public DbSet SecurityLogs { get; set; } + public DbSet SecurityLogs { get; set; } - public DbSet LinkUsers { get; set; } + public DbSet LinkUsers { get; set; } - public IdentityDbContext(DbContextOptions options) - : base(options) - { + public IdentityDbContext(DbContextOptions options) + : base(options) + { - } + } - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); - builder.ConfigureIdentity(); - } + builder.ConfigureIdentity(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityDbContextModelBuilderExtensions.cs b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityDbContextModelBuilderExtensions.cs index 0aab3525da..472581fdbd 100644 --- a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityDbContextModelBuilderExtensions.cs +++ b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityDbContextModelBuilderExtensions.cs @@ -4,274 +4,272 @@ using Microsoft.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore.Modeling; using Volo.Abp.Users.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public static class IdentityDbContextModelBuilderExtensions { - public static class IdentityDbContextModelBuilderExtensions + public static void ConfigureIdentity([NotNull] this ModelBuilder builder) { - public static void ConfigureIdentity([NotNull] this ModelBuilder builder) + Check.NotNull(builder, nameof(builder)); + + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "Users", AbpIdentityDbProperties.DbSchema); + + b.ConfigureByConvention(); + b.ConfigureAbpUser(); + + b.Property(u => u.NormalizedUserName).IsRequired() + .HasMaxLength(IdentityUserConsts.MaxNormalizedUserNameLength) + .HasColumnName(nameof(IdentityUser.NormalizedUserName)); + b.Property(u => u.NormalizedEmail).IsRequired() + .HasMaxLength(IdentityUserConsts.MaxNormalizedEmailLength) + .HasColumnName(nameof(IdentityUser.NormalizedEmail)); + b.Property(u => u.PasswordHash).HasMaxLength(IdentityUserConsts.MaxPasswordHashLength) + .HasColumnName(nameof(IdentityUser.PasswordHash)); + b.Property(u => u.SecurityStamp).IsRequired().HasMaxLength(IdentityUserConsts.MaxSecurityStampLength) + .HasColumnName(nameof(IdentityUser.SecurityStamp)); + b.Property(u => u.TwoFactorEnabled).HasDefaultValue(false) + .HasColumnName(nameof(IdentityUser.TwoFactorEnabled)); + b.Property(u => u.LockoutEnabled).HasDefaultValue(false) + .HasColumnName(nameof(IdentityUser.LockoutEnabled)); + + b.Property(u => u.IsExternal).IsRequired().HasDefaultValue(false) + .HasColumnName(nameof(IdentityUser.IsExternal)); + + b.Property(u => u.AccessFailedCount) + .If(!builder.IsUsingOracle(), p => p.HasDefaultValue(0)) + .HasColumnName(nameof(IdentityUser.AccessFailedCount)); + + b.HasMany(u => u.Claims).WithOne().HasForeignKey(uc => uc.UserId).IsRequired(); + b.HasMany(u => u.Logins).WithOne().HasForeignKey(ul => ul.UserId).IsRequired(); + b.HasMany(u => u.Roles).WithOne().HasForeignKey(ur => ur.UserId).IsRequired(); + b.HasMany(u => u.Tokens).WithOne().HasForeignKey(ur => ur.UserId).IsRequired(); + b.HasMany(u => u.OrganizationUnits).WithOne().HasForeignKey(ur => ur.UserId).IsRequired(); + + b.HasIndex(u => u.NormalizedUserName); + b.HasIndex(u => u.NormalizedEmail); + b.HasIndex(u => u.UserName); + b.HasIndex(u => u.Email); + + b.ApplyObjectExtensionMappings(); + }); + + builder.Entity(b => { - Check.NotNull(builder, nameof(builder)); + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "UserClaims", AbpIdentityDbProperties.DbSchema); - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "Users", AbpIdentityDbProperties.DbSchema); + b.ConfigureByConvention(); - b.ConfigureByConvention(); - b.ConfigureAbpUser(); - - b.Property(u => u.NormalizedUserName).IsRequired() - .HasMaxLength(IdentityUserConsts.MaxNormalizedUserNameLength) - .HasColumnName(nameof(IdentityUser.NormalizedUserName)); - b.Property(u => u.NormalizedEmail).IsRequired() - .HasMaxLength(IdentityUserConsts.MaxNormalizedEmailLength) - .HasColumnName(nameof(IdentityUser.NormalizedEmail)); - b.Property(u => u.PasswordHash).HasMaxLength(IdentityUserConsts.MaxPasswordHashLength) - .HasColumnName(nameof(IdentityUser.PasswordHash)); - b.Property(u => u.SecurityStamp).IsRequired().HasMaxLength(IdentityUserConsts.MaxSecurityStampLength) - .HasColumnName(nameof(IdentityUser.SecurityStamp)); - b.Property(u => u.TwoFactorEnabled).HasDefaultValue(false) - .HasColumnName(nameof(IdentityUser.TwoFactorEnabled)); - b.Property(u => u.LockoutEnabled).HasDefaultValue(false) - .HasColumnName(nameof(IdentityUser.LockoutEnabled)); - - b.Property(u => u.IsExternal).IsRequired().HasDefaultValue(false) - .HasColumnName(nameof(IdentityUser.IsExternal)); - - b.Property(u => u.AccessFailedCount) - .If(!builder.IsUsingOracle(), p => p.HasDefaultValue(0)) - .HasColumnName(nameof(IdentityUser.AccessFailedCount)); - - b.HasMany(u => u.Claims).WithOne().HasForeignKey(uc => uc.UserId).IsRequired(); - b.HasMany(u => u.Logins).WithOne().HasForeignKey(ul => ul.UserId).IsRequired(); - b.HasMany(u => u.Roles).WithOne().HasForeignKey(ur => ur.UserId).IsRequired(); - b.HasMany(u => u.Tokens).WithOne().HasForeignKey(ur => ur.UserId).IsRequired(); - b.HasMany(u => u.OrganizationUnits).WithOne().HasForeignKey(ur => ur.UserId).IsRequired(); - - b.HasIndex(u => u.NormalizedUserName); - b.HasIndex(u => u.NormalizedEmail); - b.HasIndex(u => u.UserName); - b.HasIndex(u => u.Email); + b.Property(x => x.Id).ValueGeneratedNever(); - b.ApplyObjectExtensionMappings(); - }); + b.Property(uc => uc.ClaimType).HasMaxLength(IdentityUserClaimConsts.MaxClaimTypeLength).IsRequired(); + b.Property(uc => uc.ClaimValue).HasMaxLength(IdentityUserClaimConsts.MaxClaimValueLength); - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "UserClaims", AbpIdentityDbProperties.DbSchema); + b.HasIndex(uc => uc.UserId); - b.ConfigureByConvention(); + b.ApplyObjectExtensionMappings(); + }); - b.Property(x => x.Id).ValueGeneratedNever(); + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "UserRoles", AbpIdentityDbProperties.DbSchema); - b.Property(uc => uc.ClaimType).HasMaxLength(IdentityUserClaimConsts.MaxClaimTypeLength).IsRequired(); - b.Property(uc => uc.ClaimValue).HasMaxLength(IdentityUserClaimConsts.MaxClaimValueLength); + b.ConfigureByConvention(); - b.HasIndex(uc => uc.UserId); + b.HasKey(ur => new { ur.UserId, ur.RoleId }); - b.ApplyObjectExtensionMappings(); - }); + b.HasOne().WithMany().HasForeignKey(ur => ur.RoleId).IsRequired(); + b.HasOne().WithMany(u => u.Roles).HasForeignKey(ur => ur.UserId).IsRequired(); - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "UserRoles", AbpIdentityDbProperties.DbSchema); + b.HasIndex(ur => new { ur.RoleId, ur.UserId }); - b.ConfigureByConvention(); + b.ApplyObjectExtensionMappings(); + }); - b.HasKey(ur => new {ur.UserId, ur.RoleId}); + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "UserLogins", AbpIdentityDbProperties.DbSchema); - b.HasOne().WithMany().HasForeignKey(ur => ur.RoleId).IsRequired(); - b.HasOne().WithMany(u => u.Roles).HasForeignKey(ur => ur.UserId).IsRequired(); + b.ConfigureByConvention(); - b.HasIndex(ur => new {ur.RoleId, ur.UserId}); + b.HasKey(x => new { x.UserId, x.LoginProvider }); - b.ApplyObjectExtensionMappings(); - }); + b.Property(ul => ul.LoginProvider).HasMaxLength(IdentityUserLoginConsts.MaxLoginProviderLength) + .IsRequired(); + b.Property(ul => ul.ProviderKey).HasMaxLength(IdentityUserLoginConsts.MaxProviderKeyLength) + .IsRequired(); + b.Property(ul => ul.ProviderDisplayName) + .HasMaxLength(IdentityUserLoginConsts.MaxProviderDisplayNameLength); - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "UserLogins", AbpIdentityDbProperties.DbSchema); + b.HasIndex(l => new { l.LoginProvider, l.ProviderKey }); - b.ConfigureByConvention(); + b.ApplyObjectExtensionMappings(); + }); - b.HasKey(x => new {x.UserId, x.LoginProvider}); + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "UserTokens", AbpIdentityDbProperties.DbSchema); - b.Property(ul => ul.LoginProvider).HasMaxLength(IdentityUserLoginConsts.MaxLoginProviderLength) - .IsRequired(); - b.Property(ul => ul.ProviderKey).HasMaxLength(IdentityUserLoginConsts.MaxProviderKeyLength) - .IsRequired(); - b.Property(ul => ul.ProviderDisplayName) - .HasMaxLength(IdentityUserLoginConsts.MaxProviderDisplayNameLength); + b.ConfigureByConvention(); - b.HasIndex(l => new {l.LoginProvider, l.ProviderKey}); + b.HasKey(l => new { l.UserId, l.LoginProvider, l.Name }); - b.ApplyObjectExtensionMappings(); - }); + b.Property(ul => ul.LoginProvider).HasMaxLength(IdentityUserTokenConsts.MaxLoginProviderLength) + .IsRequired(); + b.Property(ul => ul.Name).HasMaxLength(IdentityUserTokenConsts.MaxNameLength).IsRequired(); - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "UserTokens", AbpIdentityDbProperties.DbSchema); + b.ApplyObjectExtensionMappings(); + }); - b.ConfigureByConvention(); + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "Roles", AbpIdentityDbProperties.DbSchema); - b.HasKey(l => new {l.UserId, l.LoginProvider, l.Name}); + b.ConfigureByConvention(); - b.Property(ul => ul.LoginProvider).HasMaxLength(IdentityUserTokenConsts.MaxLoginProviderLength) - .IsRequired(); - b.Property(ul => ul.Name).HasMaxLength(IdentityUserTokenConsts.MaxNameLength).IsRequired(); + b.Property(r => r.Name).IsRequired().HasMaxLength(IdentityRoleConsts.MaxNameLength); + b.Property(r => r.NormalizedName).IsRequired().HasMaxLength(IdentityRoleConsts.MaxNormalizedNameLength); + b.Property(r => r.IsDefault).HasColumnName(nameof(IdentityRole.IsDefault)); + b.Property(r => r.IsStatic).HasColumnName(nameof(IdentityRole.IsStatic)); + b.Property(r => r.IsPublic).HasColumnName(nameof(IdentityRole.IsPublic)); - b.ApplyObjectExtensionMappings(); - }); + b.HasMany(r => r.Claims).WithOne().HasForeignKey(rc => rc.RoleId).IsRequired(); - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "Roles", AbpIdentityDbProperties.DbSchema); + b.HasIndex(r => r.NormalizedName); - b.ConfigureByConvention(); + b.ApplyObjectExtensionMappings(); + }); - b.Property(r => r.Name).IsRequired().HasMaxLength(IdentityRoleConsts.MaxNameLength); - b.Property(r => r.NormalizedName).IsRequired().HasMaxLength(IdentityRoleConsts.MaxNormalizedNameLength); - b.Property(r => r.IsDefault).HasColumnName(nameof(IdentityRole.IsDefault)); - b.Property(r => r.IsStatic).HasColumnName(nameof(IdentityRole.IsStatic)); - b.Property(r => r.IsPublic).HasColumnName(nameof(IdentityRole.IsPublic)); + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "RoleClaims", AbpIdentityDbProperties.DbSchema); - b.HasMany(r => r.Claims).WithOne().HasForeignKey(rc => rc.RoleId).IsRequired(); + b.ConfigureByConvention(); - b.HasIndex(r => r.NormalizedName); + b.Property(x => x.Id).ValueGeneratedNever(); - b.ApplyObjectExtensionMappings(); - }); + b.Property(uc => uc.ClaimType).HasMaxLength(IdentityRoleClaimConsts.MaxClaimTypeLength).IsRequired(); + b.Property(uc => uc.ClaimValue).HasMaxLength(IdentityRoleClaimConsts.MaxClaimValueLength); - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "RoleClaims", AbpIdentityDbProperties.DbSchema); + b.HasIndex(uc => uc.RoleId); - b.ConfigureByConvention(); + b.ApplyObjectExtensionMappings(); + }); - b.Property(x => x.Id).ValueGeneratedNever(); + if (builder.IsHostDatabase()) + { + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "ClaimTypes", AbpIdentityDbProperties.DbSchema); - b.Property(uc => uc.ClaimType).HasMaxLength(IdentityRoleClaimConsts.MaxClaimTypeLength).IsRequired(); - b.Property(uc => uc.ClaimValue).HasMaxLength(IdentityRoleClaimConsts.MaxClaimValueLength); + b.ConfigureByConvention(); - b.HasIndex(uc => uc.RoleId); + b.Property(uc => uc.Name).HasMaxLength(IdentityClaimTypeConsts.MaxNameLength) + .IsRequired(); // make unique + b.Property(uc => uc.Regex).HasMaxLength(IdentityClaimTypeConsts.MaxRegexLength); + b.Property(uc => uc.RegexDescription).HasMaxLength(IdentityClaimTypeConsts.MaxRegexDescriptionLength); + b.Property(uc => uc.Description).HasMaxLength(IdentityClaimTypeConsts.MaxDescriptionLength); b.ApplyObjectExtensionMappings(); }); + } - if (builder.IsHostDatabase()) - { - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "ClaimTypes", AbpIdentityDbProperties.DbSchema); + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "OrganizationUnits", AbpIdentityDbProperties.DbSchema); - b.ConfigureByConvention(); + b.ConfigureByConvention(); - b.Property(uc => uc.Name).HasMaxLength(IdentityClaimTypeConsts.MaxNameLength) - .IsRequired(); // make unique - b.Property(uc => uc.Regex).HasMaxLength(IdentityClaimTypeConsts.MaxRegexLength); - b.Property(uc => uc.RegexDescription).HasMaxLength(IdentityClaimTypeConsts.MaxRegexDescriptionLength); - b.Property(uc => uc.Description).HasMaxLength(IdentityClaimTypeConsts.MaxDescriptionLength); + b.Property(ou => ou.Code).IsRequired().HasMaxLength(OrganizationUnitConsts.MaxCodeLength) + .HasColumnName(nameof(OrganizationUnit.Code)); + b.Property(ou => ou.DisplayName).IsRequired().HasMaxLength(OrganizationUnitConsts.MaxDisplayNameLength) + .HasColumnName(nameof(OrganizationUnit.DisplayName)); - b.ApplyObjectExtensionMappings(); - }); - } + b.HasMany().WithOne().HasForeignKey(ou => ou.ParentId); + b.HasMany(ou => ou.Roles).WithOne().HasForeignKey(our => our.OrganizationUnitId).IsRequired(); - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "OrganizationUnits", AbpIdentityDbProperties.DbSchema); + b.HasIndex(ou => ou.Code); - b.ConfigureByConvention(); + b.ApplyObjectExtensionMappings(); + }); - b.Property(ou => ou.Code).IsRequired().HasMaxLength(OrganizationUnitConsts.MaxCodeLength) - .HasColumnName(nameof(OrganizationUnit.Code)); - b.Property(ou => ou.DisplayName).IsRequired().HasMaxLength(OrganizationUnitConsts.MaxDisplayNameLength) - .HasColumnName(nameof(OrganizationUnit.DisplayName)); + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "OrganizationUnitRoles", AbpIdentityDbProperties.DbSchema); - b.HasMany().WithOne().HasForeignKey(ou => ou.ParentId); - b.HasMany(ou => ou.Roles).WithOne().HasForeignKey(our => our.OrganizationUnitId).IsRequired(); + b.ConfigureByConvention(); - b.HasIndex(ou => ou.Code); + b.HasKey(ou => new { ou.OrganizationUnitId, ou.RoleId }); - b.ApplyObjectExtensionMappings(); - }); + b.HasOne().WithMany().HasForeignKey(ou => ou.RoleId).IsRequired(); - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "OrganizationUnitRoles", AbpIdentityDbProperties.DbSchema); + b.HasIndex(ou => new { ou.RoleId, ou.OrganizationUnitId }); - b.ConfigureByConvention(); + b.ApplyObjectExtensionMappings(); + }); - b.HasKey(ou => new {ou.OrganizationUnitId, ou.RoleId}); + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "UserOrganizationUnits", AbpIdentityDbProperties.DbSchema); - b.HasOne().WithMany().HasForeignKey(ou => ou.RoleId).IsRequired(); + b.ConfigureByConvention(); - b.HasIndex(ou => new {ou.RoleId, ou.OrganizationUnitId}); + b.HasKey(ou => new { ou.OrganizationUnitId, ou.UserId }); - b.ApplyObjectExtensionMappings(); - }); + b.HasOne().WithMany().HasForeignKey(ou => ou.OrganizationUnitId).IsRequired(); - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "UserOrganizationUnits", AbpIdentityDbProperties.DbSchema); + b.HasIndex(ou => new { ou.UserId, ou.OrganizationUnitId }); - b.ConfigureByConvention(); + b.ApplyObjectExtensionMappings(); + }); - b.HasKey(ou => new {ou.OrganizationUnitId, ou.UserId}); + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "SecurityLogs", AbpIdentityDbProperties.DbSchema); - b.HasOne().WithMany().HasForeignKey(ou => ou.OrganizationUnitId).IsRequired(); + b.ConfigureByConvention(); - b.HasIndex(ou => new {ou.UserId, ou.OrganizationUnitId}); + b.Property(x => x.TenantName).HasMaxLength(IdentitySecurityLogConsts.MaxTenantNameLength); - b.ApplyObjectExtensionMappings(); - }); + b.Property(x => x.ApplicationName).HasMaxLength(IdentitySecurityLogConsts.MaxApplicationNameLength); + b.Property(x => x.Identity).HasMaxLength(IdentitySecurityLogConsts.MaxIdentityLength); + b.Property(x => x.Action).HasMaxLength(IdentitySecurityLogConsts.MaxActionLength); - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "SecurityLogs", AbpIdentityDbProperties.DbSchema); + b.Property(x => x.UserName).HasMaxLength(IdentitySecurityLogConsts.MaxUserNameLength); - b.ConfigureByConvention(); + b.Property(x => x.ClientIpAddress).HasMaxLength(IdentitySecurityLogConsts.MaxClientIpAddressLength); + b.Property(x => x.ClientId).HasMaxLength(IdentitySecurityLogConsts.MaxClientIdLength); + b.Property(x => x.CorrelationId).HasMaxLength(IdentitySecurityLogConsts.MaxCorrelationIdLength); + b.Property(x => x.BrowserInfo).HasMaxLength(IdentitySecurityLogConsts.MaxBrowserInfoLength); - b.Property(x => x.TenantName).HasMaxLength(IdentitySecurityLogConsts.MaxTenantNameLength); + b.HasIndex(x => new { x.TenantId, x.ApplicationName }); + b.HasIndex(x => new { x.TenantId, x.Identity }); + b.HasIndex(x => new { x.TenantId, x.Action }); + b.HasIndex(x => new { x.TenantId, x.UserId }); - b.Property(x => x.ApplicationName).HasMaxLength(IdentitySecurityLogConsts.MaxApplicationNameLength); - b.Property(x => x.Identity).HasMaxLength(IdentitySecurityLogConsts.MaxIdentityLength); - b.Property(x => x.Action).HasMaxLength(IdentitySecurityLogConsts.MaxActionLength); + b.ApplyObjectExtensionMappings(); + }); - b.Property(x => x.UserName).HasMaxLength(IdentitySecurityLogConsts.MaxUserNameLength); + if (builder.IsHostDatabase()) + { + builder.Entity(b => + { + b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "LinkUsers", AbpIdentityDbProperties.DbSchema); - b.Property(x => x.ClientIpAddress).HasMaxLength(IdentitySecurityLogConsts.MaxClientIpAddressLength); - b.Property(x => x.ClientId).HasMaxLength(IdentitySecurityLogConsts.MaxClientIdLength); - b.Property(x => x.CorrelationId).HasMaxLength(IdentitySecurityLogConsts.MaxCorrelationIdLength); - b.Property(x => x.BrowserInfo).HasMaxLength(IdentitySecurityLogConsts.MaxBrowserInfoLength); + b.ConfigureByConvention(); - b.HasIndex(x => new { x.TenantId, x.ApplicationName }); - b.HasIndex(x => new { x.TenantId, x.Identity }); - b.HasIndex(x => new { x.TenantId, x.Action }); - b.HasIndex(x => new { x.TenantId, x.UserId }); + b.HasIndex(x => new { + UserId = x.SourceUserId, + TenantId = x.SourceTenantId, + LinkedUserId = x.TargetUserId, + LinkedTenantId = x.TargetTenantId + }).IsUnique(); b.ApplyObjectExtensionMappings(); }); - - if (builder.IsHostDatabase()) - { - builder.Entity(b => - { - b.ToTable(AbpIdentityDbProperties.DbTablePrefix + "LinkUsers", AbpIdentityDbProperties.DbSchema); - - b.ConfigureByConvention(); - - b.HasIndex(x => new - { - UserId = x.SourceUserId, - TenantId = x.SourceTenantId, - LinkedUserId = x.TargetUserId, - LinkedTenantId = x.TargetTenantId - }).IsUnique(); - - b.ApplyObjectExtensionMappings(); - }); - } - - builder.TryConfigureObjectExtensions(); } + + builder.TryConfigureObjectExtensions(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityEfCoreQueryableExtensions.cs b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityEfCoreQueryableExtensions.cs index 4eddc83ea3..2f04fbbe62 100644 --- a/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityEfCoreQueryableExtensions.cs +++ b/modules/identity/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/IdentityEfCoreQueryableExtensions.cs @@ -1,45 +1,44 @@ using System.Linq; using Microsoft.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public static class IdentityEfCoreQueryableExtensions { - public static class IdentityEfCoreQueryableExtensions + public static IQueryable IncludeDetails(this IQueryable queryable, bool include = true) { - public static IQueryable IncludeDetails(this IQueryable queryable, bool include = true) + if (!include) { - if (!include) - { - return queryable; - } - - return queryable - .Include(x => x.Roles) - .Include(x => x.Logins) - .Include(x => x.Claims) - .Include(x => x.Tokens) - .Include(x => x.OrganizationUnits); + return queryable; } - public static IQueryable IncludeDetails(this IQueryable queryable, bool include = true) - { - if (!include) - { - return queryable; - } + return queryable + .Include(x => x.Roles) + .Include(x => x.Logins) + .Include(x => x.Claims) + .Include(x => x.Tokens) + .Include(x => x.OrganizationUnits); + } - return queryable - .Include(x => x.Claims); + public static IQueryable IncludeDetails(this IQueryable queryable, bool include = true) + { + if (!include) + { + return queryable; } - public static IQueryable IncludeDetails(this IQueryable queryable, bool include = true) - { - if (!include) - { - return queryable; - } + return queryable + .Include(x => x.Claims); + } - return queryable - .Include(x => x.Roles); + public static IQueryable IncludeDetails(this IQueryable queryable, bool include = true) + { + if (!include) + { + return queryable; } + + return queryable + .Include(x => x.Roles); } } diff --git a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityRoleClientProxy.cs b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityRoleClientProxy.cs index 3b80698304..a7a5bf4a24 100644 --- a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityRoleClientProxy.cs +++ b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityRoleClientProxy.cs @@ -1,8 +1,7 @@ // This file is part of IdentityRoleClientProxy, you can customize it here // ReSharper disable once CheckNamespace -namespace Volo.Abp.Identity.ClientProxies +namespace Volo.Abp.Identity.ClientProxies; + +public partial class IdentityRoleClientProxy { - public partial class IdentityRoleClientProxy - { - } } diff --git a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityUserClientProxy.cs b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityUserClientProxy.cs index 494713ec5a..99954e2eb5 100644 --- a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityUserClientProxy.cs +++ b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityUserClientProxy.cs @@ -1,8 +1,7 @@ // This file is part of IdentityUserClientProxy, you can customize it here // ReSharper disable once CheckNamespace -namespace Volo.Abp.Identity.ClientProxies +namespace Volo.Abp.Identity.ClientProxies; + +public partial class IdentityUserClientProxy { - public partial class IdentityUserClientProxy - { - } } diff --git a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityUserLookupClientProxy.cs b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityUserLookupClientProxy.cs index ca96fcfe7b..e9d1ad8a82 100644 --- a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityUserLookupClientProxy.cs +++ b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/ClientProxies/IdentityUserLookupClientProxy.cs @@ -1,8 +1,7 @@ // This file is part of IdentityUserLookupClientProxy, you can customize it here // ReSharper disable once CheckNamespace -namespace Volo.Abp.Identity.ClientProxies +namespace Volo.Abp.Identity.ClientProxies; + +public partial class IdentityUserLookupClientProxy { - public partial class IdentityUserLookupClientProxy - { - } } diff --git a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/AbpIdentityHttpApiClientModule.cs b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/AbpIdentityHttpApiClientModule.cs index 695729de58..518706a613 100644 --- a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/AbpIdentityHttpApiClientModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/AbpIdentityHttpApiClientModule.cs @@ -3,24 +3,23 @@ using Volo.Abp.Http.Client; using Volo.Abp.Modularity; using Volo.Abp.VirtualFileSystem; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[DependsOn( + typeof(AbpIdentityApplicationContractsModule), + typeof(AbpHttpClientModule))] +public class AbpIdentityHttpApiClientModule : AbpModule { - [DependsOn( - typeof(AbpIdentityApplicationContractsModule), - typeof(AbpHttpClientModule))] - public class AbpIdentityHttpApiClientModule : AbpModule + public override void ConfigureServices(ServiceConfigurationContext context) { - public override void ConfigureServices(ServiceConfigurationContext context) - { - context.Services.AddStaticHttpClientProxies( - typeof(AbpIdentityApplicationContractsModule).Assembly, - IdentityRemoteServiceConsts.RemoteServiceName - ); + context.Services.AddStaticHttpClientProxies( + typeof(AbpIdentityApplicationContractsModule).Assembly, + IdentityRemoteServiceConsts.RemoteServiceName + ); - Configure(options => - { - options.FileSets.AddEmbedded(); - }); - } + Configure(options => + { + options.FileSets.AddEmbedded(); + }); } } diff --git a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/HttpClientExternalUserLookupServiceProvider.cs b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/HttpClientExternalUserLookupServiceProvider.cs index 28859c6c1f..1c824db402 100644 --- a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/HttpClientExternalUserLookupServiceProvider.cs +++ b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/HttpClientExternalUserLookupServiceProvider.cs @@ -6,59 +6,58 @@ using System.Threading.Tasks; using Volo.Abp.DependencyInjection; using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[Dependency(TryRegister = true)] +public class HttpClientExternalUserLookupServiceProvider : IExternalUserLookupServiceProvider, ITransientDependency { - [Dependency(TryRegister = true)] - public class HttpClientExternalUserLookupServiceProvider : IExternalUserLookupServiceProvider, ITransientDependency + protected IIdentityUserLookupAppService UserLookupAppService { get; } + + public HttpClientExternalUserLookupServiceProvider(IIdentityUserLookupAppService userLookupAppService) { - protected IIdentityUserLookupAppService UserLookupAppService { get; } + UserLookupAppService = userLookupAppService; + } - public HttpClientExternalUserLookupServiceProvider(IIdentityUserLookupAppService userLookupAppService) - { - UserLookupAppService = userLookupAppService; - } + public virtual async Task FindByIdAsync(Guid id, CancellationToken cancellationToken = default) + { + return await UserLookupAppService.FindByIdAsync(id); + } - public virtual async Task FindByIdAsync(Guid id, CancellationToken cancellationToken = default) - { - return await UserLookupAppService.FindByIdAsync(id); - } + public virtual async Task FindByUserNameAsync(string userName, CancellationToken cancellationToken = default) + { + return await UserLookupAppService.FindByUserNameAsync(userName); + } - public virtual async Task FindByUserNameAsync(string userName, CancellationToken cancellationToken = default) - { - return await UserLookupAppService.FindByUserNameAsync(userName); - } + public async Task> SearchAsync( + string sorting = null, + string filter = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + CancellationToken cancellationToken = default) + { + var result = await UserLookupAppService.SearchAsync( + new UserLookupSearchInputDto + { + Filter = filter, + MaxResultCount = maxResultCount, + SkipCount = skipCount, + Sorting = sorting + } + ); + + return result.Items.Cast().ToList(); + } - public async Task> SearchAsync( - string sorting = null, - string filter = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - CancellationToken cancellationToken = default) - { - var result = await UserLookupAppService.SearchAsync( - new UserLookupSearchInputDto + public async Task GetCountAsync( + string filter = null, + CancellationToken cancellationToken = new CancellationToken()) + { + return await UserLookupAppService + .GetCountAsync( + new UserLookupCountInputDto { - Filter = filter, - MaxResultCount = maxResultCount, - SkipCount = skipCount, - Sorting = sorting + Filter = filter } ); - - return result.Items.Cast().ToList(); - } - - public async Task GetCountAsync( - string filter = null, - CancellationToken cancellationToken = new CancellationToken()) - { - return await UserLookupAppService - .GetCountAsync( - new UserLookupCountInputDto - { - Filter = filter - } - ); - } } } diff --git a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/HttpClientUserRoleFinder.cs b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/HttpClientUserRoleFinder.cs index 61e35f4d35..b747b416c2 100644 --- a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/HttpClientUserRoleFinder.cs +++ b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/HttpClientUserRoleFinder.cs @@ -3,22 +3,21 @@ using System.Linq; using System.Threading.Tasks; using Volo.Abp.DependencyInjection; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[Dependency(TryRegister = true)] +public class HttpClientUserRoleFinder : IUserRoleFinder, ITransientDependency { - [Dependency(TryRegister = true)] - public class HttpClientUserRoleFinder : IUserRoleFinder, ITransientDependency - { - protected IIdentityUserAppService _userAppService { get; } + protected IIdentityUserAppService _userAppService { get; } - public HttpClientUserRoleFinder(IIdentityUserAppService userAppService) - { - _userAppService = userAppService; - } + public HttpClientUserRoleFinder(IIdentityUserAppService userAppService) + { + _userAppService = userAppService; + } - public virtual async Task GetRolesAsync(Guid userId) - { - var output = await _userAppService.GetRolesAsync(userId); - return output.Items.Select(r => r.Name).ToArray(); - } + public virtual async Task GetRolesAsync(Guid userId) + { + var output = await _userAppService.GetRolesAsync(userId); + return output.Items.Select(r => r.Name).ToArray(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/IdentityUserDtoExtensions.cs b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/IdentityUserDtoExtensions.cs index bdb1e9044e..f5f0ec030d 100644 --- a/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/IdentityUserDtoExtensions.cs +++ b/modules/identity/src/Volo.Abp.Identity.HttpApi.Client/Volo/Abp/Identity/IdentityUserDtoExtensions.cs @@ -1,22 +1,21 @@ using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class IdentityUserDtoExtensions { - public static class IdentityUserDtoExtensions + public static IUserData ToUserInfo(this IdentityUserDto user) { - public static IUserData ToUserInfo(this IdentityUserDto user) - { - return new UserData( - user.Id, - user.UserName, - user.Email, - user.Name, - user.Surname, - user.EmailConfirmed, - user.PhoneNumber, - user.PhoneNumberConfirmed, - user.TenantId - ); - } + return new UserData( + user.Id, + user.UserName, + user.Email, + user.Name, + user.Surname, + user.EmailConfirmed, + user.PhoneNumber, + user.PhoneNumberConfirmed, + user.TenantId + ); } } diff --git a/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/AbpIdentityHttpApiModule.cs b/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/AbpIdentityHttpApiModule.cs index b2de93b41b..6f33275c81 100644 --- a/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/AbpIdentityHttpApiModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/AbpIdentityHttpApiModule.cs @@ -5,29 +5,28 @@ using Volo.Abp.Modularity; using Localization.Resources.AbpUi; using Microsoft.Extensions.DependencyInjection; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[DependsOn(typeof(AbpIdentityApplicationContractsModule), typeof(AbpAspNetCoreMvcModule))] +public class AbpIdentityHttpApiModule : AbpModule { - [DependsOn(typeof(AbpIdentityApplicationContractsModule), typeof(AbpAspNetCoreMvcModule))] - public class AbpIdentityHttpApiModule : AbpModule + public override void PreConfigureServices(ServiceConfigurationContext context) { - public override void PreConfigureServices(ServiceConfigurationContext context) + PreConfigure(mvcBuilder => { - PreConfigure(mvcBuilder => - { - mvcBuilder.AddApplicationPartIfNotExists(typeof(AbpIdentityHttpApiModule).Assembly); - }); - } + mvcBuilder.AddApplicationPartIfNotExists(typeof(AbpIdentityHttpApiModule).Assembly); + }); + } - public override void ConfigureServices(ServiceConfigurationContext context) + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => { - Configure(options => - { - options.Resources - .Get() - .AddBaseTypes( - typeof(AbpUiResource) - ); - }); - } + options.Resources + .Get() + .AddBaseTypes( + typeof(AbpUiResource) + ); + }); } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityRoleController.cs b/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityRoleController.cs index 6c680c86ad..41d2f341f0 100644 --- a/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityRoleController.cs +++ b/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityRoleController.cs @@ -4,59 +4,58 @@ using Microsoft.AspNetCore.Mvc; using Volo.Abp.Application.Dtos; using Volo.Abp.AspNetCore.Mvc; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[RemoteService(Name = IdentityRemoteServiceConsts.RemoteServiceName)] +[Area(IdentityRemoteServiceConsts.ModuleName)] +[ControllerName("Role")] +[Route("api/identity/roles")] +public class IdentityRoleController : AbpControllerBase, IIdentityRoleAppService { - [RemoteService(Name = IdentityRemoteServiceConsts.RemoteServiceName)] - [Area(IdentityRemoteServiceConsts.ModuleName)] - [ControllerName("Role")] - [Route("api/identity/roles")] - public class IdentityRoleController : AbpControllerBase, IIdentityRoleAppService + protected IIdentityRoleAppService RoleAppService { get; } + + public IdentityRoleController(IIdentityRoleAppService roleAppService) + { + RoleAppService = roleAppService; + } + + [HttpGet] + [Route("all")] + public virtual Task> GetAllListAsync() + { + return RoleAppService.GetAllListAsync(); + } + + [HttpGet] + public virtual Task> GetListAsync(GetIdentityRolesInput input) + { + return RoleAppService.GetListAsync(input); + } + + [HttpGet] + [Route("{id}")] + public virtual Task GetAsync(Guid id) + { + return RoleAppService.GetAsync(id); + } + + [HttpPost] + public virtual Task CreateAsync(IdentityRoleCreateDto input) + { + return RoleAppService.CreateAsync(input); + } + + [HttpPut] + [Route("{id}")] + public virtual Task UpdateAsync(Guid id, IdentityRoleUpdateDto input) + { + return RoleAppService.UpdateAsync(id, input); + } + + [HttpDelete] + [Route("{id}")] + public virtual Task DeleteAsync(Guid id) { - protected IIdentityRoleAppService RoleAppService { get; } - - public IdentityRoleController(IIdentityRoleAppService roleAppService) - { - RoleAppService = roleAppService; - } - - [HttpGet] - [Route("all")] - public virtual Task> GetAllListAsync() - { - return RoleAppService.GetAllListAsync(); - } - - [HttpGet] - public virtual Task> GetListAsync(GetIdentityRolesInput input) - { - return RoleAppService.GetListAsync(input); - } - - [HttpGet] - [Route("{id}")] - public virtual Task GetAsync(Guid id) - { - return RoleAppService.GetAsync(id); - } - - [HttpPost] - public virtual Task CreateAsync(IdentityRoleCreateDto input) - { - return RoleAppService.CreateAsync(input); - } - - [HttpPut] - [Route("{id}")] - public virtual Task UpdateAsync(Guid id, IdentityRoleUpdateDto input) - { - return RoleAppService.UpdateAsync(id, input); - } - - [HttpDelete] - [Route("{id}")] - public virtual Task DeleteAsync(Guid id) - { - return RoleAppService.DeleteAsync(id); - } + return RoleAppService.DeleteAsync(id); } } diff --git a/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityUserController.cs b/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityUserController.cs index 9dd071f934..4381636a7b 100644 --- a/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityUserController.cs +++ b/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityUserController.cs @@ -4,87 +4,86 @@ using Microsoft.AspNetCore.Mvc; using Volo.Abp.Application.Dtos; using Volo.Abp.AspNetCore.Mvc; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[RemoteService(Name = IdentityRemoteServiceConsts.RemoteServiceName)] +[Area(IdentityRemoteServiceConsts.ModuleName)] +[ControllerName("User")] +[Route("api/identity/users")] +public class IdentityUserController : AbpControllerBase, IIdentityUserAppService { - [RemoteService(Name = IdentityRemoteServiceConsts.RemoteServiceName)] - [Area(IdentityRemoteServiceConsts.ModuleName)] - [ControllerName("User")] - [Route("api/identity/users")] - public class IdentityUserController : AbpControllerBase, IIdentityUserAppService - { - protected IIdentityUserAppService UserAppService { get; } + protected IIdentityUserAppService UserAppService { get; } - public IdentityUserController(IIdentityUserAppService userAppService) - { - UserAppService = userAppService; - } + public IdentityUserController(IIdentityUserAppService userAppService) + { + UserAppService = userAppService; + } - [HttpGet] - [Route("{id}")] - public virtual Task GetAsync(Guid id) - { - return UserAppService.GetAsync(id); - } + [HttpGet] + [Route("{id}")] + public virtual Task GetAsync(Guid id) + { + return UserAppService.GetAsync(id); + } - [HttpGet] - public virtual Task> GetListAsync(GetIdentityUsersInput input) - { - return UserAppService.GetListAsync(input); - } + [HttpGet] + public virtual Task> GetListAsync(GetIdentityUsersInput input) + { + return UserAppService.GetListAsync(input); + } - [HttpPost] - public virtual Task CreateAsync(IdentityUserCreateDto input) - { - return UserAppService.CreateAsync(input); - } + [HttpPost] + public virtual Task CreateAsync(IdentityUserCreateDto input) + { + return UserAppService.CreateAsync(input); + } - [HttpPut] - [Route("{id}")] - public virtual Task UpdateAsync(Guid id, IdentityUserUpdateDto input) - { - return UserAppService.UpdateAsync(id, input); - } + [HttpPut] + [Route("{id}")] + public virtual Task UpdateAsync(Guid id, IdentityUserUpdateDto input) + { + return UserAppService.UpdateAsync(id, input); + } - [HttpDelete] - [Route("{id}")] - public virtual Task DeleteAsync(Guid id) - { - return UserAppService.DeleteAsync(id); - } + [HttpDelete] + [Route("{id}")] + public virtual Task DeleteAsync(Guid id) + { + return UserAppService.DeleteAsync(id); + } - [HttpGet] - [Route("{id}/roles")] - public virtual Task> GetRolesAsync(Guid id) - { - return UserAppService.GetRolesAsync(id); - } + [HttpGet] + [Route("{id}/roles")] + public virtual Task> GetRolesAsync(Guid id) + { + return UserAppService.GetRolesAsync(id); + } - [HttpGet] - [Route("assignable-roles")] - public Task> GetAssignableRolesAsync() - { - return UserAppService.GetAssignableRolesAsync(); - } + [HttpGet] + [Route("assignable-roles")] + public Task> GetAssignableRolesAsync() + { + return UserAppService.GetAssignableRolesAsync(); + } - [HttpPut] - [Route("{id}/roles")] - public virtual Task UpdateRolesAsync(Guid id, IdentityUserUpdateRolesDto input) - { - return UserAppService.UpdateRolesAsync(id, input); - } + [HttpPut] + [Route("{id}/roles")] + public virtual Task UpdateRolesAsync(Guid id, IdentityUserUpdateRolesDto input) + { + return UserAppService.UpdateRolesAsync(id, input); + } - [HttpGet] - [Route("by-username/{userName}")] - public virtual Task FindByUsernameAsync(string userName) - { - return UserAppService.FindByUsernameAsync(userName); - } + [HttpGet] + [Route("by-username/{userName}")] + public virtual Task FindByUsernameAsync(string userName) + { + return UserAppService.FindByUsernameAsync(userName); + } - [HttpGet] - [Route("by-email/{email}")] - public virtual Task FindByEmailAsync(string email) - { - return UserAppService.FindByEmailAsync(email); - } + [HttpGet] + [Route("by-email/{email}")] + public virtual Task FindByEmailAsync(string email) + { + return UserAppService.FindByEmailAsync(email); } } diff --git a/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityUserLookupController.cs b/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityUserLookupController.cs index b63bed3886..4db70514bd 100644 --- a/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityUserLookupController.cs +++ b/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityUserLookupController.cs @@ -5,47 +5,46 @@ using Volo.Abp.Application.Dtos; using Volo.Abp.AspNetCore.Mvc; using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[RemoteService(Name = IdentityRemoteServiceConsts.RemoteServiceName)] +[Area(IdentityRemoteServiceConsts.ModuleName)] +[ControllerName("UserLookup")] +[Route("api/identity/users/lookup")] +public class IdentityUserLookupController : AbpControllerBase, IIdentityUserLookupAppService { - [RemoteService(Name = IdentityRemoteServiceConsts.RemoteServiceName)] - [Area(IdentityRemoteServiceConsts.ModuleName)] - [ControllerName("UserLookup")] - [Route("api/identity/users/lookup")] - public class IdentityUserLookupController : AbpControllerBase, IIdentityUserLookupAppService - { - protected IIdentityUserLookupAppService LookupAppService { get; } + protected IIdentityUserLookupAppService LookupAppService { get; } - public IdentityUserLookupController(IIdentityUserLookupAppService lookupAppService) - { - LookupAppService = lookupAppService; - } + public IdentityUserLookupController(IIdentityUserLookupAppService lookupAppService) + { + LookupAppService = lookupAppService; + } - [HttpGet] - [Route("{id}")] - public virtual Task FindByIdAsync(Guid id) - { - return LookupAppService.FindByIdAsync(id); - } + [HttpGet] + [Route("{id}")] + public virtual Task FindByIdAsync(Guid id) + { + return LookupAppService.FindByIdAsync(id); + } - [HttpGet] - [Route("by-username/{userName}")] - public virtual Task FindByUserNameAsync(string userName) - { - return LookupAppService.FindByUserNameAsync(userName); - } + [HttpGet] + [Route("by-username/{userName}")] + public virtual Task FindByUserNameAsync(string userName) + { + return LookupAppService.FindByUserNameAsync(userName); + } - [HttpGet] - [Route("search")] - public Task> SearchAsync(UserLookupSearchInputDto input) - { - return LookupAppService.SearchAsync(input); - } + [HttpGet] + [Route("search")] + public Task> SearchAsync(UserLookupSearchInputDto input) + { + return LookupAppService.SearchAsync(input); + } - [HttpGet] - [Route("count")] - public Task GetCountAsync(UserLookupCountInputDto input) - { - return LookupAppService.GetCountAsync(input); - } + [HttpGet] + [Route("count")] + public Task GetCountAsync(UserLookupCountInputDto input) + { + return LookupAppService.GetCountAsync(input); } } diff --git a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbContext.cs b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbContext.cs index 7a59b255e3..1acc952024 100644 --- a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbContext.cs +++ b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbContext.cs @@ -2,28 +2,27 @@ using Volo.Abp.Data; using Volo.Abp.MongoDB; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[ConnectionStringName(AbpIdentityDbProperties.ConnectionStringName)] +public class AbpIdentityMongoDbContext : AbpMongoDbContext, IAbpIdentityMongoDbContext { - [ConnectionStringName(AbpIdentityDbProperties.ConnectionStringName)] - public class AbpIdentityMongoDbContext : AbpMongoDbContext, IAbpIdentityMongoDbContext - { - public IMongoCollection Users => Collection(); + public IMongoCollection Users => Collection(); - public IMongoCollection Roles => Collection(); + public IMongoCollection Roles => Collection(); - public IMongoCollection ClaimTypes => Collection(); + public IMongoCollection ClaimTypes => Collection(); - public IMongoCollection OrganizationUnits => Collection(); + public IMongoCollection OrganizationUnits => Collection(); - public IMongoCollection SecurityLogs => Collection(); + public IMongoCollection SecurityLogs => Collection(); - public IMongoCollection LinkUsers => Collection(); + public IMongoCollection LinkUsers => Collection(); - protected override void CreateModel(IMongoModelBuilder modelBuilder) - { - base.CreateModel(modelBuilder); + protected override void CreateModel(IMongoModelBuilder modelBuilder) + { + base.CreateModel(modelBuilder); - modelBuilder.ConfigureIdentity(); - } + modelBuilder.ConfigureIdentity(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbContextExtensions.cs b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbContextExtensions.cs index d589337593..4816664d68 100644 --- a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbContextExtensions.cs +++ b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbContextExtensions.cs @@ -1,42 +1,41 @@ using Volo.Abp.MongoDB; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +public static class AbpIdentityMongoDbContextExtensions { - public static class AbpIdentityMongoDbContextExtensions + public static void ConfigureIdentity(this IMongoModelBuilder builder) { - public static void ConfigureIdentity(this IMongoModelBuilder builder) + Check.NotNull(builder, nameof(builder)); + + builder.Entity(b => + { + b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "Users"; + }); + + builder.Entity(b => + { + b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "Roles"; + }); + + builder.Entity(b => + { + b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "ClaimTypes"; + }); + + builder.Entity(b => + { + b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "OrganizationUnits"; + }); + + builder.Entity(b => + { + b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "SecurityLogs"; + }); + + builder.Entity(b => { - Check.NotNull(builder, nameof(builder)); - - builder.Entity(b => - { - b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "Users"; - }); - - builder.Entity(b => - { - b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "Roles"; - }); - - builder.Entity(b => - { - b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "ClaimTypes"; - }); - - builder.Entity(b => - { - b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "OrganizationUnits"; - }); - - builder.Entity(b => - { - b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "SecurityLogs"; - }); - - builder.Entity(b => - { - b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "LinkUsers"; - }); - } + b.CollectionName = AbpIdentityDbProperties.DbTablePrefix + "LinkUsers"; + }); } } diff --git a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbModule.cs b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbModule.cs index 2d2be9637a..85fc619180 100644 --- a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbModule.cs @@ -2,25 +2,24 @@ using Volo.Abp.Modularity; using Volo.Abp.Users.MongoDB; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[DependsOn( + typeof(AbpIdentityDomainModule), + typeof(AbpUsersMongoDbModule) + )] +public class AbpIdentityMongoDbModule : AbpModule { - [DependsOn( - typeof(AbpIdentityDomainModule), - typeof(AbpUsersMongoDbModule) - )] - public class AbpIdentityMongoDbModule : AbpModule + public override void ConfigureServices(ServiceConfigurationContext context) { - public override void ConfigureServices(ServiceConfigurationContext context) + context.Services.AddMongoDbContext(options => { - context.Services.AddMongoDbContext(options => - { - options.AddRepository(); - options.AddRepository(); - options.AddRepository(); - options.AddRepository(); - options.AddRepository(); - options.AddRepository(); - }); - } + options.AddRepository(); + options.AddRepository(); + options.AddRepository(); + options.AddRepository(); + options.AddRepository(); + options.AddRepository(); + }); } } diff --git a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/IAbpIdentityMongoDbContext.cs b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/IAbpIdentityMongoDbContext.cs index 54e3ae7bdc..ad2ae429e1 100644 --- a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/IAbpIdentityMongoDbContext.cs +++ b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/IAbpIdentityMongoDbContext.cs @@ -2,21 +2,20 @@ using Volo.Abp.Data; using Volo.Abp.MongoDB; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[ConnectionStringName(AbpIdentityDbProperties.ConnectionStringName)] +public interface IAbpIdentityMongoDbContext : IAbpMongoDbContext { - [ConnectionStringName(AbpIdentityDbProperties.ConnectionStringName)] - public interface IAbpIdentityMongoDbContext : IAbpMongoDbContext - { - IMongoCollection Users { get; } + IMongoCollection Users { get; } - IMongoCollection Roles { get; } + IMongoCollection Roles { get; } - IMongoCollection ClaimTypes { get; } + IMongoCollection ClaimTypes { get; } - IMongoCollection OrganizationUnits { get; } + IMongoCollection OrganizationUnits { get; } - IMongoCollection SecurityLogs { get; } + IMongoCollection SecurityLogs { get; } - IMongoCollection LinkUsers { get; } - } + IMongoCollection LinkUsers { get; } } diff --git a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityClaimTypeRepository.cs b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityClaimTypeRepository.cs index 860a2c20e5..144e0655cf 100644 --- a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityClaimTypeRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityClaimTypeRepository.cs @@ -9,64 +9,63 @@ using System.Threading; using Volo.Abp.Domain.Repositories.MongoDB; using Volo.Abp.MongoDB; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +public class MongoIdentityClaimTypeRepository : MongoDbRepository, IIdentityClaimTypeRepository { - public class MongoIdentityClaimTypeRepository : MongoDbRepository, IIdentityClaimTypeRepository + public MongoIdentityClaimTypeRepository(IMongoDbContextProvider dbContextProvider) : base(dbContextProvider) { - public MongoIdentityClaimTypeRepository(IMongoDbContextProvider dbContextProvider) : base(dbContextProvider) - { - } - - public virtual async Task AnyAsync( - string name, - Guid? ignoredId = null, - CancellationToken cancellationToken = default) - { - if (ignoredId == null) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(ct => ct.Name == name) - .AnyAsync(GetCancellationToken(cancellationToken)); - } - else - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(ct => ct.Id != ignoredId && ct.Name == name) - .AnyAsync(GetCancellationToken(cancellationToken)); - } - } + } - public virtual async Task> GetListAsync( - string sorting, - int maxResultCount, - int skipCount, - string filter, - CancellationToken cancellationToken = default) + public virtual async Task AnyAsync( + string name, + Guid? ignoredId = null, + CancellationToken cancellationToken = default) + { + if (ignoredId == null) { return await (await GetMongoQueryableAsync(cancellationToken)) - .WhereIf>( - !filter.IsNullOrWhiteSpace(), - u => - u.Name.Contains(filter) - ) - .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityClaimType.Name) : sorting) - .As>() - .PageBy>(skipCount, maxResultCount) - .ToListAsync(GetCancellationToken(cancellationToken)); + .Where(ct => ct.Name == name) + .AnyAsync(GetCancellationToken(cancellationToken)); } - - public virtual async Task GetCountAsync( - string filter = null, - CancellationToken cancellationToken = default) + else { return await (await GetMongoQueryableAsync(cancellationToken)) - .WhereIf>( - !filter.IsNullOrWhiteSpace(), - u => - u.Name.Contains(filter) - ) - .As>() - .LongCountAsync(GetCancellationToken(cancellationToken)); + .Where(ct => ct.Id != ignoredId && ct.Name == name) + .AnyAsync(GetCancellationToken(cancellationToken)); } } + + public virtual async Task> GetListAsync( + string sorting, + int maxResultCount, + int skipCount, + string filter, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .WhereIf>( + !filter.IsNullOrWhiteSpace(), + u => + u.Name.Contains(filter) + ) + .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityClaimType.Name) : sorting) + .As>() + .PageBy>(skipCount, maxResultCount) + .ToListAsync(GetCancellationToken(cancellationToken)); + } + + public virtual async Task GetCountAsync( + string filter = null, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .WhereIf>( + !filter.IsNullOrWhiteSpace(), + u => + u.Name.Contains(filter) + ) + .As>() + .LongCountAsync(GetCancellationToken(cancellationToken)); + } } diff --git a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityLinkUserRepository.cs b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityLinkUserRepository.cs index bb30103dfc..20116fdd0b 100644 --- a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityLinkUserRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityLinkUserRepository.cs @@ -8,53 +8,52 @@ using MongoDB.Driver.Linq; using Volo.Abp.Domain.Repositories.MongoDB; using Volo.Abp.MongoDB; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +public class MongoIdentityLinkUserRepository : MongoDbRepository, IIdentityLinkUserRepository { - public class MongoIdentityLinkUserRepository : MongoDbRepository, IIdentityLinkUserRepository + public MongoIdentityLinkUserRepository(IMongoDbContextProvider dbContextProvider) : base(dbContextProvider) { - public MongoIdentityLinkUserRepository(IMongoDbContextProvider dbContextProvider) : base(dbContextProvider) - { - } + } - public virtual async Task FindAsync(IdentityLinkUserInfo sourceLinkUserInfo, IdentityLinkUserInfo targetLinkUserInfo, CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .OrderBy(x => x.Id).FirstOrDefaultAsync(x => - x.SourceUserId == sourceLinkUserInfo.UserId && x.SourceTenantId == sourceLinkUserInfo.TenantId && - x.TargetUserId == targetLinkUserInfo.UserId && x.TargetTenantId == targetLinkUserInfo.TenantId || - x.TargetUserId == sourceLinkUserInfo.UserId && x.TargetTenantId == sourceLinkUserInfo.TenantId && - x.SourceUserId == targetLinkUserInfo.UserId && x.SourceTenantId == targetLinkUserInfo.TenantId - , cancellationToken: GetCancellationToken(cancellationToken)); - } + public virtual async Task FindAsync(IdentityLinkUserInfo sourceLinkUserInfo, IdentityLinkUserInfo targetLinkUserInfo, CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .OrderBy(x => x.Id).FirstOrDefaultAsync(x => + x.SourceUserId == sourceLinkUserInfo.UserId && x.SourceTenantId == sourceLinkUserInfo.TenantId && + x.TargetUserId == targetLinkUserInfo.UserId && x.TargetTenantId == targetLinkUserInfo.TenantId || + x.TargetUserId == sourceLinkUserInfo.UserId && x.TargetTenantId == sourceLinkUserInfo.TenantId && + x.SourceUserId == targetLinkUserInfo.UserId && x.SourceTenantId == targetLinkUserInfo.TenantId + , cancellationToken: GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListAsync(IdentityLinkUserInfo linkUserInfo, List excludes = null, - CancellationToken cancellationToken = default) - { - var query = (await GetMongoQueryableAsync(cancellationToken)).Where(x => - x.SourceUserId == linkUserInfo.UserId && x.SourceTenantId == linkUserInfo.TenantId || - x.TargetUserId == linkUserInfo.UserId && x.TargetTenantId == linkUserInfo.TenantId); + public virtual async Task> GetListAsync(IdentityLinkUserInfo linkUserInfo, List excludes = null, + CancellationToken cancellationToken = default) + { + var query = (await GetMongoQueryableAsync(cancellationToken)).Where(x => + x.SourceUserId == linkUserInfo.UserId && x.SourceTenantId == linkUserInfo.TenantId || + x.TargetUserId == linkUserInfo.UserId && x.TargetTenantId == linkUserInfo.TenantId); - if (!excludes.IsNullOrEmpty()) + if (!excludes.IsNullOrEmpty()) + { + foreach (var userInfo in excludes) { - foreach (var userInfo in excludes) - { - query = query.Where(x => - (x.SourceTenantId != userInfo.TenantId || x.SourceUserId != userInfo.UserId) && - (x.TargetTenantId != userInfo.TenantId || x.TargetUserId != userInfo.UserId)); - } + query = query.Where(x => + (x.SourceTenantId != userInfo.TenantId || x.SourceUserId != userInfo.UserId) && + (x.TargetTenantId != userInfo.TenantId || x.TargetUserId != userInfo.UserId)); } - - return await query.ToListAsync(cancellationToken: GetCancellationToken(cancellationToken)); } - public virtual async Task DeleteAsync(IdentityLinkUserInfo linkUserInfo, CancellationToken cancellationToken = default) - { - var linkUsers = await (await GetMongoQueryableAsync(cancellationToken)).Where(x => - x.SourceUserId == linkUserInfo.UserId && x.SourceTenantId == linkUserInfo.TenantId || - x.TargetUserId == linkUserInfo.UserId && x.TargetTenantId == linkUserInfo.TenantId) - .ToListAsync(cancellationToken: GetCancellationToken(cancellationToken)); + return await query.ToListAsync(cancellationToken: GetCancellationToken(cancellationToken)); + } - await DeleteManyAsync(linkUsers, cancellationToken: cancellationToken); - } + public virtual async Task DeleteAsync(IdentityLinkUserInfo linkUserInfo, CancellationToken cancellationToken = default) + { + var linkUsers = await (await GetMongoQueryableAsync(cancellationToken)).Where(x => + x.SourceUserId == linkUserInfo.UserId && x.SourceTenantId == linkUserInfo.TenantId || + x.TargetUserId == linkUserInfo.UserId && x.TargetTenantId == linkUserInfo.TenantId) + .ToListAsync(cancellationToken: GetCancellationToken(cancellationToken)); + + await DeleteManyAsync(linkUsers, cancellationToken: cancellationToken); } } diff --git a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityRoleRepository.cs b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityRoleRepository.cs index dc538bd513..dfffe41116 100644 --- a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityRoleRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityRoleRepository.cs @@ -9,71 +9,70 @@ using MongoDB.Driver.Linq; using Volo.Abp.Domain.Repositories.MongoDB; using Volo.Abp.MongoDB; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +public class MongoIdentityRoleRepository : MongoDbRepository, IIdentityRoleRepository { - public class MongoIdentityRoleRepository : MongoDbRepository, IIdentityRoleRepository + public MongoIdentityRoleRepository(IMongoDbContextProvider dbContextProvider) + : base(dbContextProvider) { - public MongoIdentityRoleRepository(IMongoDbContextProvider dbContextProvider) - : base(dbContextProvider) - { - } + } - public virtual async Task FindByNormalizedNameAsync( - string normalizedRoleName, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .OrderBy(x => x.Id) - .FirstOrDefaultAsync(r => r.NormalizedName == normalizedRoleName, GetCancellationToken(cancellationToken)); - } + public virtual async Task FindByNormalizedNameAsync( + string normalizedRoleName, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync(r => r.NormalizedName == normalizedRoleName, GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListAsync( - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .WhereIf(!filter.IsNullOrWhiteSpace(), - x => x.Name.Contains(filter) || - x.NormalizedName.Contains(filter)) - .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityRole.Name) : sorting) - .As>() - .PageBy>(skipCount, maxResultCount) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetListAsync( + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .WhereIf(!filter.IsNullOrWhiteSpace(), + x => x.Name.Contains(filter) || + x.NormalizedName.Contains(filter)) + .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityRole.Name) : sorting) + .As>() + .PageBy>(skipCount, maxResultCount) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListAsync( - IEnumerable ids, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(t => ids.Contains(t.Id)) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetListAsync( + IEnumerable ids, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(t => ids.Contains(t.Id)) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetDefaultOnesAsync( - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(r => r.IsDefault) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetDefaultOnesAsync( + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(r => r.IsDefault) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task GetCountAsync( - string filter = null, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .WhereIf(!filter.IsNullOrWhiteSpace(), - x => x.Name.Contains(filter) || - x.NormalizedName.Contains(filter)) - .As>() - .LongCountAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task GetCountAsync( + string filter = null, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .WhereIf(!filter.IsNullOrWhiteSpace(), + x => x.Name.Contains(filter) || + x.NormalizedName.Contains(filter)) + .As>() + .LongCountAsync(GetCancellationToken(cancellationToken)); } } diff --git a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentitySecurityLogRepository.cs b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentitySecurityLogRepository.cs index adb5883e16..de5587d8d9 100644 --- a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentitySecurityLogRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentitySecurityLogRepository.cs @@ -9,112 +9,111 @@ using MongoDB.Driver.Linq; using Volo.Abp.Domain.Repositories.MongoDB; using Volo.Abp.MongoDB; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +public class MongoIdentitySecurityLogRepository : + MongoDbRepository, IIdentitySecurityLogRepository { - public class MongoIdentitySecurityLogRepository : - MongoDbRepository, IIdentitySecurityLogRepository + public MongoIdentitySecurityLogRepository(IMongoDbContextProvider dbContextProvider) + : base(dbContextProvider) { - public MongoIdentitySecurityLogRepository(IMongoDbContextProvider dbContextProvider) - : base(dbContextProvider) - { - } + } - public virtual async Task> GetListAsync( - string sorting = null, - int maxResultCount = 50, - int skipCount = 0, - DateTime? startTime = null, - DateTime? endTime = null, - string applicationName = null, - string identity = null, - string action = null, - Guid? userId = null, - string userName = null, - string clientId = null, - string correlationId = null, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var query = await GetListQueryAsync( - startTime, - endTime, - applicationName, - identity, - action, - userId, - userName, - clientId, - correlationId, - cancellationToken - ); + public virtual async Task> GetListAsync( + string sorting = null, + int maxResultCount = 50, + int skipCount = 0, + DateTime? startTime = null, + DateTime? endTime = null, + string applicationName = null, + string identity = null, + string action = null, + Guid? userId = null, + string userName = null, + string clientId = null, + string correlationId = null, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var query = await GetListQueryAsync( + startTime, + endTime, + applicationName, + identity, + action, + userId, + userName, + clientId, + correlationId, + cancellationToken + ); - return await query.OrderBy(sorting.IsNullOrWhiteSpace() ? $"{nameof(IdentitySecurityLog.CreationTime)} desc" : sorting) - .As>() - .PageBy>(skipCount, maxResultCount) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + return await query.OrderBy(sorting.IsNullOrWhiteSpace() ? $"{nameof(IdentitySecurityLog.CreationTime)} desc" : sorting) + .As>() + .PageBy>(skipCount, maxResultCount) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task GetCountAsync( - DateTime? startTime = null, - DateTime? endTime = null, - string applicationName = null, - string identity = null, - string action = null, - Guid? userId = null, - string userName = null, - string clientId = null, - string correlationId = null, - CancellationToken cancellationToken = default) - { - var query = await GetListQueryAsync( - startTime, - endTime, - applicationName, - identity, - action, - userId, - userName, - clientId, - correlationId, - cancellationToken - ); + public virtual async Task GetCountAsync( + DateTime? startTime = null, + DateTime? endTime = null, + string applicationName = null, + string identity = null, + string action = null, + Guid? userId = null, + string userName = null, + string clientId = null, + string correlationId = null, + CancellationToken cancellationToken = default) + { + var query = await GetListQueryAsync( + startTime, + endTime, + applicationName, + identity, + action, + userId, + userName, + clientId, + correlationId, + cancellationToken + ); - return await query.As>() - .LongCountAsync(GetCancellationToken(cancellationToken)); - } + return await query.As>() + .LongCountAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task GetByUserIdAsync(Guid id, Guid userId, bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)).OrderBy(x => x.Id).FirstOrDefaultAsync(x => x.Id == id && x.UserId == userId, - GetCancellationToken(cancellationToken)); - } + public virtual async Task GetByUserIdAsync(Guid id, Guid userId, bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)).OrderBy(x => x.Id).FirstOrDefaultAsync(x => x.Id == id && x.UserId == userId, + GetCancellationToken(cancellationToken)); + } - protected virtual async Task> GetListQueryAsync( - DateTime? startTime = null, - DateTime? endTime = null, - string applicationName = null, - string identity = null, - string action = null, - Guid? userId = null, - string userName = null, - string clientId = null, - string correlationId = null, - CancellationToken cancellationToken = default) - { - return (await GetMongoQueryableAsync(cancellationToken)) - .WhereIf(startTime.HasValue, securityLog => securityLog.CreationTime >= startTime.Value) - .WhereIf(endTime.HasValue, securityLog => securityLog.CreationTime < endTime.Value.AddDays(1).Date) - .WhereIf(!applicationName.IsNullOrWhiteSpace(), - securityLog => securityLog.ApplicationName == applicationName) - .WhereIf(!identity.IsNullOrWhiteSpace(), securityLog => securityLog.Identity == identity) - .WhereIf(!action.IsNullOrWhiteSpace(), securityLog => securityLog.Action == action) - .WhereIf(userId.HasValue, securityLog => securityLog.UserId == userId) - .WhereIf(!userName.IsNullOrWhiteSpace(), securityLog => securityLog.UserName == userName) - .WhereIf(!clientId.IsNullOrWhiteSpace(), securityLog => securityLog.ClientId == clientId) - .WhereIf(!correlationId.IsNullOrWhiteSpace(), - securityLog => securityLog.CorrelationId == correlationId); - } + protected virtual async Task> GetListQueryAsync( + DateTime? startTime = null, + DateTime? endTime = null, + string applicationName = null, + string identity = null, + string action = null, + Guid? userId = null, + string userName = null, + string clientId = null, + string correlationId = null, + CancellationToken cancellationToken = default) + { + return (await GetMongoQueryableAsync(cancellationToken)) + .WhereIf(startTime.HasValue, securityLog => securityLog.CreationTime >= startTime.Value) + .WhereIf(endTime.HasValue, securityLog => securityLog.CreationTime < endTime.Value.AddDays(1).Date) + .WhereIf(!applicationName.IsNullOrWhiteSpace(), + securityLog => securityLog.ApplicationName == applicationName) + .WhereIf(!identity.IsNullOrWhiteSpace(), securityLog => securityLog.Identity == identity) + .WhereIf(!action.IsNullOrWhiteSpace(), securityLog => securityLog.Action == action) + .WhereIf(userId.HasValue, securityLog => securityLog.UserId == userId) + .WhereIf(!userName.IsNullOrWhiteSpace(), securityLog => securityLog.UserName == userName) + .WhereIf(!clientId.IsNullOrWhiteSpace(), securityLog => securityLog.ClientId == clientId) + .WhereIf(!correlationId.IsNullOrWhiteSpace(), + securityLog => securityLog.CorrelationId == correlationId); } } diff --git a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityUserRepository.cs b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityUserRepository.cs index 42a9065103..7a953ed81e 100644 --- a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityUserRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoIdentityUserRepository.cs @@ -10,260 +10,259 @@ using MongoDB.Driver.Linq; using Volo.Abp.Domain.Repositories.MongoDB; using Volo.Abp.MongoDB; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +public class MongoIdentityUserRepository : MongoDbRepository, IIdentityUserRepository { - public class MongoIdentityUserRepository : MongoDbRepository, IIdentityUserRepository + public MongoIdentityUserRepository(IMongoDbContextProvider dbContextProvider) + : base(dbContextProvider) { - public MongoIdentityUserRepository(IMongoDbContextProvider dbContextProvider) - : base(dbContextProvider) - { - } - - public virtual async Task FindByNormalizedUserNameAsync( - string normalizedUserName, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .OrderBy(x => x.Id) - .FirstOrDefaultAsync( - u => u.NormalizedUserName == normalizedUserName, - GetCancellationToken(cancellationToken) - ); - } + } - public virtual async Task> GetRoleNamesAsync( - Guid id, - CancellationToken cancellationToken = default) - { - var user = await GetAsync(id, cancellationToken: GetCancellationToken(cancellationToken)); - var organizationUnitIds = user.OrganizationUnits - .Select(r => r.OrganizationUnitId) - .ToArray(); + public virtual async Task FindByNormalizedUserNameAsync( + string normalizedUserName, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync( + u => u.NormalizedUserName == normalizedUserName, + GetCancellationToken(cancellationToken) + ); + } - var organizationUnits = await (await GetMongoQueryableAsync(cancellationToken)) - .Where(ou => organizationUnitIds.Contains(ou.Id)) - .ToListAsync(cancellationToken: cancellationToken); - var orgUnitRoleIds = organizationUnits.SelectMany(x => x.Roles.Select(r => r.RoleId)).ToArray(); - var roleIds = user.Roles.Select(r => r.RoleId).ToArray(); - var allRoleIds = orgUnitRoleIds.Union(roleIds); - return await (await GetMongoQueryableAsync(cancellationToken)).Where(r => allRoleIds.Contains(r.Id)).Select(r => r.Name).ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetRoleNamesAsync( + Guid id, + CancellationToken cancellationToken = default) + { + var user = await GetAsync(id, cancellationToken: GetCancellationToken(cancellationToken)); + var organizationUnitIds = user.OrganizationUnits + .Select(r => r.OrganizationUnitId) + .ToArray(); - public virtual async Task> GetRoleNamesInOrganizationUnitAsync( - Guid id, - CancellationToken cancellationToken = default) - { - var user = await GetAsync(id, cancellationToken: GetCancellationToken(cancellationToken)); + var organizationUnits = await (await GetMongoQueryableAsync(cancellationToken)) + .Where(ou => organizationUnitIds.Contains(ou.Id)) + .ToListAsync(cancellationToken: cancellationToken); + var orgUnitRoleIds = organizationUnits.SelectMany(x => x.Roles.Select(r => r.RoleId)).ToArray(); + var roleIds = user.Roles.Select(r => r.RoleId).ToArray(); + var allRoleIds = orgUnitRoleIds.Union(roleIds); + return await (await GetMongoQueryableAsync(cancellationToken)).Where(r => allRoleIds.Contains(r.Id)).Select(r => r.Name).ToListAsync(GetCancellationToken(cancellationToken)); + } - var organizationUnitIds = user.OrganizationUnits - .Select(r => r.OrganizationUnitId) - .ToArray(); + public virtual async Task> GetRoleNamesInOrganizationUnitAsync( + Guid id, + CancellationToken cancellationToken = default) + { + var user = await GetAsync(id, cancellationToken: GetCancellationToken(cancellationToken)); - var organizationUnits = await (await GetMongoQueryableAsync(cancellationToken)) - .Where(ou => organizationUnitIds.Contains(ou.Id)) - .ToListAsync(cancellationToken: cancellationToken); + var organizationUnitIds = user.OrganizationUnits + .Select(r => r.OrganizationUnitId) + .ToArray(); - var roleIds = organizationUnits.SelectMany(x => x.Roles.Select(r => r.RoleId)).ToArray(); + var organizationUnits = await (await GetMongoQueryableAsync(cancellationToken)) + .Where(ou => organizationUnitIds.Contains(ou.Id)) + .ToListAsync(cancellationToken: cancellationToken); - var queryable = await GetMongoQueryableAsync(cancellationToken); + var roleIds = organizationUnits.SelectMany(x => x.Roles.Select(r => r.RoleId)).ToArray(); - return await queryable - .Where(r => roleIds.Contains(r.Id)) - .Select(r => r.Name) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + var queryable = await GetMongoQueryableAsync(cancellationToken); - public virtual async Task FindByLoginAsync( - string loginProvider, - string providerKey, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(u => u.Logins.Any(login => login.LoginProvider == loginProvider && login.ProviderKey == providerKey)) - .OrderBy(x => x.Id) - .FirstOrDefaultAsync(GetCancellationToken(cancellationToken)); - } - - public virtual async Task FindByNormalizedEmailAsync( - string normalizedEmail, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .OrderBy(x => x.Id).FirstOrDefaultAsync(u => u.NormalizedEmail == normalizedEmail, GetCancellationToken(cancellationToken)); - } + return await queryable + .Where(r => roleIds.Contains(r.Id)) + .Select(r => r.Name) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListByClaimAsync( - Claim claim, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(u => u.Claims.Any(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value)) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task FindByLoginAsync( + string loginProvider, + string providerKey, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(u => u.Logins.Any(login => login.LoginProvider == loginProvider && login.ProviderKey == providerKey)) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListByNormalizedRoleNameAsync( - string normalizedRoleName, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - cancellationToken = GetCancellationToken(cancellationToken); + public virtual async Task FindByNormalizedEmailAsync( + string normalizedEmail, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .OrderBy(x => x.Id).FirstOrDefaultAsync(u => u.NormalizedEmail == normalizedEmail, GetCancellationToken(cancellationToken)); + } - var queryable = await GetMongoQueryableAsync(cancellationToken); + public virtual async Task> GetListByClaimAsync( + Claim claim, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(u => u.Claims.Any(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value)) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - var role = await queryable - .Where(x => x.NormalizedName == normalizedRoleName) - .OrderBy(x => x.Id) - .FirstOrDefaultAsync(cancellationToken); + public virtual async Task> GetListByNormalizedRoleNameAsync( + string normalizedRoleName, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + cancellationToken = GetCancellationToken(cancellationToken); - if (role == null) - { - return new List(); - } + var queryable = await GetMongoQueryableAsync(cancellationToken); - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(u => u.Roles.Any(r => r.RoleId == role.Id)) - .ToListAsync(cancellationToken); - } + var role = await queryable + .Where(x => x.NormalizedName == normalizedRoleName) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync(cancellationToken); - public virtual async Task> GetListAsync( - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - Guid? roleId = null, - Guid? organizationUnitId = null, - string userName = null, - string phoneNumber = null, - string emailAddress = null, - bool? isLockedOut = null, - bool? notActive = null, - CancellationToken cancellationToken = default) + if (role == null) { - return await (await GetMongoQueryableAsync(cancellationToken)) - .WhereIf>( - !filter.IsNullOrWhiteSpace(), - u => - u.UserName.Contains(filter) || - u.Email.Contains(filter) || - (u.Name != null && u.Name.Contains(filter)) || - (u.Surname != null && u.Surname.Contains(filter)) || - (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) - ) - .WhereIf>(roleId.HasValue, identityUser => identityUser.Roles.Any(x => x.RoleId == roleId.Value)) - .WhereIf>(organizationUnitId.HasValue, identityUser => identityUser.OrganizationUnits.Any(x => x.OrganizationUnitId == organizationUnitId.Value)) - .WhereIf>(!string.IsNullOrWhiteSpace(userName), x => x.UserName == userName) - .WhereIf>(!string.IsNullOrWhiteSpace(phoneNumber), x => x.PhoneNumber == phoneNumber) - .WhereIf>(!string.IsNullOrWhiteSpace(emailAddress), x => x.Email == emailAddress) - .WhereIf>(isLockedOut == true, x => x.LockoutEnabled && x.LockoutEnd > DateTimeOffset.UtcNow) - .WhereIf>(notActive == true, x => !x.IsActive) - .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityUser.UserName) : sorting) - .As>() - .PageBy>(skipCount, maxResultCount) - .ToListAsync(GetCancellationToken(cancellationToken)); + return new List(); } - public virtual async Task> GetRolesAsync( - Guid id, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var user = await GetAsync(id, cancellationToken: GetCancellationToken(cancellationToken)); - var organizationUnitIds = user.OrganizationUnits - .Select(r => r.OrganizationUnitId) - .ToArray(); + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(u => u.Roles.Any(r => r.RoleId == role.Id)) + .ToListAsync(cancellationToken); + } - var organizationUnits = await (await GetMongoQueryableAsync(cancellationToken)) - .Where(ou => organizationUnitIds.Contains(ou.Id)) - .ToListAsync(cancellationToken: cancellationToken); - var orgUnitRoleIds = organizationUnits.SelectMany(x => x.Roles.Select(r => r.RoleId)).ToArray(); - var roleIds = user.Roles.Select(r => r.RoleId).ToArray(); - var allRoleIds = orgUnitRoleIds.Union(roleIds); - return await (await GetMongoQueryableAsync(cancellationToken)).Where(r => allRoleIds.Contains(r.Id)).ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetListAsync( + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + Guid? roleId = null, + Guid? organizationUnitId = null, + string userName = null, + string phoneNumber = null, + string emailAddress = null, + bool? isLockedOut = null, + bool? notActive = null, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .WhereIf>( + !filter.IsNullOrWhiteSpace(), + u => + u.UserName.Contains(filter) || + u.Email.Contains(filter) || + (u.Name != null && u.Name.Contains(filter)) || + (u.Surname != null && u.Surname.Contains(filter)) || + (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) + ) + .WhereIf>(roleId.HasValue, identityUser => identityUser.Roles.Any(x => x.RoleId == roleId.Value)) + .WhereIf>(organizationUnitId.HasValue, identityUser => identityUser.OrganizationUnits.Any(x => x.OrganizationUnitId == organizationUnitId.Value)) + .WhereIf>(!string.IsNullOrWhiteSpace(userName), x => x.UserName == userName) + .WhereIf>(!string.IsNullOrWhiteSpace(phoneNumber), x => x.PhoneNumber == phoneNumber) + .WhereIf>(!string.IsNullOrWhiteSpace(emailAddress), x => x.Email == emailAddress) + .WhereIf>(isLockedOut == true, x => x.LockoutEnabled && x.LockoutEnd > DateTimeOffset.UtcNow) + .WhereIf>(notActive == true, x => !x.IsActive) + .OrderBy(sorting.IsNullOrWhiteSpace() ? nameof(IdentityUser.UserName) : sorting) + .As>() + .PageBy>(skipCount, maxResultCount) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetOrganizationUnitsAsync( - Guid id, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var user = await GetAsync(id, cancellationToken: GetCancellationToken(cancellationToken)); - var organizationUnitIds = user.OrganizationUnits.Select(r => r.OrganizationUnitId); + public virtual async Task> GetRolesAsync( + Guid id, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var user = await GetAsync(id, cancellationToken: GetCancellationToken(cancellationToken)); + var organizationUnitIds = user.OrganizationUnits + .Select(r => r.OrganizationUnitId) + .ToArray(); - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(ou => organizationUnitIds.Contains(ou.Id)) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + var organizationUnits = await (await GetMongoQueryableAsync(cancellationToken)) + .Where(ou => organizationUnitIds.Contains(ou.Id)) + .ToListAsync(cancellationToken: cancellationToken); + var orgUnitRoleIds = organizationUnits.SelectMany(x => x.Roles.Select(r => r.RoleId)).ToArray(); + var roleIds = user.Roles.Select(r => r.RoleId).ToArray(); + var allRoleIds = orgUnitRoleIds.Union(roleIds); + return await (await GetMongoQueryableAsync(cancellationToken)).Where(r => allRoleIds.Contains(r.Id)).ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task GetCountAsync( - string filter = null, - Guid? roleId = null, - Guid? organizationUnitId = null, - string userName = null, - string phoneNumber = null, - string emailAddress = null, - bool? isLockedOut = null, - bool? notActive = null, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .WhereIf>( - !filter.IsNullOrWhiteSpace(), - u => - u.UserName.Contains(filter) || - u.Email.Contains(filter) || - (u.Name != null && u.Name.Contains(filter)) || - (u.Surname != null && u.Surname.Contains(filter)) || - (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) - ) - .WhereIf>(roleId.HasValue, identityUser => identityUser.Roles.Any(x => x.RoleId == roleId.Value)) - .WhereIf>(organizationUnitId.HasValue, identityUser => identityUser.OrganizationUnits.Any(x => x.OrganizationUnitId == organizationUnitId.Value)) - .WhereIf>(!string.IsNullOrWhiteSpace(userName), x => x.UserName == userName) - .WhereIf>(!string.IsNullOrWhiteSpace(phoneNumber), x => x.PhoneNumber == phoneNumber) - .WhereIf>(!string.IsNullOrWhiteSpace(emailAddress), x => x.Email == emailAddress) - .WhereIf>(isLockedOut == true, x => x.LockoutEnabled && x.LockoutEnd > DateTimeOffset.UtcNow) - .WhereIf>(notActive == true, x => !x.IsActive) - .LongCountAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetOrganizationUnitsAsync( + Guid id, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var user = await GetAsync(id, cancellationToken: GetCancellationToken(cancellationToken)); + var organizationUnitIds = user.OrganizationUnits.Select(r => r.OrganizationUnitId); - public virtual async Task> GetUsersInOrganizationUnitAsync( - Guid organizationUnitId, - CancellationToken cancellationToken = default) - { - var result = await (await GetMongoQueryableAsync(cancellationToken)) - .Where(u => u.OrganizationUnits.Any(uou => uou.OrganizationUnitId == organizationUnitId)) - .ToListAsync(GetCancellationToken(cancellationToken)); - return result; - } + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(ou => organizationUnitIds.Contains(ou.Id)) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetUsersInOrganizationsListAsync( - List organizationUnitIds, - CancellationToken cancellationToken = default) - { - var result = await (await GetMongoQueryableAsync(cancellationToken)) - .Where(u => u.OrganizationUnits.Any(uou => organizationUnitIds.Contains(uou.OrganizationUnitId))) - .ToListAsync(GetCancellationToken(cancellationToken)); - return result; - } + public virtual async Task GetCountAsync( + string filter = null, + Guid? roleId = null, + Guid? organizationUnitId = null, + string userName = null, + string phoneNumber = null, + string emailAddress = null, + bool? isLockedOut = null, + bool? notActive = null, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .WhereIf>( + !filter.IsNullOrWhiteSpace(), + u => + u.UserName.Contains(filter) || + u.Email.Contains(filter) || + (u.Name != null && u.Name.Contains(filter)) || + (u.Surname != null && u.Surname.Contains(filter)) || + (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) + ) + .WhereIf>(roleId.HasValue, identityUser => identityUser.Roles.Any(x => x.RoleId == roleId.Value)) + .WhereIf>(organizationUnitId.HasValue, identityUser => identityUser.OrganizationUnits.Any(x => x.OrganizationUnitId == organizationUnitId.Value)) + .WhereIf>(!string.IsNullOrWhiteSpace(userName), x => x.UserName == userName) + .WhereIf>(!string.IsNullOrWhiteSpace(phoneNumber), x => x.PhoneNumber == phoneNumber) + .WhereIf>(!string.IsNullOrWhiteSpace(emailAddress), x => x.Email == emailAddress) + .WhereIf>(isLockedOut == true, x => x.LockoutEnabled && x.LockoutEnd > DateTimeOffset.UtcNow) + .WhereIf>(notActive == true, x => !x.IsActive) + .LongCountAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetUsersInOrganizationUnitWithChildrenAsync( - string code, - CancellationToken cancellationToken = default) - { - cancellationToken = GetCancellationToken(cancellationToken); + public virtual async Task> GetUsersInOrganizationUnitAsync( + Guid organizationUnitId, + CancellationToken cancellationToken = default) + { + var result = await (await GetMongoQueryableAsync(cancellationToken)) + .Where(u => u.OrganizationUnits.Any(uou => uou.OrganizationUnitId == organizationUnitId)) + .ToListAsync(GetCancellationToken(cancellationToken)); + return result; + } + + public virtual async Task> GetUsersInOrganizationsListAsync( + List organizationUnitIds, + CancellationToken cancellationToken = default) + { + var result = await (await GetMongoQueryableAsync(cancellationToken)) + .Where(u => u.OrganizationUnits.Any(uou => organizationUnitIds.Contains(uou.OrganizationUnitId))) + .ToListAsync(GetCancellationToken(cancellationToken)); + return result; + } + + public virtual async Task> GetUsersInOrganizationUnitWithChildrenAsync( + string code, + CancellationToken cancellationToken = default) + { + cancellationToken = GetCancellationToken(cancellationToken); - var organizationUnitIds = await (await GetMongoQueryableAsync(cancellationToken)) - .Where(ou => ou.Code.StartsWith(code)) - .Select(ou => ou.Id) - .ToListAsync(cancellationToken); + var organizationUnitIds = await (await GetMongoQueryableAsync(cancellationToken)) + .Where(ou => ou.Code.StartsWith(code)) + .Select(ou => ou.Id) + .ToListAsync(cancellationToken); - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(u => u.OrganizationUnits.Any(uou => organizationUnitIds.Contains(uou.OrganizationUnitId))) - .ToListAsync(cancellationToken); - } + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(u => u.OrganizationUnits.Any(uou => organizationUnitIds.Contains(uou.OrganizationUnitId))) + .ToListAsync(cancellationToken); } } diff --git a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoOrganizationUnitRepository.cs b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoOrganizationUnitRepository.cs index b57b3ec388..5f0f5fd097 100644 --- a/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoOrganizationUnitRepository.cs +++ b/modules/identity/src/Volo.Abp.Identity.MongoDB/Volo/Abp/Identity/MongoDB/MongoOrganizationUnitRepository.cs @@ -10,242 +10,241 @@ using Volo.Abp.Domain.Repositories.MongoDB; using Volo.Abp.MongoDB; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +public class MongoOrganizationUnitRepository + : MongoDbRepository, + IOrganizationUnitRepository { - public class MongoOrganizationUnitRepository - : MongoDbRepository, - IOrganizationUnitRepository + public MongoOrganizationUnitRepository( + IMongoDbContextProvider dbContextProvider) + : base(dbContextProvider) { - public MongoOrganizationUnitRepository( - IMongoDbContextProvider dbContextProvider) - : base(dbContextProvider) - { - } + } - public virtual async Task> GetChildrenAsync( - Guid? parentId, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(ou => ou.ParentId == parentId) + public virtual async Task> GetChildrenAsync( + Guid? parentId, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(ou => ou.ParentId == parentId) + .ToListAsync(GetCancellationToken(cancellationToken)); + } + + public virtual async Task> GetAllChildrenWithParentCodeAsync( + string code, + Guid? parentId, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(ou => ou.Code.StartsWith(code) && ou.Id != parentId.Value) .ToListAsync(GetCancellationToken(cancellationToken)); - } + } - public virtual async Task> GetAllChildrenWithParentCodeAsync( - string code, - Guid? parentId, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(ou => ou.Code.StartsWith(code) && ou.Id != parentId.Value) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetListAsync( + IEnumerable ids, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(t => ids.Contains(t.Id)) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListAsync( - IEnumerable ids, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(t => ids.Contains(t.Id)) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task> GetListAsync( + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .OrderBy(sorting.IsNullOrEmpty() ? nameof(OrganizationUnit.DisplayName) : sorting) + .As>() + .PageBy>(skipCount, maxResultCount) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetListAsync( - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .OrderBy(sorting.IsNullOrEmpty() ? nameof(OrganizationUnit.DisplayName) : sorting) - .As>() - .PageBy>(skipCount, maxResultCount) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task GetAsync( + string displayName, + bool includeDetails = true, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .OrderBy(x => x.Id) + .FirstOrDefaultAsync( + ou => ou.DisplayName == displayName, + GetCancellationToken(cancellationToken) + ); + } - public virtual async Task GetAsync( - string displayName, - bool includeDetails = true, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .OrderBy(x => x.Id) - .FirstOrDefaultAsync( - ou => ou.DisplayName == displayName, - GetCancellationToken(cancellationToken) - ); - } + public virtual async Task> GetRolesAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToArray(); + + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(r => roleIds.Contains(r.Id)) + .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityRole.Name) : sorting) + .As>() + .PageBy>(skipCount, maxResultCount) + .ToListAsync(cancellationToken); + } - public virtual async Task> GetRolesAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToArray(); - - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(r => roleIds.Contains(r.Id)) - .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityRole.Name) : sorting) - .As>() - .PageBy>(skipCount, maxResultCount) - .ToListAsync(cancellationToken); - } + public virtual async Task GetRolesCountAsync( + OrganizationUnit organizationUnit, + CancellationToken cancellationToken = default) + { + var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToArray(); - public virtual async Task GetRolesCountAsync( - OrganizationUnit organizationUnit, - CancellationToken cancellationToken = default) - { - var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToArray(); + return await (await GetMongoQueryableAsync(cancellationToken)).Where(r => roleIds.Contains(r.Id)).CountAsync(cancellationToken); + } - return await (await GetMongoQueryableAsync(cancellationToken)).Where(r => roleIds.Contains(r.Id)).CountAsync(cancellationToken); - } + public virtual async Task> GetUnaddedRolesAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToArray(); + + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(r => !roleIds.Contains(r.Id)) + .WhereIf(!filter.IsNullOrWhiteSpace(), r => r.Name.Contains(filter)) + .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityRole.Name) : sorting) + .As>() + .PageBy>(skipCount, maxResultCount) + .ToListAsync(cancellationToken); + } - public virtual async Task> GetUnaddedRolesAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToArray(); - - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(r => !roleIds.Contains(r.Id)) - .WhereIf(!filter.IsNullOrWhiteSpace(), r => r.Name.Contains(filter)) - .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityRole.Name) : sorting) - .As>() - .PageBy>(skipCount, maxResultCount) - .ToListAsync(cancellationToken); - } + public virtual async Task GetUnaddedRolesCountAsync( + OrganizationUnit organizationUnit, + string filter = null, + CancellationToken cancellationToken = default) + { + var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToArray(); - public virtual async Task GetUnaddedRolesCountAsync( - OrganizationUnit organizationUnit, - string filter = null, - CancellationToken cancellationToken = default) - { - var roleIds = organizationUnit.Roles.Select(r => r.RoleId).ToArray(); + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(r => !roleIds.Contains(r.Id)) + .WhereIf(!filter.IsNullOrWhiteSpace(), r => r.Name.Contains(filter)) + .As>() + .CountAsync(cancellationToken); + } - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(r => !roleIds.Contains(r.Id)) - .WhereIf(!filter.IsNullOrWhiteSpace(), r => r.Name.Contains(filter)) - .As>() - .CountAsync(cancellationToken); - } + public virtual async Task> GetMembersAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + cancellationToken = GetCancellationToken(cancellationToken); + var query = await CreateGetMembersFilteredQueryAsync(organizationUnit, filter, cancellationToken); + return await query + .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityUser.UserName) : sorting) + .As>() + .PageBy>(skipCount, maxResultCount) + .ToListAsync(cancellationToken); + } - public virtual async Task> GetMembersAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - cancellationToken = GetCancellationToken(cancellationToken); - var query = await CreateGetMembersFilteredQueryAsync(organizationUnit, filter, cancellationToken); - return await query - .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityUser.UserName) : sorting) - .As>() - .PageBy>(skipCount, maxResultCount) - .ToListAsync(cancellationToken); - } + public virtual async Task GetMembersCountAsync( + OrganizationUnit organizationUnit, + string filter = null, + CancellationToken cancellationToken = default) + { + cancellationToken = GetCancellationToken(cancellationToken); + var query = await CreateGetMembersFilteredQueryAsync(organizationUnit, filter, cancellationToken); + return await query.CountAsync(cancellationToken); + } - public virtual async Task GetMembersCountAsync( - OrganizationUnit organizationUnit, - string filter = null, - CancellationToken cancellationToken = default) - { - cancellationToken = GetCancellationToken(cancellationToken); - var query = await CreateGetMembersFilteredQueryAsync(organizationUnit, filter, cancellationToken); - return await query.CountAsync(cancellationToken); - } + public virtual async Task> GetUnaddedUsersAsync( + OrganizationUnit organizationUnit, + string sorting = null, + int maxResultCount = int.MaxValue, + int skipCount = 0, + string filter = null, + bool includeDetails = false, + CancellationToken cancellationToken = default) + { + return await + (await GetMongoQueryableAsync(cancellationToken)) + .Where(u => !u.OrganizationUnits.Any(uou => uou.OrganizationUnitId == organizationUnit.Id)) + .WhereIf>( + !filter.IsNullOrWhiteSpace(), + u => + u.UserName.Contains(filter) || + u.Email.Contains(filter) || + (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) + ) + .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityUser.UserName) : sorting) + .As>() + .PageBy>(skipCount, maxResultCount) + .ToListAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task> GetUnaddedUsersAsync( - OrganizationUnit organizationUnit, - string sorting = null, - int maxResultCount = int.MaxValue, - int skipCount = 0, - string filter = null, - bool includeDetails = false, - CancellationToken cancellationToken = default) - { - return await - (await GetMongoQueryableAsync(cancellationToken)) - .Where(u => !u.OrganizationUnits.Any(uou => uou.OrganizationUnitId == organizationUnit.Id)) - .WhereIf>( - !filter.IsNullOrWhiteSpace(), - u => - u.UserName.Contains(filter) || - u.Email.Contains(filter) || - (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) - ) - .OrderBy(sorting.IsNullOrEmpty() ? nameof(IdentityUser.UserName) : sorting) - .As>() - .PageBy>(skipCount, maxResultCount) - .ToListAsync(GetCancellationToken(cancellationToken)); - } + public virtual async Task GetUnaddedUsersCountAsync(OrganizationUnit organizationUnit, string filter = null, + CancellationToken cancellationToken = default) + { + return await (await GetMongoQueryableAsync(cancellationToken)) + .Where(u => !u.OrganizationUnits.Any(uou => uou.OrganizationUnitId == organizationUnit.Id)) + .WhereIf>( + !filter.IsNullOrWhiteSpace(), + u => + u.UserName.Contains(filter) || + u.Email.Contains(filter) || + (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) + ) + .As>() + .CountAsync(GetCancellationToken(cancellationToken)); + } - public virtual async Task GetUnaddedUsersCountAsync(OrganizationUnit organizationUnit, string filter = null, - CancellationToken cancellationToken = default) - { - return await (await GetMongoQueryableAsync(cancellationToken)) - .Where(u => !u.OrganizationUnits.Any(uou => uou.OrganizationUnitId == organizationUnit.Id)) - .WhereIf>( - !filter.IsNullOrWhiteSpace(), - u => - u.UserName.Contains(filter) || - u.Email.Contains(filter) || - (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) - ) - .As>() - .CountAsync(GetCancellationToken(cancellationToken)); - } + public virtual Task RemoveAllRolesAsync(OrganizationUnit organizationUnit, CancellationToken cancellationToken = default) + { + organizationUnit.Roles.Clear(); + return Task.FromResult(0); + } - public virtual Task RemoveAllRolesAsync(OrganizationUnit organizationUnit, CancellationToken cancellationToken = default) - { - organizationUnit.Roles.Clear(); - return Task.FromResult(0); - } + public virtual async Task RemoveAllMembersAsync(OrganizationUnit organizationUnit, CancellationToken cancellationToken = default) + { + var userQueryable = await GetMongoQueryableAsync(cancellationToken); + var dbContext = await GetDbContextAsync(cancellationToken); + var users = await userQueryable + .Where(u => u.OrganizationUnits.Any(uou => uou.OrganizationUnitId == organizationUnit.Id)) + .As>() + .ToListAsync(GetCancellationToken(cancellationToken)); - public virtual async Task RemoveAllMembersAsync(OrganizationUnit organizationUnit, CancellationToken cancellationToken = default) + foreach (var user in users) { - var userQueryable = await GetMongoQueryableAsync(cancellationToken); - var dbContext = await GetDbContextAsync(cancellationToken); - var users = await userQueryable - .Where(u => u.OrganizationUnits.Any(uou => uou.OrganizationUnitId == organizationUnit.Id)) - .As>() - .ToListAsync(GetCancellationToken(cancellationToken)); - - foreach (var user in users) - { - user.RemoveOrganizationUnit(organizationUnit.Id); - await dbContext.Users.ReplaceOneAsync(u => u.Id == user.Id, user, cancellationToken: cancellationToken); - } + user.RemoveOrganizationUnit(organizationUnit.Id); + await dbContext.Users.ReplaceOneAsync(u => u.Id == user.Id, user, cancellationToken: cancellationToken); } + } - protected virtual async Task> CreateGetMembersFilteredQueryAsync( - OrganizationUnit organizationUnit, - string filter = null, - CancellationToken cancellationToken = default) - { - return (await GetMongoQueryableAsync(cancellationToken)) - .Where(u => u.OrganizationUnits.Any(uou => uou.OrganizationUnitId == organizationUnit.Id)) - .WhereIf>( - !filter.IsNullOrWhiteSpace(), - u => - u.UserName.Contains(filter) || - u.Email.Contains(filter) || - (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) - ); - } + protected virtual async Task> CreateGetMembersFilteredQueryAsync( + OrganizationUnit organizationUnit, + string filter = null, + CancellationToken cancellationToken = default) + { + return (await GetMongoQueryableAsync(cancellationToken)) + .Where(u => u.OrganizationUnits.Any(uou => uou.OrganizationUnitId == organizationUnit.Id)) + .WhereIf>( + !filter.IsNullOrWhiteSpace(), + u => + u.UserName.Contains(filter) || + u.Email.Contains(filter) || + (u.PhoneNumber != null && u.PhoneNumber.Contains(filter)) + ); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Web/AbpIdentityWebAutoMapperProfile.cs b/modules/identity/src/Volo.Abp.Identity.Web/AbpIdentityWebAutoMapperProfile.cs index f7dfc69099..0fe498e49a 100644 --- a/modules/identity/src/Volo.Abp.Identity.Web/AbpIdentityWebAutoMapperProfile.cs +++ b/modules/identity/src/Volo.Abp.Identity.Web/AbpIdentityWebAutoMapperProfile.cs @@ -4,51 +4,50 @@ using Volo.Abp.Identity.Web.Pages.Identity.Roles; using CreateUserModalModel = Volo.Abp.Identity.Web.Pages.Identity.Users.CreateModalModel; using EditUserModalModel = Volo.Abp.Identity.Web.Pages.Identity.Users.EditModalModel; -namespace Volo.Abp.Identity.Web +namespace Volo.Abp.Identity.Web; + +public class AbpIdentityWebAutoMapperProfile : Profile { - public class AbpIdentityWebAutoMapperProfile : Profile + public AbpIdentityWebAutoMapperProfile() + { + CreateUserMappings(); + CreateRoleMappings(); + } + + protected virtual void CreateUserMappings() { - public AbpIdentityWebAutoMapperProfile() - { - CreateUserMappings(); - CreateRoleMappings(); - } - - protected virtual void CreateUserMappings() - { - //List - CreateMap() - .Ignore(x => x.Password); - - //CreateModal - CreateMap() - .MapExtraProperties() - .ForMember(dest => dest.RoleNames, opt => opt.Ignore()); - - CreateMap() - .ForMember(dest => dest.IsAssigned, opt => opt.Ignore()); - - //EditModal - CreateMap() - .MapExtraProperties() - .ForMember(dest => dest.RoleNames, opt => opt.Ignore()); - - CreateMap() - .ForMember(dest => dest.IsAssigned, opt => opt.Ignore()); - } - - protected virtual void CreateRoleMappings() - { - //List - CreateMap(); - - //CreateModal - CreateMap() - .MapExtraProperties(); - - //EditModal - CreateMap() - .MapExtraProperties(); - } + //List + CreateMap() + .Ignore(x => x.Password); + + //CreateModal + CreateMap() + .MapExtraProperties() + .ForMember(dest => dest.RoleNames, opt => opt.Ignore()); + + CreateMap() + .ForMember(dest => dest.IsAssigned, opt => opt.Ignore()); + + //EditModal + CreateMap() + .MapExtraProperties() + .ForMember(dest => dest.RoleNames, opt => opt.Ignore()); + + CreateMap() + .ForMember(dest => dest.IsAssigned, opt => opt.Ignore()); + } + + protected virtual void CreateRoleMappings() + { + //List + CreateMap(); + + //CreateModal + CreateMap() + .MapExtraProperties(); + + //EditModal + CreateMap() + .MapExtraProperties(); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Web/AbpIdentityWebModule.cs b/modules/identity/src/Volo.Abp.Identity.Web/AbpIdentityWebModule.cs index 0b0e15d447..ae3e8ebc72 100644 --- a/modules/identity/src/Volo.Abp.Identity.Web/AbpIdentityWebModule.cs +++ b/modules/identity/src/Volo.Abp.Identity.Web/AbpIdentityWebModule.cs @@ -16,112 +16,111 @@ using Volo.Abp.UI.Navigation; using Volo.Abp.VirtualFileSystem; using Volo.Abp.Threading; -namespace Volo.Abp.Identity.Web +namespace Volo.Abp.Identity.Web; + +[DependsOn(typeof(AbpIdentityApplicationContractsModule))] +[DependsOn(typeof(AbpAutoMapperModule))] +[DependsOn(typeof(AbpPermissionManagementWebModule))] +[DependsOn(typeof(AbpAspNetCoreMvcUiThemeSharedModule))] +public class AbpIdentityWebModule : AbpModule { - [DependsOn(typeof(AbpIdentityApplicationContractsModule))] - [DependsOn(typeof(AbpAutoMapperModule))] - [DependsOn(typeof(AbpPermissionManagementWebModule))] - [DependsOn(typeof(AbpAspNetCoreMvcUiThemeSharedModule))] - public class AbpIdentityWebModule : AbpModule - { - private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); + private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); - public override void PreConfigureServices(ServiceConfigurationContext context) + public override void PreConfigureServices(ServiceConfigurationContext context) + { + context.Services.PreConfigure(options => { - context.Services.PreConfigure(options => - { - options.AddAssemblyResource(typeof(IdentityResource), typeof(AbpIdentityWebModule).Assembly); - }); + options.AddAssemblyResource(typeof(IdentityResource), typeof(AbpIdentityWebModule).Assembly); + }); - PreConfigure(mvcBuilder => - { - mvcBuilder.AddApplicationPartIfNotExists(typeof(AbpIdentityWebModule).Assembly); - }); - } + PreConfigure(mvcBuilder => + { + mvcBuilder.AddApplicationPartIfNotExists(typeof(AbpIdentityWebModule).Assembly); + }); + } - public override void ConfigureServices(ServiceConfigurationContext context) + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => { - Configure(options => - { - options.MenuContributors.Add(new AbpIdentityWebMainMenuContributor()); - }); + options.MenuContributors.Add(new AbpIdentityWebMainMenuContributor()); + }); - Configure(options => - { - options.FileSets.AddEmbedded(); - }); + Configure(options => + { + options.FileSets.AddEmbedded(); + }); - context.Services.AddAutoMapperObjectMapper(); + context.Services.AddAutoMapperObjectMapper(); - Configure(options => - { - options.AddProfile(validate: true); - }); + Configure(options => + { + options.AddProfile(validate: true); + }); - Configure(options => - { - options.Conventions.AuthorizePage("/Identity/Users/Index", IdentityPermissions.Users.Default); - options.Conventions.AuthorizePage("/Identity/Users/CreateModal", IdentityPermissions.Users.Create); - options.Conventions.AuthorizePage("/Identity/Users/EditModal", IdentityPermissions.Users.Update); - options.Conventions.AuthorizePage("/Identity/Roles/Index", IdentityPermissions.Roles.Default); - options.Conventions.AuthorizePage("/Identity/Roles/CreateModal", IdentityPermissions.Roles.Create); - options.Conventions.AuthorizePage("/Identity/Roles/EditModal", IdentityPermissions.Roles.Update); - }); + Configure(options => + { + options.Conventions.AuthorizePage("/Identity/Users/Index", IdentityPermissions.Users.Default); + options.Conventions.AuthorizePage("/Identity/Users/CreateModal", IdentityPermissions.Users.Create); + options.Conventions.AuthorizePage("/Identity/Users/EditModal", IdentityPermissions.Users.Update); + options.Conventions.AuthorizePage("/Identity/Roles/Index", IdentityPermissions.Roles.Default); + options.Conventions.AuthorizePage("/Identity/Roles/CreateModal", IdentityPermissions.Roles.Create); + options.Conventions.AuthorizePage("/Identity/Roles/EditModal", IdentityPermissions.Roles.Update); + }); - Configure(options => - { - options.Configure( - toolbar => - { - toolbar.AddButton( - LocalizableString.Create("NewUser"), - icon: "plus", - name: "CreateUser", - requiredPolicyName: IdentityPermissions.Users.Create - ); - } - ); + Configure(options => + { + options.Configure( + toolbar => + { + toolbar.AddButton( + LocalizableString.Create("NewUser"), + icon: "plus", + name: "CreateUser", + requiredPolicyName: IdentityPermissions.Users.Create + ); + } + ); - options.Configure( - toolbar => - { - toolbar.AddButton( - LocalizableString.Create("NewRole"), - icon: "plus", - name: "CreateRole", - requiredPolicyName: IdentityPermissions.Roles.Create - ); - } - ); - }); + options.Configure( + toolbar => + { + toolbar.AddButton( + LocalizableString.Create("NewRole"), + icon: "plus", + name: "CreateRole", + requiredPolicyName: IdentityPermissions.Roles.Create + ); + } + ); + }); - Configure(options => - { - options.DisableModule(IdentityRemoteServiceConsts.ModuleName); - }); - } + Configure(options => + { + options.DisableModule(IdentityRemoteServiceConsts.ModuleName); + }); + } - public override void PostConfigureServices(ServiceConfigurationContext context) + public override void PostConfigureServices(ServiceConfigurationContext context) + { + OneTimeRunner.Run(() => { - OneTimeRunner.Run(() => - { - ModuleExtensionConfigurationHelper - .ApplyEntityConfigurationToUi( - IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.Role, - createFormTypes: new[] { typeof(Volo.Abp.Identity.Web.Pages.Identity.Roles.CreateModalModel.RoleInfoModel) }, - editFormTypes: new[] { typeof(Volo.Abp.Identity.Web.Pages.Identity.Roles.EditModalModel.RoleInfoModel) } - ); + ModuleExtensionConfigurationHelper + .ApplyEntityConfigurationToUi( + IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.Role, + createFormTypes: new[] { typeof(Volo.Abp.Identity.Web.Pages.Identity.Roles.CreateModalModel.RoleInfoModel) }, + editFormTypes: new[] { typeof(Volo.Abp.Identity.Web.Pages.Identity.Roles.EditModalModel.RoleInfoModel) } + ); - ModuleExtensionConfigurationHelper - .ApplyEntityConfigurationToUi( - IdentityModuleExtensionConsts.ModuleName, - IdentityModuleExtensionConsts.EntityNames.User, - createFormTypes: new[] { typeof(Volo.Abp.Identity.Web.Pages.Identity.Users.CreateModalModel.UserInfoViewModel) }, - editFormTypes: new[] { typeof(Volo.Abp.Identity.Web.Pages.Identity.Users.EditModalModel.UserInfoViewModel) } - ); - }); - } + ModuleExtensionConfigurationHelper + .ApplyEntityConfigurationToUi( + IdentityModuleExtensionConsts.ModuleName, + IdentityModuleExtensionConsts.EntityNames.User, + createFormTypes: new[] { typeof(Volo.Abp.Identity.Web.Pages.Identity.Users.CreateModalModel.UserInfoViewModel) }, + editFormTypes: new[] { typeof(Volo.Abp.Identity.Web.Pages.Identity.Users.EditModalModel.UserInfoViewModel) } + ); + }); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Web/Navigation/AbpIdentityWebMainMenuContributor.cs b/modules/identity/src/Volo.Abp.Identity.Web/Navigation/AbpIdentityWebMainMenuContributor.cs index a6355a794a..a191e6f250 100644 --- a/modules/identity/src/Volo.Abp.Identity.Web/Navigation/AbpIdentityWebMainMenuContributor.cs +++ b/modules/identity/src/Volo.Abp.Identity.Web/Navigation/AbpIdentityWebMainMenuContributor.cs @@ -6,26 +6,25 @@ using Volo.Abp.Identity.Localization; using Volo.Abp.UI.Navigation; using Volo.Abp.Authorization.Permissions; -namespace Volo.Abp.Identity.Web.Navigation +namespace Volo.Abp.Identity.Web.Navigation; + +public class AbpIdentityWebMainMenuContributor : IMenuContributor { - public class AbpIdentityWebMainMenuContributor : IMenuContributor + public virtual Task ConfigureMenuAsync(MenuConfigurationContext context) { - public virtual Task ConfigureMenuAsync(MenuConfigurationContext context) + if (context.Menu.Name != StandardMenus.Main) { - if (context.Menu.Name != StandardMenus.Main) - { - return Task.CompletedTask; - } + return Task.CompletedTask; + } - var l = context.GetLocalizer(); + var l = context.GetLocalizer(); - var identityMenuItem = new ApplicationMenuItem(IdentityMenuNames.GroupName, l["Menu:IdentityManagement"], icon: "fa fa-id-card-o"); - identityMenuItem.AddItem(new ApplicationMenuItem(IdentityMenuNames.Roles, l["Roles"], url: "~/Identity/Roles").RequirePermissions(IdentityPermissions.Roles.Default)); - identityMenuItem.AddItem(new ApplicationMenuItem(IdentityMenuNames.Users, l["Users"], url: "~/Identity/Users").RequirePermissions( IdentityPermissions.Users.Default)); + var identityMenuItem = new ApplicationMenuItem(IdentityMenuNames.GroupName, l["Menu:IdentityManagement"], icon: "fa fa-id-card-o"); + identityMenuItem.AddItem(new ApplicationMenuItem(IdentityMenuNames.Roles, l["Roles"], url: "~/Identity/Roles").RequirePermissions(IdentityPermissions.Roles.Default)); + identityMenuItem.AddItem(new ApplicationMenuItem(IdentityMenuNames.Users, l["Users"], url: "~/Identity/Users").RequirePermissions(IdentityPermissions.Users.Default)); - context.Menu.GetAdministration().AddItem(identityMenuItem); + context.Menu.GetAdministration().AddItem(identityMenuItem); - return Task.CompletedTask; - } + return Task.CompletedTask; } } diff --git a/modules/identity/src/Volo.Abp.Identity.Web/Navigation/IdentityMenuNames.cs b/modules/identity/src/Volo.Abp.Identity.Web/Navigation/IdentityMenuNames.cs index 61a503f457..70094f7490 100644 --- a/modules/identity/src/Volo.Abp.Identity.Web/Navigation/IdentityMenuNames.cs +++ b/modules/identity/src/Volo.Abp.Identity.Web/Navigation/IdentityMenuNames.cs @@ -1,10 +1,9 @@ -namespace Volo.Abp.Identity.Web.Navigation +namespace Volo.Abp.Identity.Web.Navigation; + +public class IdentityMenuNames { - public class IdentityMenuNames - { - public const string GroupName = "AbpIdentity"; + public const string GroupName = "AbpIdentity"; - public const string Roles = GroupName + ".Roles"; - public const string Users = GroupName + ".Users"; - } + public const string Roles = GroupName + ".Roles"; + public const string Users = GroupName + ".Users"; } diff --git a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/IdentityPageModel.cs b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/IdentityPageModel.cs index fab6685d07..679262fd31 100644 --- a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/IdentityPageModel.cs +++ b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/IdentityPageModel.cs @@ -1,12 +1,11 @@ using Volo.Abp.AspNetCore.Mvc.UI.RazorPages; -namespace Volo.Abp.Identity.Web.Pages.Identity +namespace Volo.Abp.Identity.Web.Pages.Identity; + +public abstract class IdentityPageModel : AbpPageModel { - public abstract class IdentityPageModel : AbpPageModel + protected IdentityPageModel() { - protected IdentityPageModel() - { - ObjectMapperContext = typeof(AbpIdentityWebModule); - } + ObjectMapperContext = typeof(AbpIdentityWebModule); } } diff --git a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/CreateModal.cshtml.cs b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/CreateModal.cshtml.cs index 79787da08b..80bc114967 100644 --- a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/CreateModal.cshtml.cs +++ b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/CreateModal.cshtml.cs @@ -4,49 +4,48 @@ using Microsoft.AspNetCore.Mvc; using Volo.Abp.ObjectExtending; using Volo.Abp.Validation; -namespace Volo.Abp.Identity.Web.Pages.Identity.Roles +namespace Volo.Abp.Identity.Web.Pages.Identity.Roles; + +public class CreateModalModel : IdentityPageModel { - public class CreateModalModel : IdentityPageModel + [BindProperty] + public RoleInfoModel Role { get; set; } + + protected IIdentityRoleAppService IdentityRoleAppService { get; } + + public CreateModalModel(IIdentityRoleAppService identityRoleAppService) { - [BindProperty] - public RoleInfoModel Role { get; set; } - - protected IIdentityRoleAppService IdentityRoleAppService { get; } - - public CreateModalModel(IIdentityRoleAppService identityRoleAppService) - { - IdentityRoleAppService = identityRoleAppService; - } - - public virtual Task OnGetAsync() - { - Role = new RoleInfoModel(); - - return Task.FromResult(Page()); - } - - public virtual async Task OnPostAsync() - { - ValidateModel(); - - var input = ObjectMapper.Map(Role); - await IdentityRoleAppService.CreateAsync(input); - - return NoContent(); - } - - public class RoleInfoModel : ExtensibleObject - { - [Required] - [DynamicStringLength(typeof(IdentityRoleConsts), nameof(IdentityRoleConsts.MaxNameLength))] - [Display(Name = "DisplayName:RoleName")] - public string Name { get; set; } - - [Display(Name = "DisplayName:IsDefault")] - public bool IsDefault { get; set; } - - [Display(Name = "DisplayName:IsPublic")] - public bool IsPublic { get; set; } - } + IdentityRoleAppService = identityRoleAppService; + } + + public virtual Task OnGetAsync() + { + Role = new RoleInfoModel(); + + return Task.FromResult(Page()); + } + + public virtual async Task OnPostAsync() + { + ValidateModel(); + + var input = ObjectMapper.Map(Role); + await IdentityRoleAppService.CreateAsync(input); + + return NoContent(); + } + + public class RoleInfoModel : ExtensibleObject + { + [Required] + [DynamicStringLength(typeof(IdentityRoleConsts), nameof(IdentityRoleConsts.MaxNameLength))] + [Display(Name = "DisplayName:RoleName")] + public string Name { get; set; } + + [Display(Name = "DisplayName:IsDefault")] + public bool IsDefault { get; set; } + + [Display(Name = "DisplayName:IsPublic")] + public bool IsPublic { get; set; } } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/EditModal.cshtml.cs b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/EditModal.cshtml.cs index 14236c1466..245b0daad6 100644 --- a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/EditModal.cshtml.cs +++ b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/EditModal.cshtml.cs @@ -6,57 +6,56 @@ using Volo.Abp.Domain.Entities; using Volo.Abp.ObjectExtending; using Volo.Abp.Validation; -namespace Volo.Abp.Identity.Web.Pages.Identity.Roles +namespace Volo.Abp.Identity.Web.Pages.Identity.Roles; + +public class EditModalModel : IdentityPageModel { - public class EditModalModel : IdentityPageModel - { - [BindProperty] - public RoleInfoModel Role { get; set; } + [BindProperty] + public RoleInfoModel Role { get; set; } - protected IIdentityRoleAppService IdentityRoleAppService { get; } + protected IIdentityRoleAppService IdentityRoleAppService { get; } - public EditModalModel(IIdentityRoleAppService identityRoleAppService) - { - IdentityRoleAppService = identityRoleAppService; - } + public EditModalModel(IIdentityRoleAppService identityRoleAppService) + { + IdentityRoleAppService = identityRoleAppService; + } - public virtual async Task OnGetAsync(Guid id) - { - Role = ObjectMapper.Map( - await IdentityRoleAppService.GetAsync(id) - ); - } + public virtual async Task OnGetAsync(Guid id) + { + Role = ObjectMapper.Map( + await IdentityRoleAppService.GetAsync(id) + ); + } - public virtual async Task OnPostAsync() - { - ValidateModel(); + public virtual async Task OnPostAsync() + { + ValidateModel(); - var input = ObjectMapper.Map(Role); - await IdentityRoleAppService.UpdateAsync(Role.Id, input); + var input = ObjectMapper.Map(Role); + await IdentityRoleAppService.UpdateAsync(Role.Id, input); - return NoContent(); - } + return NoContent(); + } - public class RoleInfoModel : ExtensibleObject, IHasConcurrencyStamp - { - [HiddenInput] - public Guid Id { get; set; } + public class RoleInfoModel : ExtensibleObject, IHasConcurrencyStamp + { + [HiddenInput] + public Guid Id { get; set; } - [HiddenInput] - public string ConcurrencyStamp { get; set; } + [HiddenInput] + public string ConcurrencyStamp { get; set; } - [Required] - [DynamicStringLength(typeof(IdentityRoleConsts), nameof(IdentityRoleConsts.MaxNameLength))] - [Display(Name = "DisplayName:RoleName")] - public string Name { get; set; } + [Required] + [DynamicStringLength(typeof(IdentityRoleConsts), nameof(IdentityRoleConsts.MaxNameLength))] + [Display(Name = "DisplayName:RoleName")] + public string Name { get; set; } - [Display(Name = "DisplayName:IsDefault")] - public bool IsDefault { get; set; } + [Display(Name = "DisplayName:IsDefault")] + public bool IsDefault { get; set; } - public bool IsStatic { get; set; } + public bool IsStatic { get; set; } - [Display(Name = "DisplayName:IsPublic")] - public bool IsPublic { get; set; } - } + [Display(Name = "DisplayName:IsPublic")] + public bool IsPublic { get; set; } } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/Index.cshtml.cs b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/Index.cshtml.cs index 254c1785bc..1dfb9f73c2 100644 --- a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/Index.cshtml.cs +++ b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Roles/Index.cshtml.cs @@ -1,18 +1,17 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; -namespace Volo.Abp.Identity.Web.Pages.Identity.Roles +namespace Volo.Abp.Identity.Web.Pages.Identity.Roles; + +public class IndexModel : IdentityPageModel { - public class IndexModel : IdentityPageModel + public virtual Task OnGetAsync() { - public virtual Task OnGetAsync() - { - return Task.FromResult(Page()); - } + return Task.FromResult(Page()); + } - public virtual Task OnPostAsync() - { - return Task.FromResult(Page()); - } + public virtual Task OnPostAsync() + { + return Task.FromResult(Page()); } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/CreateModal.cshtml.cs b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/CreateModal.cshtml.cs index c239ac2e48..ff67986f1b 100644 --- a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/CreateModal.cshtml.cs +++ b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/CreateModal.cshtml.cs @@ -8,91 +8,90 @@ using Volo.Abp.Application.Dtos; using Volo.Abp.ObjectExtending; using Volo.Abp.Validation; -namespace Volo.Abp.Identity.Web.Pages.Identity.Users -{ - public class CreateModalModel : IdentityPageModel - { - [BindProperty] - public UserInfoViewModel UserInfo { get; set; } +namespace Volo.Abp.Identity.Web.Pages.Identity.Users; - [BindProperty] - public AssignedRoleViewModel[] Roles { get; set; } +public class CreateModalModel : IdentityPageModel +{ + [BindProperty] + public UserInfoViewModel UserInfo { get; set; } - protected IIdentityUserAppService IdentityUserAppService { get; } + [BindProperty] + public AssignedRoleViewModel[] Roles { get; set; } - public CreateModalModel(IIdentityUserAppService identityUserAppService) - { - IdentityUserAppService = identityUserAppService; - } + protected IIdentityUserAppService IdentityUserAppService { get; } - public virtual async Task OnGetAsync() - { - UserInfo = new UserInfoViewModel(); + public CreateModalModel(IIdentityUserAppService identityUserAppService) + { + IdentityUserAppService = identityUserAppService; + } - var roleDtoList = (await IdentityUserAppService.GetAssignableRolesAsync()).Items; + public virtual async Task OnGetAsync() + { + UserInfo = new UserInfoViewModel(); - Roles = ObjectMapper.Map, AssignedRoleViewModel[]>(roleDtoList); + var roleDtoList = (await IdentityUserAppService.GetAssignableRolesAsync()).Items; - foreach (var role in Roles) - { - role.IsAssigned = role.IsDefault; - } + Roles = ObjectMapper.Map, AssignedRoleViewModel[]>(roleDtoList); - return Page(); + foreach (var role in Roles) + { + role.IsAssigned = role.IsDefault; } - public virtual async Task OnPostAsync() - { - ValidateModel(); + return Page(); + } - var input = ObjectMapper.Map(UserInfo); - input.RoleNames = Roles.Where(r => r.IsAssigned).Select(r => r.Name).ToArray(); + public virtual async Task OnPostAsync() + { + ValidateModel(); - await IdentityUserAppService.CreateAsync(input); + var input = ObjectMapper.Map(UserInfo); + input.RoleNames = Roles.Where(r => r.IsAssigned).Select(r => r.Name).ToArray(); - return NoContent(); - } + await IdentityUserAppService.CreateAsync(input); - public class UserInfoViewModel : ExtensibleObject - { - [Required] - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxUserNameLength))] - public string UserName { get; set; } + return NoContent(); + } - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxNameLength))] - public string Name { get; set; } + public class UserInfoViewModel : ExtensibleObject + { + [Required] + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxUserNameLength))] + public string UserName { get; set; } - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxSurnameLength))] - public string Surname { get; set; } + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxNameLength))] + public string Name { get; set; } - [Required] - [DataType(DataType.Password)] - [DisableAuditing] - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))] - public string Password { get; set; } + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxSurnameLength))] + public string Surname { get; set; } - [Required] - [EmailAddress] - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxEmailLength))] - public string Email { get; set; } + [Required] + [DataType(DataType.Password)] + [DisableAuditing] + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))] + public string Password { get; set; } - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPhoneNumberLength))] - public string PhoneNumber { get; set; } + [Required] + [EmailAddress] + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxEmailLength))] + public string Email { get; set; } - public bool IsActive { get; set; } = true; + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPhoneNumberLength))] + public string PhoneNumber { get; set; } - public bool LockoutEnabled { get; set; } = true; - } + public bool IsActive { get; set; } = true; - public class AssignedRoleViewModel - { - [Required] - [HiddenInput] - public string Name { get; set; } + public bool LockoutEnabled { get; set; } = true; + } - public bool IsAssigned { get; set; } + public class AssignedRoleViewModel + { + [Required] + [HiddenInput] + public string Name { get; set; } - public bool IsDefault { get; set; } - } + public bool IsAssigned { get; set; } + + public bool IsDefault { get; set; } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/EditModal.cshtml.cs b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/EditModal.cshtml.cs index 25affb88a3..2b15d794ac 100644 --- a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/EditModal.cshtml.cs +++ b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/EditModal.cshtml.cs @@ -10,95 +10,94 @@ using Volo.Abp.Domain.Entities; using Volo.Abp.ObjectExtending; using Volo.Abp.Validation; -namespace Volo.Abp.Identity.Web.Pages.Identity.Users +namespace Volo.Abp.Identity.Web.Pages.Identity.Users; + +public class EditModalModel : IdentityPageModel { - public class EditModalModel : IdentityPageModel - { - [BindProperty] - public UserInfoViewModel UserInfo { get; set; } + [BindProperty] + public UserInfoViewModel UserInfo { get; set; } - [BindProperty] - public AssignedRoleViewModel[] Roles { get; set; } + [BindProperty] + public AssignedRoleViewModel[] Roles { get; set; } - protected IIdentityUserAppService IdentityUserAppService { get; } + protected IIdentityUserAppService IdentityUserAppService { get; } - public EditModalModel(IIdentityUserAppService identityUserAppService) - { - IdentityUserAppService = identityUserAppService; - } + public EditModalModel(IIdentityUserAppService identityUserAppService) + { + IdentityUserAppService = identityUserAppService; + } - public virtual async Task OnGetAsync(Guid id) - { - UserInfo = ObjectMapper.Map(await IdentityUserAppService.GetAsync(id)); + public virtual async Task OnGetAsync(Guid id) + { + UserInfo = ObjectMapper.Map(await IdentityUserAppService.GetAsync(id)); - Roles = ObjectMapper.Map, AssignedRoleViewModel[]>((await IdentityUserAppService.GetAssignableRolesAsync()).Items); + Roles = ObjectMapper.Map, AssignedRoleViewModel[]>((await IdentityUserAppService.GetAssignableRolesAsync()).Items); - var userRoleNames = (await IdentityUserAppService.GetRolesAsync(UserInfo.Id)).Items.Select(r => r.Name).ToList(); - foreach (var role in Roles) + var userRoleNames = (await IdentityUserAppService.GetRolesAsync(UserInfo.Id)).Items.Select(r => r.Name).ToList(); + foreach (var role in Roles) + { + if (userRoleNames.Contains(role.Name)) { - if (userRoleNames.Contains(role.Name)) - { - role.IsAssigned = true; - } + role.IsAssigned = true; } - - return Page(); } - public virtual async Task OnPostAsync() - { - ValidateModel(); + return Page(); + } - var input = ObjectMapper.Map(UserInfo); - input.RoleNames = Roles.Where(r => r.IsAssigned).Select(r => r.Name).ToArray(); - await IdentityUserAppService.UpdateAsync(UserInfo.Id, input); + public virtual async Task OnPostAsync() + { + ValidateModel(); - return NoContent(); - } + var input = ObjectMapper.Map(UserInfo); + input.RoleNames = Roles.Where(r => r.IsAssigned).Select(r => r.Name).ToArray(); + await IdentityUserAppService.UpdateAsync(UserInfo.Id, input); - public class UserInfoViewModel : ExtensibleObject, IHasConcurrencyStamp - { - [HiddenInput] - public Guid Id { get; set; } + return NoContent(); + } - [HiddenInput] - public string ConcurrencyStamp { get; set; } + public class UserInfoViewModel : ExtensibleObject, IHasConcurrencyStamp + { + [HiddenInput] + public Guid Id { get; set; } - [Required] - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxUserNameLength))] - public string UserName { get; set; } + [HiddenInput] + public string ConcurrencyStamp { get; set; } - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxNameLength))] - public string Name { get; set; } + [Required] + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxUserNameLength))] + public string UserName { get; set; } - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxSurnameLength))] - public string Surname { get; set; } + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxNameLength))] + public string Name { get; set; } - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))] - [DataType(DataType.Password)] - [DisableAuditing] - public string Password { get; set; } + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxSurnameLength))] + public string Surname { get; set; } - [Required] - [EmailAddress] - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxEmailLength))] - public string Email { get; set; } + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))] + [DataType(DataType.Password)] + [DisableAuditing] + public string Password { get; set; } - [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPhoneNumberLength))] - public string PhoneNumber { get; set; } + [Required] + [EmailAddress] + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxEmailLength))] + public string Email { get; set; } - public bool IsActive { get; set; } + [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPhoneNumberLength))] + public string PhoneNumber { get; set; } - public bool LockoutEnabled { get; set; } - } + public bool IsActive { get; set; } - public class AssignedRoleViewModel - { - [Required] - [HiddenInput] - public string Name { get; set; } + public bool LockoutEnabled { get; set; } + } - public bool IsAssigned { get; set; } - } + public class AssignedRoleViewModel + { + [Required] + [HiddenInput] + public string Name { get; set; } + + public bool IsAssigned { get; set; } } } diff --git a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/Index.cshtml.cs b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/Index.cshtml.cs index b6ff2c0e94..f7962e04dd 100644 --- a/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/Index.cshtml.cs +++ b/modules/identity/src/Volo.Abp.Identity.Web/Pages/Identity/Users/Index.cshtml.cs @@ -1,18 +1,17 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; -namespace Volo.Abp.Identity.Web.Pages.Identity.Users +namespace Volo.Abp.Identity.Web.Pages.Identity.Users; + +public class IndexModel : IdentityPageModel { - public class IndexModel : IdentityPageModel + public virtual Task OnGetAsync() { - public virtual Task OnGetAsync() - { - return Task.FromResult(Page()); - } + return Task.FromResult(Page()); + } - public virtual Task OnPostAsync() - { - return Task.FromResult(Page()); - } + public virtual Task OnPostAsync() + { + return Task.FromResult(Page()); } } diff --git a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/AbpPermissionManagementDomainIdentityModule.cs b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/AbpPermissionManagementDomainIdentityModule.cs index a70657d6da..924fbf4a36 100644 --- a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/AbpPermissionManagementDomainIdentityModule.cs +++ b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/AbpPermissionManagementDomainIdentityModule.cs @@ -2,25 +2,24 @@ using Volo.Abp.Identity; using Volo.Abp.Modularity; -namespace Volo.Abp.PermissionManagement.Identity +namespace Volo.Abp.PermissionManagement.Identity; + +[DependsOn( + typeof(AbpIdentityDomainSharedModule), + typeof(AbpPermissionManagementDomainModule) + )] +public class AbpPermissionManagementDomainIdentityModule : AbpModule { - [DependsOn( - typeof(AbpIdentityDomainSharedModule), - typeof(AbpPermissionManagementDomainModule) - )] - public class AbpPermissionManagementDomainIdentityModule : AbpModule + public override void ConfigureServices(ServiceConfigurationContext context) { - public override void ConfigureServices(ServiceConfigurationContext context) + Configure(options => { - Configure(options => - { - options.ManagementProviders.Add(); - options.ManagementProviders.Add(); + options.ManagementProviders.Add(); + options.ManagementProviders.Add(); //TODO: Can we prevent duplication of permission names without breaking the design and making the system complicated options.ProviderPolicies[UserPermissionValueProvider.ProviderName] = "AbpIdentity.Users.ManagePermissions"; - options.ProviderPolicies[RolePermissionValueProvider.ProviderName] = "AbpIdentity.Roles.ManagePermissions"; - }); - } + options.ProviderPolicies[RolePermissionValueProvider.ProviderName] = "AbpIdentity.Roles.ManagePermissions"; + }); } } diff --git a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RoleDeletedEventHandler.cs b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RoleDeletedEventHandler.cs index 4a25abea50..38a9578c9d 100644 --- a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RoleDeletedEventHandler.cs +++ b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RoleDeletedEventHandler.cs @@ -6,22 +6,21 @@ using Volo.Abp.EventBus; using Volo.Abp.EventBus.Distributed; using Volo.Abp.Identity; -namespace Volo.Abp.PermissionManagement.Identity +namespace Volo.Abp.PermissionManagement.Identity; + +public class RoleDeletedEventHandler : + IDistributedEventHandler>, + ITransientDependency { - public class RoleDeletedEventHandler : - IDistributedEventHandler>, - ITransientDependency - { - protected IPermissionManager PermissionManager { get; } + protected IPermissionManager PermissionManager { get; } - public RoleDeletedEventHandler(IPermissionManager permissionManager) - { - PermissionManager = permissionManager; - } + public RoleDeletedEventHandler(IPermissionManager permissionManager) + { + PermissionManager = permissionManager; + } - public async Task HandleEventAsync(EntityDeletedEto eventData) - { - await PermissionManager.DeleteAsync(RolePermissionValueProvider.ProviderName, eventData.Entity.Name); - } + public async Task HandleEventAsync(EntityDeletedEto eventData) + { + await PermissionManager.DeleteAsync(RolePermissionValueProvider.ProviderName, eventData.Entity.Name); } } diff --git a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RolePermissionManagementProvider.cs b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RolePermissionManagementProvider.cs index 7b2fb4344e..a4a6cd60f2 100644 --- a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RolePermissionManagementProvider.cs +++ b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RolePermissionManagementProvider.cs @@ -7,72 +7,71 @@ using Volo.Abp.Guids; using Volo.Abp.Identity; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.PermissionManagement.Identity +namespace Volo.Abp.PermissionManagement.Identity; + +public class RolePermissionManagementProvider : PermissionManagementProvider { - public class RolePermissionManagementProvider : PermissionManagementProvider + public override string Name => RolePermissionValueProvider.ProviderName; + + protected IUserRoleFinder UserRoleFinder { get; } + + public RolePermissionManagementProvider( + IPermissionGrantRepository permissionGrantRepository, + IGuidGenerator guidGenerator, + ICurrentTenant currentTenant, + IUserRoleFinder userRoleFinder) + : base( + permissionGrantRepository, + guidGenerator, + currentTenant) { - public override string Name => RolePermissionValueProvider.ProviderName; + UserRoleFinder = userRoleFinder; + } - protected IUserRoleFinder UserRoleFinder { get; } + public override async Task CheckAsync(string name, string providerName, string providerKey) + { + var multipleGrantInfo = await CheckAsync(new[] { name }, providerName, providerKey); - public RolePermissionManagementProvider( - IPermissionGrantRepository permissionGrantRepository, - IGuidGenerator guidGenerator, - ICurrentTenant currentTenant, - IUserRoleFinder userRoleFinder) - : base( - permissionGrantRepository, - guidGenerator, - currentTenant) - { - UserRoleFinder = userRoleFinder; - } + return multipleGrantInfo.Result.Values.First(); + } + + public override async Task CheckAsync(string[] names, string providerName, string providerKey) + { + var multiplePermissionValueProviderGrantInfo = new MultiplePermissionValueProviderGrantInfo(names); + var permissionGrants = new List(); - public override async Task CheckAsync(string name, string providerName, string providerKey) + if (providerName == Name) { - var multipleGrantInfo = await CheckAsync(new[] {name}, providerName, providerKey); + permissionGrants.AddRange(await PermissionGrantRepository.GetListAsync(names, providerName, providerKey)); - return multipleGrantInfo.Result.Values.First(); } - public override async Task CheckAsync(string[] names, string providerName, string providerKey) + if (providerName == UserPermissionValueProvider.ProviderName) { - var multiplePermissionValueProviderGrantInfo = new MultiplePermissionValueProviderGrantInfo(names); - var permissionGrants = new List(); + var userId = Guid.Parse(providerKey); + var roleNames = await UserRoleFinder.GetRolesAsync(userId); - if (providerName == Name) + foreach (var roleName in roleNames) { - permissionGrants.AddRange(await PermissionGrantRepository.GetListAsync(names, providerName, providerKey)); - - } - - if (providerName == UserPermissionValueProvider.ProviderName) - { - var userId = Guid.Parse(providerKey); - var roleNames = await UserRoleFinder.GetRolesAsync(userId); - - foreach (var roleName in roleNames) - { - permissionGrants.AddRange(await PermissionGrantRepository.GetListAsync(names, Name, roleName)); - } + permissionGrants.AddRange(await PermissionGrantRepository.GetListAsync(names, Name, roleName)); } + } - permissionGrants = permissionGrants.Distinct().ToList(); - if (!permissionGrants.Any()) - { - return multiplePermissionValueProviderGrantInfo; - } + permissionGrants = permissionGrants.Distinct().ToList(); + if (!permissionGrants.Any()) + { + return multiplePermissionValueProviderGrantInfo; + } - foreach (var permissionName in names) + foreach (var permissionName in names) + { + var permissionGrant = permissionGrants.FirstOrDefault(x => x.Name == permissionName); + if (permissionGrant != null) { - var permissionGrant = permissionGrants.FirstOrDefault(x => x.Name == permissionName); - if (permissionGrant != null) - { - multiplePermissionValueProviderGrantInfo.Result[permissionName] = new PermissionValueProviderGrantInfo(true, permissionGrant.ProviderKey); - } + multiplePermissionValueProviderGrantInfo.Result[permissionName] = new PermissionValueProviderGrantInfo(true, permissionGrant.ProviderKey); } - - return multiplePermissionValueProviderGrantInfo; } + + return multiplePermissionValueProviderGrantInfo; } } diff --git a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RoleUpdateEventHandler.cs b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RoleUpdateEventHandler.cs index d2d25ec3e8..ca865063e0 100644 --- a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RoleUpdateEventHandler.cs +++ b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/RoleUpdateEventHandler.cs @@ -4,30 +4,29 @@ using Volo.Abp.DependencyInjection; using Volo.Abp.EventBus.Distributed; using Volo.Abp.Identity; -namespace Volo.Abp.PermissionManagement.Identity +namespace Volo.Abp.PermissionManagement.Identity; + +public class RoleUpdateEventHandler : + IDistributedEventHandler, + ITransientDependency { - public class RoleUpdateEventHandler : - IDistributedEventHandler, - ITransientDependency + protected IPermissionManager PermissionManager { get; } + protected IPermissionGrantRepository PermissionGrantRepository { get; } + + public RoleUpdateEventHandler( + IPermissionManager permissionManager, + IPermissionGrantRepository permissionGrantRepository) { - protected IPermissionManager PermissionManager { get; } - protected IPermissionGrantRepository PermissionGrantRepository { get; } - - public RoleUpdateEventHandler( - IPermissionManager permissionManager, - IPermissionGrantRepository permissionGrantRepository) - { - PermissionManager = permissionManager; - PermissionGrantRepository = permissionGrantRepository; - } + PermissionManager = permissionManager; + PermissionGrantRepository = permissionGrantRepository; + } - public async Task HandleEventAsync(IdentityRoleNameChangedEto eventData) + public async Task HandleEventAsync(IdentityRoleNameChangedEto eventData) + { + var permissionGrantsInRole = await PermissionGrantRepository.GetListAsync(RolePermissionValueProvider.ProviderName, eventData.OldName); + foreach (var permissionGrant in permissionGrantsInRole) { - var permissionGrantsInRole = await PermissionGrantRepository.GetListAsync(RolePermissionValueProvider.ProviderName, eventData.OldName); - foreach (var permissionGrant in permissionGrantsInRole) - { - await PermissionManager.UpdateProviderKeyAsync(permissionGrant, eventData.Name); - } + await PermissionManager.UpdateProviderKeyAsync(permissionGrant, eventData.Name); } } } diff --git a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/UserPermissionManagementProvider.cs b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/UserPermissionManagementProvider.cs index db9a0cbadd..92e5313202 100644 --- a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/UserPermissionManagementProvider.cs +++ b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/Identity/UserPermissionManagementProvider.cs @@ -2,22 +2,21 @@ using Volo.Abp.Guids; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.PermissionManagement.Identity +namespace Volo.Abp.PermissionManagement.Identity; + +public class UserPermissionManagementProvider : PermissionManagementProvider { - public class UserPermissionManagementProvider : PermissionManagementProvider - { - public override string Name => UserPermissionValueProvider.ProviderName; + public override string Name => UserPermissionValueProvider.ProviderName; - public UserPermissionManagementProvider( - IPermissionGrantRepository permissionGrantRepository, - IGuidGenerator guidGenerator, - ICurrentTenant currentTenant) - : base( - permissionGrantRepository, - guidGenerator, - currentTenant) - { + public UserPermissionManagementProvider( + IPermissionGrantRepository permissionGrantRepository, + IGuidGenerator guidGenerator, + ICurrentTenant currentTenant) + : base( + permissionGrantRepository, + guidGenerator, + currentTenant) + { - } } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/RolePermissionManagerExtensions.cs b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/RolePermissionManagerExtensions.cs index 1ad565350c..4fe1650e4f 100644 --- a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/RolePermissionManagerExtensions.cs +++ b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/RolePermissionManagerExtensions.cs @@ -3,29 +3,28 @@ using System.Threading.Tasks; using JetBrains.Annotations; using Volo.Abp.Authorization.Permissions; -namespace Volo.Abp.PermissionManagement +namespace Volo.Abp.PermissionManagement; + +public static class RolePermissionManagerExtensions { - public static class RolePermissionManagerExtensions + public static Task GetForRoleAsync([NotNull] this IPermissionManager permissionManager, string roleName, string permissionName) { - public static Task GetForRoleAsync([NotNull] this IPermissionManager permissionManager, string roleName, string permissionName) - { - Check.NotNull(permissionManager, nameof(permissionManager)); + Check.NotNull(permissionManager, nameof(permissionManager)); - return permissionManager.GetAsync(permissionName, RolePermissionValueProvider.ProviderName, roleName); - } + return permissionManager.GetAsync(permissionName, RolePermissionValueProvider.ProviderName, roleName); + } - public static Task> GetAllForRoleAsync([NotNull] this IPermissionManager permissionManager, string roleName) - { - Check.NotNull(permissionManager, nameof(permissionManager)); + public static Task> GetAllForRoleAsync([NotNull] this IPermissionManager permissionManager, string roleName) + { + Check.NotNull(permissionManager, nameof(permissionManager)); - return permissionManager.GetAllAsync(RolePermissionValueProvider.ProviderName, roleName); - } + return permissionManager.GetAllAsync(RolePermissionValueProvider.ProviderName, roleName); + } - public static Task SetForRoleAsync([NotNull] this IPermissionManager permissionManager, string roleName, [NotNull] string permissionName, bool isGranted) - { - Check.NotNull(permissionManager, nameof(permissionManager)); + public static Task SetForRoleAsync([NotNull] this IPermissionManager permissionManager, string roleName, [NotNull] string permissionName, bool isGranted) + { + Check.NotNull(permissionManager, nameof(permissionManager)); - return permissionManager.SetAsync(permissionName, RolePermissionValueProvider.ProviderName, roleName, isGranted); - } + return permissionManager.SetAsync(permissionName, RolePermissionValueProvider.ProviderName, roleName, isGranted); } -} \ No newline at end of file +} diff --git a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/UserPermissionManagerExtensions.cs b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/UserPermissionManagerExtensions.cs index 1456081a4a..ae1c52a7b5 100644 --- a/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/UserPermissionManagerExtensions.cs +++ b/modules/identity/src/Volo.Abp.PermissionManagement.Domain.Identity/Volo/Abp/PermissionManagement/UserPermissionManagerExtensions.cs @@ -4,22 +4,21 @@ using System.Threading.Tasks; using JetBrains.Annotations; using Volo.Abp.Authorization.Permissions; -namespace Volo.Abp.PermissionManagement +namespace Volo.Abp.PermissionManagement; + +public static class UserPermissionManagerExtensions { - public static class UserPermissionManagerExtensions + public static Task> GetAllForUserAsync([NotNull] this IPermissionManager permissionManager, Guid userId) { - public static Task> GetAllForUserAsync([NotNull] this IPermissionManager permissionManager, Guid userId) - { - Check.NotNull(permissionManager, nameof(permissionManager)); + Check.NotNull(permissionManager, nameof(permissionManager)); - return permissionManager.GetAllAsync(UserPermissionValueProvider.ProviderName, userId.ToString()); - } + return permissionManager.GetAllAsync(UserPermissionValueProvider.ProviderName, userId.ToString()); + } - public static Task SetForUserAsync([NotNull] this IPermissionManager permissionManager, Guid userId, [NotNull] string name, bool isGranted) - { - Check.NotNull(permissionManager, nameof(permissionManager)); + public static Task SetForUserAsync([NotNull] this IPermissionManager permissionManager, Guid userId, [NotNull] string name, bool isGranted) + { + Check.NotNull(permissionManager, nameof(permissionManager)); - return permissionManager.SetAsync(name, UserPermissionValueProvider.ProviderName, userId.ToString(), isGranted); - } + return permissionManager.SetAsync(name, UserPermissionValueProvider.ProviderName, userId.ToString(), isGranted); } } diff --git a/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/AbpIdentityApplicationTestBase.cs b/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/AbpIdentityApplicationTestBase.cs index dd3594e81d..3cc610ad7c 100644 --- a/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/AbpIdentityApplicationTestBase.cs +++ b/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/AbpIdentityApplicationTestBase.cs @@ -1,7 +1,6 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class AbpIdentityApplicationTestBase : AbpIdentityExtendedTestBase { - public class AbpIdentityApplicationTestBase : AbpIdentityExtendedTestBase - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/AbpIdentityApplicationTestModule.cs b/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/AbpIdentityApplicationTestModule.cs index 9a57646264..fe5e8f9033 100644 --- a/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/AbpIdentityApplicationTestModule.cs +++ b/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/AbpIdentityApplicationTestModule.cs @@ -1,13 +1,12 @@ using Volo.Abp.Modularity; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[DependsOn( + typeof(AbpIdentityApplicationModule), + typeof(AbpIdentityDomainTestModule) + )] +public class AbpIdentityApplicationTestModule : AbpModule { - [DependsOn( - typeof(AbpIdentityApplicationModule), - typeof(AbpIdentityDomainTestModule) - )] - public class AbpIdentityApplicationTestModule : AbpModule - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityRoleAppService_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityRoleAppService_Tests.cs index ce2ba8b511..d9f6d17523 100644 --- a/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityRoleAppService_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityRoleAppService_Tests.cs @@ -5,134 +5,133 @@ using Xunit; using Shouldly; using Volo.Abp.Application.Dtos; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityRoleAppService_Tests : AbpIdentityApplicationTestBase { - public class IdentityRoleAppService_Tests : AbpIdentityApplicationTestBase + private readonly IIdentityRoleAppService _roleAppService; + private readonly IIdentityRoleRepository _roleRepository; + + public IdentityRoleAppService_Tests() { - private readonly IIdentityRoleAppService _roleAppService; - private readonly IIdentityRoleRepository _roleRepository; + _roleAppService = GetRequiredService(); + _roleRepository = GetRequiredService(); + } - public IdentityRoleAppService_Tests() - { - _roleAppService = GetRequiredService(); - _roleRepository = GetRequiredService(); - } + [Fact] + public async Task GetAsync() + { + //Arrange - [Fact] - public async Task GetAsync() - { - //Arrange + var moderator = await GetRoleAsync("moderator"); - var moderator = await GetRoleAsync("moderator"); + //Act - //Act + var result = await _roleAppService.GetAsync(moderator.Id); - var result = await _roleAppService.GetAsync(moderator.Id); + //Assert - //Assert + result.Id.ShouldBe(moderator.Id); + } - result.Id.ShouldBe(moderator.Id); - } + [Fact] + public async Task GetAllListAsync() + { + //Act - [Fact] - public async Task GetAllListAsync() - { - //Act + var result = await _roleAppService.GetAllListAsync(); - var result = await _roleAppService.GetAllListAsync(); + //Assert - //Assert + result.Items.Count.ShouldBeGreaterThan(0); + } - result.Items.Count.ShouldBeGreaterThan(0); - } + [Fact] + public async Task GetListAsync() + { + //Act - [Fact] - public async Task GetListAsync() - { - //Act + var result = await _roleAppService.GetListAsync(new GetIdentityRolesInput()); - var result = await _roleAppService.GetListAsync(new GetIdentityRolesInput()); + //Assert - //Assert + result.Items.Count.ShouldBeGreaterThan(0); + } - result.Items.Count.ShouldBeGreaterThan(0); - } + [Fact] + public async Task CreateAsync() + { + //Arrange - [Fact] - public async Task CreateAsync() + var input = new IdentityRoleCreateDto { - //Arrange + Name = Guid.NewGuid().ToString("N").Left(8) + }; - var input = new IdentityRoleCreateDto - { - Name = Guid.NewGuid().ToString("N").Left(8) - }; + //Act - //Act + var result = await _roleAppService.CreateAsync(input); - var result = await _roleAppService.CreateAsync(input); + //Assert - //Assert + result.Id.ShouldNotBe(Guid.Empty); + result.Name.ShouldBe(input.Name); - result.Id.ShouldNotBe(Guid.Empty); - result.Name.ShouldBe(input.Name); - - var role = await _roleRepository.GetAsync(result.Id); - role.Name.ShouldBe(input.Name); - } + var role = await _roleRepository.GetAsync(result.Id); + role.Name.ShouldBe(input.Name); + } - [Fact] - public async Task UpdateAsync() - { - //Arrange + [Fact] + public async Task UpdateAsync() + { + //Arrange - var moderator = await GetRoleAsync("moderator"); + var moderator = await GetRoleAsync("moderator"); - var input = new IdentityRoleUpdateDto - { - Name = Guid.NewGuid().ToString("N").Left(8), - ConcurrencyStamp = moderator.ConcurrencyStamp, - IsDefault = moderator.IsDefault, - IsPublic = moderator.IsPublic - }; + var input = new IdentityRoleUpdateDto + { + Name = Guid.NewGuid().ToString("N").Left(8), + ConcurrencyStamp = moderator.ConcurrencyStamp, + IsDefault = moderator.IsDefault, + IsPublic = moderator.IsPublic + }; - //Act + //Act - var result = await _roleAppService.UpdateAsync(moderator.Id, input); + var result = await _roleAppService.UpdateAsync(moderator.Id, input); - //Assert + //Assert - result.Id.ShouldBe(moderator.Id); - result.Name.ShouldBe(input.Name); + result.Id.ShouldBe(moderator.Id); + result.Name.ShouldBe(input.Name); - var updatedRole = await _roleRepository.GetAsync(moderator.Id); - updatedRole.Name.ShouldBe(input.Name); - } + var updatedRole = await _roleRepository.GetAsync(moderator.Id); + updatedRole.Name.ShouldBe(input.Name); + } - [Fact] - public async Task DeleteAsync() - { - //Arrange + [Fact] + public async Task DeleteAsync() + { + //Arrange - var moderator = await GetRoleAsync("moderator"); + var moderator = await GetRoleAsync("moderator"); - //Act + //Act - await _roleAppService.DeleteAsync(moderator.Id); + await _roleAppService.DeleteAsync(moderator.Id); - //Assert + //Assert - (await FindRoleAsync("moderator")).ShouldBeNull(); - } + (await FindRoleAsync("moderator")).ShouldBeNull(); + } - private async Task GetRoleAsync(string roleName) - { - return (await _roleRepository.GetListAsync()).First(u => u.Name == roleName); - } + private async Task GetRoleAsync(string roleName) + { + return (await _roleRepository.GetListAsync()).First(u => u.Name == roleName); + } - private async Task FindRoleAsync(string roleName) - { - return (await _roleRepository.GetListAsync()).FirstOrDefault(u => u.Name == roleName); - } + private async Task FindRoleAsync(string roleName) + { + return (await _roleRepository.GetListAsync()).FirstOrDefault(u => u.Name == roleName); } } diff --git a/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserAppService_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserAppService_Tests.cs index 278ef10ced..591cefba3c 100644 --- a/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserAppService_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserAppService_Tests.cs @@ -4,229 +4,228 @@ using Shouldly; using Volo.Abp.Data; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUserAppService_Tests : AbpIdentityApplicationTestBase { - public class IdentityUserAppService_Tests : AbpIdentityApplicationTestBase + private readonly IIdentityUserAppService _userAppService; + private readonly IIdentityUserRepository _userRepository; + private readonly IdentityTestData _testData; + + public IdentityUserAppService_Tests() { - private readonly IIdentityUserAppService _userAppService; - private readonly IIdentityUserRepository _userRepository; - private readonly IdentityTestData _testData; + _userAppService = GetRequiredService(); + _userRepository = GetRequiredService(); + _testData = GetRequiredService(); + } - public IdentityUserAppService_Tests() - { - _userAppService = GetRequiredService(); - _userRepository = GetRequiredService(); - _testData = GetRequiredService(); - } + [Fact] + public async Task GetAsync() + { + //Arrange - [Fact] - public async Task GetAsync() - { - //Arrange + var johnNash = GetUser("john.nash"); - var johnNash = GetUser("john.nash"); + //Act - //Act + var result = await _userAppService.GetAsync(johnNash.Id); - var result = await _userAppService.GetAsync(johnNash.Id); + //Assert - //Assert + result.Id.ShouldBe(johnNash.Id); + result.UserName.ShouldBe(johnNash.UserName); + result.Email.ShouldBe(johnNash.Email); + result.LockoutEnabled.ShouldBe(johnNash.LockoutEnabled); + result.PhoneNumber.ShouldBe(johnNash.PhoneNumber); + } - result.Id.ShouldBe(johnNash.Id); - result.UserName.ShouldBe(johnNash.UserName); - result.Email.ShouldBe(johnNash.Email); - result.LockoutEnabled.ShouldBe(johnNash.LockoutEnabled); - result.PhoneNumber.ShouldBe(johnNash.PhoneNumber); - } + [Fact] + public async Task GetListAsync() + { + //Act - [Fact] - public async Task GetListAsync() - { - //Act + var result = await _userAppService.GetListAsync(new GetIdentityUsersInput()); - var result = await _userAppService.GetListAsync(new GetIdentityUsersInput()); + //Assert - //Assert + result.TotalCount.ShouldBeGreaterThan(0); + result.Items.Count.ShouldBeGreaterThan(0); + } - result.TotalCount.ShouldBeGreaterThan(0); - result.Items.Count.ShouldBeGreaterThan(0); - } + [Fact] + public async Task CreateAsync() + { + //Arrange - [Fact] - public async Task CreateAsync() + var input = new IdentityUserCreateDto { - //Arrange + UserName = Guid.NewGuid().ToString(), + Email = CreateRandomEmail(), + LockoutEnabled = true, + PhoneNumber = CreateRandomPhoneNumber(), + Password = "123qwE4r*", + RoleNames = new[] { "moderator" } + }; + + //Act + + var result = await _userAppService.CreateAsync(input); + + //Assert + + result.Id.ShouldNotBe(Guid.Empty); + result.UserName.ShouldBe(input.UserName); + result.Email.ShouldBe(input.Email); + result.LockoutEnabled.ShouldBe(input.LockoutEnabled); + result.PhoneNumber.ShouldBe(input.PhoneNumber); + + var user = await _userRepository.GetAsync(result.Id); + user.Id.ShouldBe(result.Id); + user.UserName.ShouldBe(input.UserName); + user.Email.ShouldBe(input.Email); + user.LockoutEnabled.ShouldBe(input.LockoutEnabled); + user.PhoneNumber.ShouldBe(input.PhoneNumber); + } - var input = new IdentityUserCreateDto - { - UserName = Guid.NewGuid().ToString(), - Email = CreateRandomEmail(), - LockoutEnabled = true, - PhoneNumber = CreateRandomPhoneNumber(), - Password = "123qwE4r*", - RoleNames = new[] { "moderator" } - }; - - //Act - - var result = await _userAppService.CreateAsync(input); - - //Assert - - result.Id.ShouldNotBe(Guid.Empty); - result.UserName.ShouldBe(input.UserName); - result.Email.ShouldBe(input.Email); - result.LockoutEnabled.ShouldBe(input.LockoutEnabled); - result.PhoneNumber.ShouldBe(input.PhoneNumber); - - var user = await _userRepository.GetAsync(result.Id); - user.Id.ShouldBe(result.Id); - user.UserName.ShouldBe(input.UserName); - user.Email.ShouldBe(input.Email); - user.LockoutEnabled.ShouldBe(input.LockoutEnabled); - user.PhoneNumber.ShouldBe(input.PhoneNumber); - } - - [Fact] - public async Task UpdateAsync() - { - //Arrange + [Fact] + public async Task UpdateAsync() + { + //Arrange - var johnNash = GetUser("john.nash"); + var johnNash = GetUser("john.nash"); - var input = new IdentityUserUpdateDto - { - UserName = johnNash.UserName, - LockoutEnabled = true, - PhoneNumber = CreateRandomPhoneNumber(), - Password = "123qwe4R*", - Email = CreateRandomEmail(), - RoleNames = new[] { "admin", "moderator" }, - ConcurrencyStamp = johnNash.ConcurrencyStamp, - Surname = johnNash.Surname, - Name = johnNash.Name - }; - - //Act - - var result = await _userAppService.UpdateAsync(johnNash.Id, input); - - //Assert - - result.Id.ShouldBe(johnNash.Id); - result.UserName.ShouldBe(input.UserName); - result.Email.ShouldBe(input.Email); - result.LockoutEnabled.ShouldBe(input.LockoutEnabled); - result.PhoneNumber.ShouldBe(input.PhoneNumber); - - var user = await _userRepository.GetAsync(result.Id); - user.Id.ShouldBe(result.Id); - user.UserName.ShouldBe(input.UserName); - user.Email.ShouldBe(input.Email); - user.LockoutEnabled.ShouldBe(input.LockoutEnabled); - user.PhoneNumber.ShouldBe(input.PhoneNumber); - user.Roles.Count.ShouldBe(2); - } - - - [Fact] - public async Task UpdateAsync_Concurrency_Exception() + var input = new IdentityUserUpdateDto { - //Get user - var johnNash = await _userAppService.GetAsync(_testData.UserJohnId); + UserName = johnNash.UserName, + LockoutEnabled = true, + PhoneNumber = CreateRandomPhoneNumber(), + Password = "123qwe4R*", + Email = CreateRandomEmail(), + RoleNames = new[] { "admin", "moderator" }, + ConcurrencyStamp = johnNash.ConcurrencyStamp, + Surname = johnNash.Surname, + Name = johnNash.Name + }; + + //Act + + var result = await _userAppService.UpdateAsync(johnNash.Id, input); + + //Assert + + result.Id.ShouldBe(johnNash.Id); + result.UserName.ShouldBe(input.UserName); + result.Email.ShouldBe(input.Email); + result.LockoutEnabled.ShouldBe(input.LockoutEnabled); + result.PhoneNumber.ShouldBe(input.PhoneNumber); + + var user = await _userRepository.GetAsync(result.Id); + user.Id.ShouldBe(result.Id); + user.UserName.ShouldBe(input.UserName); + user.Email.ShouldBe(input.Email); + user.LockoutEnabled.ShouldBe(input.LockoutEnabled); + user.PhoneNumber.ShouldBe(input.PhoneNumber); + user.Roles.Count.ShouldBe(2); + } - //Act - var input = new IdentityUserUpdateDto - { - Name = "John-updated", - Surname = "Nash-updated", - UserName = johnNash.UserName, - LockoutEnabled = true, - PhoneNumber = CreateRandomPhoneNumber(), - Email = CreateRandomEmail(), - RoleNames = new[] { "admin", "moderator" }, - ConcurrencyStamp = johnNash.ConcurrencyStamp - }; - - await _userAppService.UpdateAsync(johnNash.Id, input); + [Fact] + public async Task UpdateAsync_Concurrency_Exception() + { + //Get user + var johnNash = await _userAppService.GetAsync(_testData.UserJohnId); - //Second update with same input will throw exception because the entity has been modified - (await Assert.ThrowsAsync(async () => - { - await _userAppService.UpdateAsync(johnNash.Id, input); - })).Message.ShouldContain("Optimistic concurrency failure"); - } + //Act - [Fact] - public async Task DeleteAsync() + var input = new IdentityUserUpdateDto + { + Name = "John-updated", + Surname = "Nash-updated", + UserName = johnNash.UserName, + LockoutEnabled = true, + PhoneNumber = CreateRandomPhoneNumber(), + Email = CreateRandomEmail(), + RoleNames = new[] { "admin", "moderator" }, + ConcurrencyStamp = johnNash.ConcurrencyStamp + }; + + await _userAppService.UpdateAsync(johnNash.Id, input); + + //Second update with same input will throw exception because the entity has been modified + (await Assert.ThrowsAsync(async () => { - //Arrange + await _userAppService.UpdateAsync(johnNash.Id, input); + })).Message.ShouldContain("Optimistic concurrency failure"); + } - var johnNash = GetUser("john.nash"); + [Fact] + public async Task DeleteAsync() + { + //Arrange - //Act + var johnNash = GetUser("john.nash"); - await _userAppService.DeleteAsync(johnNash.Id); + //Act - //Assert + await _userAppService.DeleteAsync(johnNash.Id); - FindUser("john.nash").ShouldBeNull(); - } + //Assert - [Fact] - public async Task GetRolesAsync() - { - //Arrange + FindUser("john.nash").ShouldBeNull(); + } - var johnNash = GetUser("john.nash"); + [Fact] + public async Task GetRolesAsync() + { + //Arrange - //Act + var johnNash = GetUser("john.nash"); - var result = await _userAppService.GetRolesAsync(johnNash.Id); + //Act - //Assert + var result = await _userAppService.GetRolesAsync(johnNash.Id); - result.Items.Count.ShouldBe(3); - result.Items.ShouldContain(r => r.Name == "moderator"); - result.Items.ShouldContain(r => r.Name == "supporter"); - result.Items.ShouldContain(r => r.Name == "manager"); - } + //Assert - [Fact] - public async Task UpdateRolesAsync() - { - //Arrange + result.Items.Count.ShouldBe(3); + result.Items.ShouldContain(r => r.Name == "moderator"); + result.Items.ShouldContain(r => r.Name == "supporter"); + result.Items.ShouldContain(r => r.Name == "manager"); + } - var johnNash = GetUser("john.nash"); + [Fact] + public async Task UpdateRolesAsync() + { + //Arrange - //Act + var johnNash = GetUser("john.nash"); - await _userAppService.UpdateRolesAsync( - johnNash.Id, - new IdentityUserUpdateRolesDto - { - RoleNames = new[] { "admin", "moderator" } - } - ); + //Act - //Assert + await _userAppService.UpdateRolesAsync( + johnNash.Id, + new IdentityUserUpdateRolesDto + { + RoleNames = new[] { "admin", "moderator" } + } + ); - var roleNames = await _userRepository.GetRoleNamesAsync(johnNash.Id); - roleNames.Count.ShouldBe(3); - roleNames.ShouldContain("admin"); - roleNames.ShouldContain("moderator"); - roleNames.ShouldContain("manager"); - } + //Assert - private static string CreateRandomEmail() - { - return Guid.NewGuid().ToString("N").Left(16) + "@abp.io"; - } + var roleNames = await _userRepository.GetRoleNamesAsync(johnNash.Id); + roleNames.Count.ShouldBe(3); + roleNames.ShouldContain("admin"); + roleNames.ShouldContain("moderator"); + roleNames.ShouldContain("manager"); + } - private static string CreateRandomPhoneNumber() - { - return RandomHelper.GetRandom(10000000, 100000000).ToString(); - } + private static string CreateRandomEmail() + { + return Guid.NewGuid().ToString("N").Left(16) + "@abp.io"; + } + + private static string CreateRandomPhoneNumber() + { + return RandomHelper.GetRandom(10000000, 100000000).ToString(); } } diff --git a/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserLookupAppService_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserLookupAppService_Tests.cs index fc5a18cbd3..e774b0e440 100644 --- a/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserLookupAppService_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserLookupAppService_Tests.cs @@ -4,84 +4,83 @@ using Microsoft.AspNetCore.Identity; using Shouldly; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUserLookupAppService_Tests : AbpIdentityApplicationTestBase { - public class IdentityUserLookupAppService_Tests : AbpIdentityApplicationTestBase - { - private readonly IIdentityUserLookupAppService _identityUserLookupAppService; - private readonly IIdentityUserRepository _identityUserRepository; - private readonly ILookupNormalizer _lookupNormalizer; + private readonly IIdentityUserLookupAppService _identityUserLookupAppService; + private readonly IIdentityUserRepository _identityUserRepository; + private readonly ILookupNormalizer _lookupNormalizer; - public IdentityUserLookupAppService_Tests() - { - _identityUserLookupAppService = GetRequiredService(); - _identityUserRepository = GetRequiredService(); - _lookupNormalizer = GetRequiredService(); - } + public IdentityUserLookupAppService_Tests() + { + _identityUserLookupAppService = GetRequiredService(); + _identityUserRepository = GetRequiredService(); + _lookupNormalizer = GetRequiredService(); + } - [Fact] - public async Task FindByIdAsync() - { - var user = await _identityUserRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task FindByIdAsync() + { + var user = await _identityUserRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserLookupAppService.FindByIdAsync(user.Id)).UserName.ShouldBe(user.UserName); - } + (await _identityUserLookupAppService.FindByIdAsync(user.Id)).UserName.ShouldBe(user.UserName); + } - [Fact] - public async Task FindById_NotExist_Should_Return_Null() - { - var user = await _identityUserLookupAppService.FindByIdAsync(Guid.NewGuid()); - user.ShouldBeNull(); - } + [Fact] + public async Task FindById_NotExist_Should_Return_Null() + { + var user = await _identityUserLookupAppService.FindByIdAsync(Guid.NewGuid()); + user.ShouldBeNull(); + } - [Fact] - public async Task FindByUserNameAsync() - { - var user = await _identityUserRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task FindByUserNameAsync() + { + var user = await _identityUserRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserLookupAppService.FindByUserNameAsync(user.UserName)).UserName.ShouldBe(user.UserName); - } + (await _identityUserLookupAppService.FindByUserNameAsync(user.UserName)).UserName.ShouldBe(user.UserName); + } - [Fact] - public async Task FindByUserName_NotExist_Should_Return_Null() - { - var user = await _identityUserLookupAppService.FindByUserNameAsync(Guid.NewGuid().ToString()); - user.ShouldBeNull(); - } + [Fact] + public async Task FindByUserName_NotExist_Should_Return_Null() + { + var user = await _identityUserLookupAppService.FindByUserNameAsync(Guid.NewGuid().ToString()); + user.ShouldBeNull(); + } - [Fact] - public async Task Search_Without_Filter_And_Sorting() - { - var result = await _identityUserLookupAppService.SearchAsync(new UserLookupSearchInputDto()); - result.Items.Count.ShouldBeGreaterThanOrEqualTo(3); - result.Items.ShouldContain(u => u.UserName == "john.nash"); - } + [Fact] + public async Task Search_Without_Filter_And_Sorting() + { + var result = await _identityUserLookupAppService.SearchAsync(new UserLookupSearchInputDto()); + result.Items.Count.ShouldBeGreaterThanOrEqualTo(3); + result.Items.ShouldContain(u => u.UserName == "john.nash"); + } - [Fact] - public async Task Search_With_Filter() - { - var result = await _identityUserLookupAppService.SearchAsync( - new UserLookupSearchInputDto - { - Filter = "a" - } - ); + [Fact] + public async Task Search_With_Filter() + { + var result = await _identityUserLookupAppService.SearchAsync( + new UserLookupSearchInputDto + { + Filter = "a" + } + ); - result.Items.Count.ShouldBeGreaterThanOrEqualTo(2); - result.Items.ShouldContain(u => u.UserName == "john.nash"); - result.Items.ShouldContain(u => u.UserName == "david"); + result.Items.Count.ShouldBeGreaterThanOrEqualTo(2); + result.Items.ShouldContain(u => u.UserName == "john.nash"); + result.Items.ShouldContain(u => u.UserName == "david"); - result = await _identityUserLookupAppService.SearchAsync( - new UserLookupSearchInputDto - { - Filter = "neo" - } - ); + result = await _identityUserLookupAppService.SearchAsync( + new UserLookupSearchInputDto + { + Filter = "neo" + } + ); - result.Items.Count.ShouldBeGreaterThanOrEqualTo(1); - result.Items.ShouldContain(u => u.UserName == "neo"); - } + result.Items.Count.ShouldBeGreaterThanOrEqualTo(1); + result.Items.ShouldContain(u => u.UserName == "neo"); } } diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestBase.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestBase.cs index c9e11f49b3..5d438c4d05 100644 --- a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestBase.cs +++ b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestBase.cs @@ -4,21 +4,20 @@ using System.Threading.Tasks; using Shouldly; using Volo.Abp.AspNetCore.TestBase; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public abstract class AbpIdentityAspNetCoreTestBase : AbpAspNetCoreIntegratedTestBase { - public abstract class AbpIdentityAspNetCoreTestBase : AbpAspNetCoreIntegratedTestBase + protected virtual async Task GetResponseAsStringAsync(string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK) { - protected virtual async Task GetResponseAsStringAsync(string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK) - { - var response = await GetResponseAsync(url, expectedStatusCode); - return await response.Content.ReadAsStringAsync(); - } + var response = await GetResponseAsync(url, expectedStatusCode); + return await response.Content.ReadAsStringAsync(); + } - protected virtual async Task GetResponseAsync(string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK) - { - var response = await Client.GetAsync(url); - response.StatusCode.ShouldBe(expectedStatusCode); - return response; - } + protected virtual async Task GetResponseAsync(string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK) + { + var response = await Client.GetAsync(url); + response.StatusCode.ShouldBe(expectedStatusCode); + return response; } } diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestModule.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestModule.cs index c3c035a208..45b3756b42 100644 --- a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestModule.cs +++ b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestModule.cs @@ -5,41 +5,40 @@ using Volo.Abp.AspNetCore.Mvc; using Volo.Abp.AspNetCore.TestBase; using Volo.Abp.Modularity; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +[DependsOn( + typeof(AbpIdentityAspNetCoreModule), + typeof(AbpIdentityDomainTestModule), + typeof(AbpAspNetCoreTestBaseModule), + typeof(AbpAspNetCoreMvcModule) +)] +public class AbpIdentityAspNetCoreTestModule : AbpModule { - [DependsOn( - typeof(AbpIdentityAspNetCoreModule), - typeof(AbpIdentityDomainTestModule), - typeof(AbpAspNetCoreTestBaseModule), - typeof(AbpAspNetCoreMvcModule) - )] - public class AbpIdentityAspNetCoreTestModule : AbpModule + public override void PreConfigureServices(ServiceConfigurationContext context) { - public override void PreConfigureServices(ServiceConfigurationContext context) + context.Services.PreConfigure(builder => { - context.Services.PreConfigure(builder => - { - builder.PartManager.ApplicationParts.Add(new AssemblyPart(typeof(AbpIdentityAspNetCoreTestModule).Assembly)); - }); - } + builder.PartManager.ApplicationParts.Add(new AssemblyPart(typeof(AbpIdentityAspNetCoreTestModule).Assembly)); + }); + } - public override void ConfigureServices(ServiceConfigurationContext context) + public override void ConfigureServices(ServiceConfigurationContext context) + { + Configure(options => { - Configure(options => - { - options.ExternalLoginProviders.Add(FakeExternalLoginProvider.Name); - }); - } + options.ExternalLoginProviders.Add(FakeExternalLoginProvider.Name); + }); + } - public override void OnApplicationInitialization(ApplicationInitializationContext context) - { - var app = context.GetApplicationBuilder(); - var env = context.GetEnvironment(); + public override void OnApplicationInitialization(ApplicationInitializationContext context) + { + var app = context.GetApplicationBuilder(); + var env = context.GetEnvironment(); - app.UseRouting(); - app.UseAuthentication(); - app.UseAuthorization(); - app.UseConfiguredEndpoints(); - } + app.UseRouting(); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseConfiguredEndpoints(); } } diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestStartup.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestStartup.cs index d495323c98..97131b8857 100644 --- a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestStartup.cs +++ b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreTestStartup.cs @@ -2,18 +2,17 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public class AbpIdentityAspNetCoreTestStartup { - public class AbpIdentityAspNetCoreTestStartup + public void ConfigureServices(IServiceCollection services) { - public void ConfigureServices(IServiceCollection services) - { - services.AddApplication(); - } + services.AddApplication(); + } - public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) - { - app.InitializeApplication(); - } + public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) + { + app.InitializeApplication(); } } diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpSignInManager_Tests.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpSignInManager_Tests.cs index b1b3368e5b..7aa540f420 100644 --- a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpSignInManager_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/AbpSignInManager_Tests.cs @@ -5,45 +5,44 @@ using Microsoft.AspNetCore.Identity; using Shouldly; using Xunit; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public class AbpSignInManager_Tests : AbpIdentityAspNetCoreTestBase { - public class AbpSignInManager_Tests : AbpIdentityAspNetCoreTestBase + [Fact] + public void Should_Resolve_AbpSignInManager() + { + var signInManager = GetRequiredService>(); + signInManager.ShouldBeOfType(); + } + + [Fact] + public async Task Should_SignIn_With_Correct_Credentials() { - [Fact] - public void Should_Resolve_AbpSignInManager() - { - var signInManager = GetRequiredService>(); - signInManager.ShouldBeOfType(); - } - - [Fact] - public async Task Should_SignIn_With_Correct_Credentials() - { - var result = await GetResponseAsStringAsync( - "api/signin-test/password?userName=admin&password=1q2w3E*" - ); - - result.ShouldBe("Succeeded"); - } - - [Fact] - public async Task Should_Not_SignIn_With_Wrong_Credentials() - { - var result = await GetResponseAsStringAsync( - "api/signin-test/password?userName=admin&password=WRONG_PASSWORD" - ); - - result.ShouldBe("Failed"); - } - - [Fact] - public async Task Should_Not_SignIn_If_User_Not_Active() - { - var result = await GetResponseAsStringAsync( - "api/signin-test/password?userName=bob&password=1q2w3E*" - ); - - result.ShouldBe("NotAllowed"); - } + var result = await GetResponseAsStringAsync( + "api/signin-test/password?userName=admin&password=1q2w3E*" + ); + + result.ShouldBe("Succeeded"); + } + + [Fact] + public async Task Should_Not_SignIn_With_Wrong_Credentials() + { + var result = await GetResponseAsStringAsync( + "api/signin-test/password?userName=admin&password=WRONG_PASSWORD" + ); + + result.ShouldBe("Failed"); + } + + [Fact] + public async Task Should_Not_SignIn_If_User_Not_Active() + { + var result = await GetResponseAsStringAsync( + "api/signin-test/password?userName=bob&password=1q2w3E*" + ); + + result.ShouldBe("NotAllowed"); } } diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/ExternalLoginProvider_Tests.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/ExternalLoginProvider_Tests.cs index c8d9f37c27..96f526da3e 100644 --- a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/ExternalLoginProvider_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/ExternalLoginProvider_Tests.cs @@ -3,54 +3,53 @@ using System.Threading.Tasks; using Shouldly; using Xunit; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public class ExternalLoginProvider_Tests : AbpIdentityAspNetCoreTestBase { - public class ExternalLoginProvider_Tests : AbpIdentityAspNetCoreTestBase + [Fact] + public async Task Should_SignIn_With_ExternalLoginProvider() { - [Fact] - public async Task Should_SignIn_With_ExternalLoginProvider() - { - // User does not exists yet - (await GetRequiredService().FindByNameAsync("ext_user")).ShouldBeNull(); - - // Try to login - - var result = await GetResponseAsStringAsync( - "api/signin-test/password?userName=ext_user&password=abc" - ); + // User does not exists yet + (await GetRequiredService().FindByNameAsync("ext_user")).ShouldBeNull(); - result.ShouldBe("Succeeded"); + // Try to login - // User should be created now + var result = await GetResponseAsStringAsync( + "api/signin-test/password?userName=ext_user&password=abc" + ); - await CheckUserAsync(); + result.ShouldBe("Succeeded"); - // Re-login + // User should be created now - result = await GetResponseAsStringAsync( - "api/signin-test/password?userName=ext_user&password=abc" - ); + await CheckUserAsync(); - result.ShouldBe("Succeeded"); + // Re-login - await CheckUserAsync(); - } + result = await GetResponseAsStringAsync( + "api/signin-test/password?userName=ext_user&password=abc" + ); - private async Task CheckUserAsync() - { - var userRepository = GetRequiredService(); + result.ShouldBe("Succeeded"); - var user = await userRepository.FindByNormalizedUserNameAsync("EXT_USER"); - user.Name.ShouldBe("Test Name"); - user.Surname.ShouldBe("Test Surname"); - user.EmailConfirmed.ShouldBeTrue(); - user.PhoneNumber.ShouldBe("123"); - user.PhoneNumberConfirmed.ShouldBeFalse(); - user.IsExternal.ShouldBeTrue(); + await CheckUserAsync(); + } - var logins = user.Logins.Where(l => l.LoginProvider == "Fake").ToList(); - logins.Count.ShouldBe(1); - logins[0].ProviderKey.ShouldBe("123"); - } + private async Task CheckUserAsync() + { + var userRepository = GetRequiredService(); + + var user = await userRepository.FindByNormalizedUserNameAsync("EXT_USER"); + user.Name.ShouldBe("Test Name"); + user.Surname.ShouldBe("Test Surname"); + user.EmailConfirmed.ShouldBeTrue(); + user.PhoneNumber.ShouldBe("123"); + user.PhoneNumberConfirmed.ShouldBeFalse(); + user.IsExternal.ShouldBeTrue(); + + var logins = user.Logins.Where(l => l.LoginProvider == "Fake").ToList(); + logins.Count.ShouldBe(1); + logins[0].ProviderKey.ShouldBe("123"); } } diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/FakeExternalLoginProvider.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/FakeExternalLoginProvider.cs index 66acc057a3..6583156c82 100644 --- a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/FakeExternalLoginProvider.cs +++ b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/FakeExternalLoginProvider.cs @@ -6,46 +6,46 @@ using Volo.Abp.DependencyInjection; using Volo.Abp.Guids; using Volo.Abp.MultiTenancy; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public class FakeExternalLoginProvider : ExternalLoginProviderBase, ITransientDependency { - public class FakeExternalLoginProvider : ExternalLoginProviderBase, ITransientDependency + public const string Name = "Fake"; + + public FakeExternalLoginProvider( + IGuidGenerator guidGenerator, + ICurrentTenant currentTenant, + IdentityUserManager userManager, + IIdentityUserRepository identityUserRepository, + IOptions identityOptions) + : base( + guidGenerator, + currentTenant, + userManager, + identityUserRepository, + identityOptions) { - public const string Name = "Fake"; - public FakeExternalLoginProvider( - IGuidGenerator guidGenerator, - ICurrentTenant currentTenant, - IdentityUserManager userManager, - IIdentityUserRepository identityUserRepository, - IOptions identityOptions) - : base( - guidGenerator, - currentTenant, - userManager, - identityUserRepository, - identityOptions) - { + } - } + public override Task TryAuthenticateAsync(string userName, string plainPassword) + { + return Task.FromResult( + userName == "ext_user" && plainPassword == "abc" + ); + } - public override Task TryAuthenticateAsync(string userName, string plainPassword) + protected override Task GetUserInfoAsync(string userName) + { + if (userName != "ext_user") { - return Task.FromResult( - userName == "ext_user" && plainPassword == "abc" - ); + throw new ArgumentException(); } - protected override Task GetUserInfoAsync(string userName) - { - if (userName != "ext_user") + return Task.FromResult( + new ExternalLoginUserInfo("ext_user@test.com") { - throw new ArgumentException(); - } - - return Task.FromResult( - new ExternalLoginUserInfo("ext_user@test.com") - { - Name = "Test Name", //optional, if the provider knows it + Name = "Test Name", //optional, if the provider knows it Surname = "Test Surname", //optional, if the provider knows it EmailConfirmed = true, //optional, if the provider knows it TwoFactorEnabled = false, //optional, if the provider knows it @@ -53,7 +53,6 @@ namespace Volo.Abp.Identity.AspNetCore PhoneNumberConfirmed = false, //optional, if the provider knows it ProviderKey = "123" //The id of the user on the provider side } - ); - } + ); } } diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/LinkUserTokenProvider_Tests.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/LinkUserTokenProvider_Tests.cs index 023537ebfd..75874feb33 100644 --- a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/LinkUserTokenProvider_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/LinkUserTokenProvider_Tests.cs @@ -4,43 +4,42 @@ using Microsoft.Extensions.Options; using Shouldly; using Xunit; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +public class LinkUserTokenProvider_Tests : AbpIdentityAspNetCoreTestBase { - public class LinkUserTokenProvider_Tests : AbpIdentityAspNetCoreTestBase - { - protected IIdentityUserRepository UserRepository { get; } - protected IIdentityLinkUserRepository IdentityLinkUserRepository { get; } - protected IdentityLinkUserManager IdentityLinkUserManager { get; } - protected IdentityTestData TestData { get; } + protected IIdentityUserRepository UserRepository { get; } + protected IIdentityLinkUserRepository IdentityLinkUserRepository { get; } + protected IdentityLinkUserManager IdentityLinkUserManager { get; } + protected IdentityTestData TestData { get; } - public LinkUserTokenProvider_Tests() - { - UserRepository = GetRequiredService(); - IdentityLinkUserRepository = GetRequiredService(); - IdentityLinkUserManager = GetRequiredService(); - TestData = GetRequiredService(); - } + public LinkUserTokenProvider_Tests() + { + UserRepository = GetRequiredService(); + IdentityLinkUserRepository = GetRequiredService(); + IdentityLinkUserManager = GetRequiredService(); + TestData = GetRequiredService(); + } - [Fact] - public void LinkUserTokenProvider_Should_Be_Register() - { - var identityOptions = GetRequiredService>().Value; + [Fact] + public void LinkUserTokenProvider_Should_Be_Register() + { + var identityOptions = GetRequiredService>().Value; - identityOptions.Tokens.ProviderMap.ShouldContain(x => - x.Key == LinkUserTokenProviderConsts.LinkUserTokenProviderName && - x.Value.ProviderType == typeof(LinkUserTokenProvider)); - } + identityOptions.Tokens.ProviderMap.ShouldContain(x => + x.Key == LinkUserTokenProviderConsts.LinkUserTokenProviderName && + x.Value.ProviderType == typeof(LinkUserTokenProvider)); + } - [Theory] - [InlineData("TestTokenPurpose1")] - [InlineData("TestTokenPurpose2")] - [InlineData("TestTokenPurpose3")] - public virtual async Task GenerateAndVerifyLinkTokenAsync(string tokenPurpose) - { - var john = await UserRepository.GetAsync(TestData.UserJohnId); - var token = await IdentityLinkUserManager.GenerateLinkTokenAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), tokenPurpose); - (await IdentityLinkUserManager.VerifyLinkTokenAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), token, tokenPurpose)).ShouldBeTrue(); - (await IdentityLinkUserManager.VerifyLinkTokenAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), "123123", tokenPurpose)).ShouldBeFalse(); - } + [Theory] + [InlineData("TestTokenPurpose1")] + [InlineData("TestTokenPurpose2")] + [InlineData("TestTokenPurpose3")] + public virtual async Task GenerateAndVerifyLinkTokenAsync(string tokenPurpose) + { + var john = await UserRepository.GetAsync(TestData.UserJohnId); + var token = await IdentityLinkUserManager.GenerateLinkTokenAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), tokenPurpose); + (await IdentityLinkUserManager.VerifyLinkTokenAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), token, tokenPurpose)).ShouldBeTrue(); + (await IdentityLinkUserManager.VerifyLinkTokenAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), "123123", tokenPurpose)).ShouldBeFalse(); } } diff --git a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/SignInTestController.cs b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/SignInTestController.cs index 77fb7918e2..bfc0c6d51e 100644 --- a/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/SignInTestController.cs +++ b/modules/identity/test/Volo.Abp.Identity.AspNetCore.Tests/Volo/Abp/Identity/AspNetCore/SignInTestController.cs @@ -3,29 +3,28 @@ using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Volo.Abp.AspNetCore.Mvc; -namespace Volo.Abp.Identity.AspNetCore +namespace Volo.Abp.Identity.AspNetCore; + +[Route("api/signin-test")] +public class SignInTestController : AbpController { - [Route("api/signin-test")] - public class SignInTestController : AbpController - { - private readonly SignInManager _signInManager; + private readonly SignInManager _signInManager; - public SignInTestController(SignInManager signInManager) - { - _signInManager = signInManager; - } + public SignInTestController(SignInManager signInManager) + { + _signInManager = signInManager; + } - [Route("password")] - public async Task PasswordLogin(string userName, string password) - { - var result = await _signInManager.PasswordSignInAsync( - userName, - password, - false, - false - ); + [Route("password")] + public async Task PasswordLogin(string userName, string password) + { + var result = await _signInManager.PasswordSignInAsync( + userName, + password, + false, + false + ); - return Content(result.ToString()); - } + return Content(result.ToString()); } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityDomainTestBase.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityDomainTestBase.cs index 95dddc2393..c2d48bb6c4 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityDomainTestBase.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityDomainTestBase.cs @@ -1,7 +1,6 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class AbpIdentityDomainTestBase : AbpIdentityExtendedTestBase { - public abstract class AbpIdentityDomainTestBase : AbpIdentityExtendedTestBase - { - - } + } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityDomainTestModule.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityDomainTestModule.cs index a6228a7cd6..a3ac1f0099 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityDomainTestModule.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityDomainTestModule.cs @@ -9,48 +9,47 @@ using Volo.Abp.PermissionManagement.Identity; using Volo.Abp.Threading; using Volo.Abp.VirtualFileSystem; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[DependsOn( + typeof(AbpIdentityEntityFrameworkCoreTestModule), + typeof(AbpIdentityTestBaseModule), + typeof(AbpPermissionManagementDomainIdentityModule) + )] +public class AbpIdentityDomainTestModule : AbpModule { - [DependsOn( - typeof(AbpIdentityEntityFrameworkCoreTestModule), - typeof(AbpIdentityTestBaseModule), - typeof(AbpPermissionManagementDomainIdentityModule) - )] - public class AbpIdentityDomainTestModule : AbpModule + public override void ConfigureServices(ServiceConfigurationContext context) { - public override void ConfigureServices(ServiceConfigurationContext context) + Configure(options => { - Configure(options => - { - options.AutoEventSelectors.Add(); - }); - - Configure(options => - { - options.FileSets.AddEmbedded(); - }); + options.AutoEventSelectors.Add(); + }); - Configure(options => - { - options.Resources - .Get() - .AddVirtualJson("/Volo/Abp/Identity/LocalizationExtensions"); - }); - } + Configure(options => + { + options.FileSets.AddEmbedded(); + }); - public override void OnApplicationInitialization(ApplicationInitializationContext context) + Configure(options => { - SeedTestData(context); - } + options.Resources + .Get() + .AddVirtualJson("/Volo/Abp/Identity/LocalizationExtensions"); + }); + } - private static void SeedTestData(ApplicationInitializationContext context) + public override void OnApplicationInitialization(ApplicationInitializationContext context) + { + SeedTestData(context); + } + + private static void SeedTestData(ApplicationInitializationContext context) + { + using (var scope = context.ServiceProvider.CreateScope()) { - using (var scope = context.ServiceProvider.CreateScope()) - { - AsyncHelper.RunSync(() => scope.ServiceProvider - .GetRequiredService() - .Build()); - } + AsyncHelper.RunSync(() => scope.ServiceProvider + .GetRequiredService() + .Build()); } } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityExtendedTestBase.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityExtendedTestBase.cs index 5385aaec49..19ff76bc92 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityExtendedTestBase.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityExtendedTestBase.cs @@ -6,50 +6,49 @@ using Volo.Abp.Identity.EntityFrameworkCore; using Volo.Abp.Modularity; using Volo.Abp.Uow; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class AbpIdentityExtendedTestBase : AbpIdentityTestBase + where TStartupModule : IAbpModule { - public abstract class AbpIdentityExtendedTestBase : AbpIdentityTestBase - where TStartupModule : IAbpModule + protected virtual IdentityUser GetUser(string userName) { - protected virtual IdentityUser GetUser(string userName) + var user = UsingDbContext(context => context.Users.FirstOrDefault(u => u.UserName == userName)); + if (user == null) { - var user = UsingDbContext(context => context.Users.FirstOrDefault(u => u.UserName == userName)); - if (user == null) - { - throw new EntityNotFoundException(); - } - - return user; + throw new EntityNotFoundException(); } - protected virtual IdentityUser FindUser(string userName) - { - return UsingDbContext(context => context.Users.FirstOrDefault(u => u.UserName == userName)); - } + return user; + } - protected virtual void UsingDbContext(Action action) + protected virtual IdentityUser FindUser(string userName) + { + return UsingDbContext(context => context.Users.FirstOrDefault(u => u.UserName == userName)); + } + + protected virtual void UsingDbContext(Action action) + { + using (var dbContext = GetRequiredService()) { - using (var dbContext = GetRequiredService()) - { - action.Invoke(dbContext); - } + action.Invoke(dbContext); } + } - protected virtual T UsingDbContext(Func action) + protected virtual T UsingDbContext(Func action) + { + using (var dbContext = GetRequiredService()) { - using (var dbContext = GetRequiredService()) - { - return action.Invoke(dbContext); - } + return action.Invoke(dbContext); } + } - protected virtual async Task UsingUowAsync(Func action) + protected virtual async Task UsingUowAsync(Func action) + { + using (var uow = GetRequiredService().Begin()) { - using (var uow = GetRequiredService().Begin()) - { - await action(); - await uow.CompleteAsync(); - } + await action(); + await uow.CompleteAsync(); } } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityResultException_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityResultException_Tests.cs index 306ea16c91..c2f7463a0b 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityResultException_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpIdentityResultException_Tests.cs @@ -3,43 +3,42 @@ using Shouldly; using Volo.Abp.Localization; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class AbpIdentityResultException_Tests : AbpIdentityDomainTestBase { - public class AbpIdentityResultException_Tests : AbpIdentityDomainTestBase + [Fact] + public void Should_Localize_Messages() { - [Fact] - public void Should_Localize_Messages() - { - var exception = new AbpIdentityResultException( - IdentityResult.Failed( - new IdentityError - { - Code = "PasswordTooShort", - Description = "Passwords must be at least 6 characters." - }, - new IdentityError - { - Code = "PasswordRequiresNonAlphanumeric", - Description = "Passwords must have at least one non alphanumeric character." - } - ) - ); + var exception = new AbpIdentityResultException( + IdentityResult.Failed( + new IdentityError + { + Code = "PasswordTooShort", + Description = "Passwords must be at least 6 characters." + }, + new IdentityError + { + Code = "PasswordRequiresNonAlphanumeric", + Description = "Passwords must have at least one non alphanumeric character." + } + ) + ); - using (CultureHelper.Use("tr")) - { - var localizeMessage = exception.LocalizeMessage(new LocalizationContext(ServiceProvider)); + using (CultureHelper.Use("tr")) + { + var localizeMessage = exception.LocalizeMessage(new LocalizationContext(ServiceProvider)); - localizeMessage.ShouldContain("Şifre en az 6 karakter uzunluğunda olmalı."); - localizeMessage.ShouldContain("Şifre en az bir sayı ya da harf olmayan karakter içermeli."); - } + localizeMessage.ShouldContain("Şifre en az 6 karakter uzunluğunda olmalı."); + localizeMessage.ShouldContain("Şifre en az bir sayı ya da harf olmayan karakter içermeli."); + } - using (CultureHelper.Use("en")) - { - var localizeMessage = exception.LocalizeMessage(new LocalizationContext(ServiceProvider)); + using (CultureHelper.Use("en")) + { + var localizeMessage = exception.LocalizeMessage(new LocalizationContext(ServiceProvider)); - localizeMessage.ShouldContain("Password length must be greater than 6 characters."); - localizeMessage.ShouldContain("Password must contain at least one non-alphanumeric character."); - } + localizeMessage.ShouldContain("Password length must be greater than 6 characters."); + localizeMessage.ShouldContain("Password must contain at least one non-alphanumeric character."); } } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpUserClaimsPrincipalFactory_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpUserClaimsPrincipalFactory_Tests.cs index 01704e108a..60a62cda1e 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpUserClaimsPrincipalFactory_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/AbpUserClaimsPrincipalFactory_Tests.cs @@ -7,58 +7,57 @@ using Volo.Abp.DependencyInjection; using Volo.Abp.Security.Claims; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class AbpUserClaimsPrincipalFactory_Tests : AbpIdentityDomainTestBase { - public class AbpUserClaimsPrincipalFactory_Tests : AbpIdentityDomainTestBase + private readonly IdentityUserManager _identityUserManager; + private readonly AbpUserClaimsPrincipalFactory _abpUserClaimsPrincipalFactory; + private readonly IdentityTestData _testData; + + public AbpUserClaimsPrincipalFactory_Tests() { - private readonly IdentityUserManager _identityUserManager; - private readonly AbpUserClaimsPrincipalFactory _abpUserClaimsPrincipalFactory; - private readonly IdentityTestData _testData; + _identityUserManager = GetRequiredService(); + _abpUserClaimsPrincipalFactory = GetRequiredService(); + _testData = GetRequiredService(); + } - public AbpUserClaimsPrincipalFactory_Tests() + [Fact] + public async Task Add_And_Replace_Claims_Test() + { + await UsingUowAsync(async () => { - _identityUserManager = GetRequiredService(); - _abpUserClaimsPrincipalFactory = GetRequiredService(); - _testData = GetRequiredService(); - } + var user = await _identityUserManager.GetByIdAsync(_testData.UserJohnId); + user.ShouldNotBeNull(); - [Fact] - public async Task Add_And_Replace_Claims_Test() - { - await UsingUowAsync(async () => - { - var user = await _identityUserManager.GetByIdAsync(_testData.UserJohnId); - user.ShouldNotBeNull(); + var claimsPrincipal = await _abpUserClaimsPrincipalFactory.CreateAsync(user); - var claimsPrincipal = await _abpUserClaimsPrincipalFactory.CreateAsync(user); + claimsPrincipal.Claims.ShouldContain(x => x.Type == ClaimTypes.NameIdentifier && x.Value == user.Id.ToString()); + claimsPrincipal.Claims.ShouldContain(x => x.Type == ClaimTypes.Name && x.Value == user.UserName); - claimsPrincipal.Claims.ShouldContain(x => x.Type == ClaimTypes.NameIdentifier && x.Value == user.Id.ToString()); - claimsPrincipal.Claims.ShouldContain(x => x.Type == ClaimTypes.Name && x.Value == user.UserName); + claimsPrincipal.Claims.ShouldContain(x => x.Type == ClaimTypes.Uri && x.Value == "www.abp.io"); - claimsPrincipal.Claims.ShouldContain(x => x.Type == ClaimTypes.Uri && x.Value =="www.abp.io"); + claimsPrincipal.Claims.ShouldNotContain(x => x.Type == ClaimTypes.Email && x.Value == user.Email); + claimsPrincipal.Claims.ShouldContain(x => x.Type == ClaimTypes.Email && x.Value == "replaced@abp.io"); + }); + } - claimsPrincipal.Claims.ShouldNotContain(x => x.Type == ClaimTypes.Email && x.Value == user.Email); - claimsPrincipal.Claims.ShouldContain(x => x.Type == ClaimTypes.Email && x.Value == "replaced@abp.io"); - }); - } + class TestAbpClaimsPrincipalContributor : IAbpClaimsPrincipalContributor, ITransientDependency + { + //https://github.com/dotnet/aspnetcore/blob/v5.0.0/src/Identity/Extensions.Core/src/UserClaimsPrincipalFactory.cs#L79 + private static string IdentityAuthenticationType => "Identity.Application"; - class TestAbpClaimsPrincipalContributor : IAbpClaimsPrincipalContributor, ITransientDependency + public Task ContributeAsync(AbpClaimsPrincipalContributorContext context) { - //https://github.com/dotnet/aspnetcore/blob/v5.0.0/src/Identity/Extensions.Core/src/UserClaimsPrincipalFactory.cs#L79 - private static string IdentityAuthenticationType => "Identity.Application"; + var claimsIdentity = context.ClaimsPrincipal.Identities.First(x => x.AuthenticationType == IdentityAuthenticationType); - public Task ContributeAsync(AbpClaimsPrincipalContributorContext context) - { - var claimsIdentity = context.ClaimsPrincipal.Identities.First(x => x.AuthenticationType == IdentityAuthenticationType); + claimsIdentity.AddOrReplace(new Claim(ClaimTypes.Uri, "www.abp.io")); + claimsIdentity.AddOrReplace(new Claim(ClaimTypes.Email, "replaced@abp.io")); - claimsIdentity.AddOrReplace(new Claim(ClaimTypes.Uri, "www.abp.io")); - claimsIdentity.AddOrReplace(new Claim(ClaimTypes.Email, "replaced@abp.io")); + context.ClaimsPrincipal.AddIdentityIfNotContains(claimsIdentity); - context.ClaimsPrincipal.AddIdentityIfNotContains(claimsIdentity); - - return Task.CompletedTask; - } + return Task.CompletedTask; } - } + } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/DistributedUserUpdateHandler.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/DistributedUserUpdateHandler.cs index bf9a0260e9..fa8417ffe5 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/DistributedUserUpdateHandler.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/DistributedUserUpdateHandler.cs @@ -5,25 +5,24 @@ using Volo.Abp.EventBus.Distributed; using Volo.Abp.Testing.Utils; using Volo.Abp.Users; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class DistributedUserUpdateHandler : IDistributedEventHandler>, ITransientDependency { - public class DistributedUserUpdateHandler : IDistributedEventHandler>, ITransientDependency + private readonly ITestCounter _testCounter; + + public DistributedUserUpdateHandler(ITestCounter testCounter) { - private readonly ITestCounter _testCounter; + _testCounter = testCounter; + } - public DistributedUserUpdateHandler(ITestCounter testCounter) + public Task HandleEventAsync(EntityUpdatedEto eventData) + { + if (eventData.Entity.UserName == "john.nash") { - _testCounter = testCounter; + _testCounter.Increment("EntityUpdatedEto"); } - public Task HandleEventAsync(EntityUpdatedEto eventData) - { - if (eventData.Entity.UserName == "john.nash") - { - _testCounter.Increment("EntityUpdatedEto"); - } - - return Task.CompletedTask; - } + return Task.CompletedTask; } -} \ No newline at end of file +} diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Distributed_Role_Change_Events_Test.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Distributed_Role_Change_Events_Test.cs index a57a8baf69..e2335d57ab 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Distributed_Role_Change_Events_Test.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Distributed_Role_Change_Events_Test.cs @@ -12,94 +12,93 @@ using Volo.Abp.PermissionManagement.Identity; using Volo.Abp.Uow; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class Distributed_Role_Change_Events_Test : AbpIdentityDomainTestBase { - public class Distributed_Role_Change_Events_Test : AbpIdentityDomainTestBase - { - protected readonly IIdentityRoleRepository RoleRepository; - protected readonly IPermissionGrantRepository PermissionGrantRepository; - protected readonly IdentityRoleManager RoleManager; - protected readonly ILookupNormalizer LookupNormalizer; - protected readonly IUnitOfWorkManager UowManager; - protected readonly IDistributedCache Cache; + protected readonly IIdentityRoleRepository RoleRepository; + protected readonly IPermissionGrantRepository PermissionGrantRepository; + protected readonly IdentityRoleManager RoleManager; + protected readonly ILookupNormalizer LookupNormalizer; + protected readonly IUnitOfWorkManager UowManager; + protected readonly IDistributedCache Cache; - public Distributed_Role_Change_Events_Test() - { - RoleRepository = GetRequiredService(); - ; - PermissionGrantRepository = GetRequiredService(); - ; - RoleManager = GetRequiredService(); - ; - LookupNormalizer = GetRequiredService(); - ; - UowManager = GetRequiredService(); - Cache = GetRequiredService>(); - } + public Distributed_Role_Change_Events_Test() + { + RoleRepository = GetRequiredService(); + ; + PermissionGrantRepository = GetRequiredService(); + ; + RoleManager = GetRequiredService(); + ; + LookupNormalizer = GetRequiredService(); + ; + UowManager = GetRequiredService(); + Cache = GetRequiredService>(); + } - [Fact] - public void Should_Register_Handler() - { - var x = GetRequiredService>(); - GetRequiredService>() - .Value - .AutoEventSelectors - .ShouldContain(m => m.Name == "Entity:" + typeof(IdentityRole).FullName); + [Fact] + public void Should_Register_Handler() + { + var x = GetRequiredService>(); + GetRequiredService>() + .Value + .AutoEventSelectors + .ShouldContain(m => m.Name == "Entity:" + typeof(IdentityRole).FullName); - GetRequiredService>() - .Value - .Handlers - .ShouldContain(h => h == typeof(RoleUpdateEventHandler) || h == typeof(RoleDeletedEventHandler)); - } + GetRequiredService>() + .Value + .Handlers + .ShouldContain(h => h == typeof(RoleUpdateEventHandler) || h == typeof(RoleDeletedEventHandler)); + } - [Fact] - public async Task Role_Updated_Distributed_Event_Test() - { - var role = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("moderator")); + [Fact] + public async Task Role_Updated_Distributed_Event_Test() + { + var role = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("moderator")); - var permissionGrantsInRole = await PermissionGrantRepository.GetListAsync("R", role.Name); - permissionGrantsInRole.ShouldNotBeNull(); - permissionGrantsInRole.Count.ShouldBeGreaterThan(0); - var count = permissionGrantsInRole.Count; + var permissionGrantsInRole = await PermissionGrantRepository.GetListAsync("R", role.Name); + permissionGrantsInRole.ShouldNotBeNull(); + permissionGrantsInRole.Count.ShouldBeGreaterThan(0); + var count = permissionGrantsInRole.Count; - using (var uow = UowManager.Begin()) - { - var identityResult = await RoleManager.SetRoleNameAsync(role, "TestModerator"); - identityResult.Succeeded.ShouldBeTrue(); - await RoleRepository.UpdateAsync(role); - await uow.CompleteAsync(); - } + using (var uow = UowManager.Begin()) + { + var identityResult = await RoleManager.SetRoleNameAsync(role, "TestModerator"); + identityResult.Succeeded.ShouldBeTrue(); + await RoleRepository.UpdateAsync(role); + await uow.CompleteAsync(); + } - role = await RoleRepository.GetAsync(role.Id); - role.Name.ShouldBe("TestModerator"); + role = await RoleRepository.GetAsync(role.Id); + role.Name.ShouldBe("TestModerator"); - permissionGrantsInRole = await PermissionGrantRepository.GetListAsync("R", role.Name); - permissionGrantsInRole.Count.ShouldBe(count); - } + permissionGrantsInRole = await PermissionGrantRepository.GetListAsync("R", role.Name); + permissionGrantsInRole.Count.ShouldBe(count); + } - [Fact] - public async Task Role_Deleted_Distributed_Event_Test() - { - var role = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("moderator")); - var permissionGrantsInRole = await PermissionGrantRepository.GetListAsync("R", role.Name); + [Fact] + public async Task Role_Deleted_Distributed_Event_Test() + { + var role = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("moderator")); + var permissionGrantsInRole = await PermissionGrantRepository.GetListAsync("R", role.Name); - var caches = permissionGrantsInRole.Select(x => new KeyValuePair( - PermissionGrantCacheItem.CalculateCacheKey(x.Name, x.ProviderName, x.ProviderKey), - new PermissionGrantCacheItem(true))).ToList(); - await Cache.SetManyAsync(caches); + var caches = permissionGrantsInRole.Select(x => new KeyValuePair( + PermissionGrantCacheItem.CalculateCacheKey(x.Name, x.ProviderName, x.ProviderKey), + new PermissionGrantCacheItem(true))).ToList(); + await Cache.SetManyAsync(caches); - using (var uow = UowManager.Begin()) - { - await RoleRepository.DeleteAsync(role); - await uow.CompleteAsync(); - } + using (var uow = UowManager.Begin()) + { + await RoleRepository.DeleteAsync(role); + await uow.CompleteAsync(); + } - var permissionGrantCaches = await Cache.GetManyAsync(caches.Select(x=>x.Key)); - foreach (var cache in permissionGrantCaches) - { - cache.Value.ShouldBeNull(); - } + var permissionGrantCaches = await Cache.GetManyAsync(caches.Select(x => x.Key)); + foreach (var cache in permissionGrantCaches) + { + cache.Value.ShouldBeNull(); } } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Distributed_User_Change_Event_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Distributed_User_Change_Event_Tests.cs index b3fc9b1ba3..3cbbcc4f8e 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Distributed_User_Change_Event_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Distributed_User_Change_Event_Tests.cs @@ -9,52 +9,51 @@ using Volo.Abp.Uow; using Volo.Abp.Users; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class Distributed_User_Change_Event_Tests : AbpIdentityDomainTestBase { - public class Distributed_User_Change_Event_Tests : AbpIdentityDomainTestBase + private readonly IIdentityUserRepository _userRepository; + private readonly ILookupNormalizer _lookupNormalizer; + private readonly IdentityUserManager _userManager; + private readonly IUnitOfWorkManager _unitOfWorkManager; + private readonly ITestCounter _testCounter; + + public Distributed_User_Change_Event_Tests() { - private readonly IIdentityUserRepository _userRepository; - private readonly ILookupNormalizer _lookupNormalizer; - private readonly IdentityUserManager _userManager; - private readonly IUnitOfWorkManager _unitOfWorkManager; - private readonly ITestCounter _testCounter; + _userRepository = GetRequiredService(); + _userManager = GetRequiredService(); + _lookupNormalizer = GetRequiredService(); + _unitOfWorkManager = GetRequiredService(); + _testCounter = GetRequiredService(); + } - public Distributed_User_Change_Event_Tests() - { - _userRepository = GetRequiredService(); - _userManager = GetRequiredService(); - _lookupNormalizer = GetRequiredService(); - _unitOfWorkManager = GetRequiredService(); - _testCounter = GetRequiredService(); - } + [Fact] + public void Should_Register_Handler() + { + GetRequiredService>() + .Value + .EtoMappings + .ShouldContain(m => m.Key == typeof(IdentityUser) && m.Value.EtoType == typeof(UserEto)); - [Fact] - public void Should_Register_Handler() - { - GetRequiredService>() - .Value - .EtoMappings - .ShouldContain(m => m.Key == typeof(IdentityUser) && m.Value.EtoType == typeof(UserEto)); - - GetRequiredService>() - .Value - .Handlers - .ShouldContain(h => h == typeof(DistributedUserUpdateHandler)); - } + GetRequiredService>() + .Value + .Handlers + .ShouldContain(h => h == typeof(DistributedUserUpdateHandler)); + } - [Fact] - public async Task Should_Trigger_Distributed_EntityUpdated_Event() + [Fact] + public async Task Should_Trigger_Distributed_EntityUpdated_Event() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - await _userManager.SetEmailAsync(user, "john.nash_UPDATED@abp.io"); - - _testCounter.GetValue("EntityUpdatedEto").ShouldBe(0); - await uow.CompleteAsync(); - } + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + await _userManager.SetEmailAsync(user, "john.nash_UPDATED@abp.io"); - _testCounter.GetValue("EntityUpdatedEto").ShouldBe(1); + _testCounter.GetValue("EntityUpdatedEto").ShouldBe(0); + await uow.CompleteAsync(); } + + _testCounter.GetValue("EntityUpdatedEto").ShouldBe(1); } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityClaimTypeManager_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityClaimTypeManager_Tests.cs index 23d5ea0d02..0a422239a8 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityClaimTypeManager_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityClaimTypeManager_Tests.cs @@ -3,69 +3,68 @@ using System.Threading.Tasks; using Shouldly; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityClaimTypeManager_Tests : AbpIdentityDomainTestBase { - public class IdentityClaimTypeManager_Tests : AbpIdentityDomainTestBase - { - private readonly IIdentityClaimTypeRepository _identityClaimTypeRepository; - private readonly IdentityClaimTypeManager _claimTypeManager; - private readonly IdentityTestData _testData; + private readonly IIdentityClaimTypeRepository _identityClaimTypeRepository; + private readonly IdentityClaimTypeManager _claimTypeManager; + private readonly IdentityTestData _testData; - public IdentityClaimTypeManager_Tests() - { - _identityClaimTypeRepository = GetRequiredService(); - _claimTypeManager = GetRequiredService(); - _testData = GetRequiredService(); - } + public IdentityClaimTypeManager_Tests() + { + _identityClaimTypeRepository = GetRequiredService(); + _claimTypeManager = GetRequiredService(); + _testData = GetRequiredService(); + } - [Fact] - public async Task CreateAsync() - { - var claimType = await _claimTypeManager.CreateAsync(new IdentityClaimType(Guid.NewGuid(), "Phone", false, - false, null, - null, null, IdentityClaimValueType.String)); + [Fact] + public async Task CreateAsync() + { + var claimType = await _claimTypeManager.CreateAsync(new IdentityClaimType(Guid.NewGuid(), "Phone", false, + false, null, + null, null, IdentityClaimValueType.String)); - claimType.ShouldNotBeNull(); - claimType.Name.ShouldBe("Phone"); - } + claimType.ShouldNotBeNull(); + claimType.Name.ShouldBe("Phone"); + } - [Fact] - public async Task Create_Name_Exist_Should_Exception() - { - await Assert.ThrowsAnyAsync(async () => await _claimTypeManager.CreateAsync( - new IdentityClaimType( - Guid.NewGuid(), "Age"))); - } + [Fact] + public async Task Create_Name_Exist_Should_Exception() + { + await Assert.ThrowsAnyAsync(async () => await _claimTypeManager.CreateAsync( + new IdentityClaimType( + Guid.NewGuid(), "Age"))); + } - [Fact] - public async Task UpdateAsync() - { - var ageClaim = await _identityClaimTypeRepository.FindAsync(_testData.AgeClaimId); - ageClaim.ShouldNotBeNull(); - ageClaim.Description = "this is age"; + [Fact] + public async Task UpdateAsync() + { + var ageClaim = await _identityClaimTypeRepository.FindAsync(_testData.AgeClaimId); + ageClaim.ShouldNotBeNull(); + ageClaim.Description = "this is age"; - var updatedAgeClaimType = await _claimTypeManager.UpdateAsync(ageClaim); - updatedAgeClaimType.ShouldNotBeNull(); - updatedAgeClaimType.Description.ShouldBe("this is age"); - } + var updatedAgeClaimType = await _claimTypeManager.UpdateAsync(ageClaim); + updatedAgeClaimType.ShouldNotBeNull(); + updatedAgeClaimType.Description.ShouldBe("this is age"); + } - [Fact] - public async Task Update_Name_Exist_Should_Exception() - { - await Assert.ThrowsAnyAsync(async () => await _claimTypeManager.UpdateAsync( - new IdentityClaimType( - Guid.NewGuid(), "Age"))); - } + [Fact] + public async Task Update_Name_Exist_Should_Exception() + { + await Assert.ThrowsAnyAsync(async () => await _claimTypeManager.UpdateAsync( + new IdentityClaimType( + Guid.NewGuid(), "Age"))); + } - [Fact] - public async Task Static_IdentityClaimType_Cant_Not_Update() - { - var phoneClaim = new IdentityClaimType(Guid.NewGuid(), "Phone", true, true); - await _identityClaimTypeRepository.InsertAsync(phoneClaim); + [Fact] + public async Task Static_IdentityClaimType_Cant_Not_Update() + { + var phoneClaim = new IdentityClaimType(Guid.NewGuid(), "Phone", true, true); + await _identityClaimTypeRepository.InsertAsync(phoneClaim); - await Assert.ThrowsAnyAsync(async () => await _claimTypeManager.UpdateAsync(phoneClaim)); - } + await Assert.ThrowsAnyAsync(async () => await _claimTypeManager.UpdateAsync(phoneClaim)); } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityLinkUserManager_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityLinkUserManager_Tests.cs index 953824ef5b..e13fefb1c2 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityLinkUserManager_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityLinkUserManager_Tests.cs @@ -3,190 +3,189 @@ using System.Threading.Tasks; using Shouldly; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityLinkUserManager_Tests : AbpIdentityDomainTestBase { - public class IdentityLinkUserManager_Tests : AbpIdentityDomainTestBase + protected IIdentityUserRepository UserRepository { get; } + protected IIdentityLinkUserRepository IdentityLinkUserRepository { get; } + protected IdentityLinkUserManager IdentityLinkUserManager { get; } + protected IdentityTestData TestData { get; } + + public IdentityLinkUserManager_Tests() + { + UserRepository = GetRequiredService(); + IdentityLinkUserRepository = GetRequiredService(); + IdentityLinkUserManager = GetRequiredService(); + TestData = GetRequiredService(); + } + + [Fact] + public async Task GetListAsync_Test() + { + var a = Guid.NewGuid(); + var b = Guid.NewGuid(); + var c = Guid.NewGuid(); + var d = Guid.NewGuid(); + var e = Guid.NewGuid(); + var f = Guid.NewGuid(); + var g = Guid.NewGuid(); + var h = Guid.NewGuid(); + var i = Guid.NewGuid(); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(a, null), + new IdentityLinkUserInfo(b, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(c, null), + new IdentityLinkUserInfo(a, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(d, null), + new IdentityLinkUserInfo(c, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(e, null), + new IdentityLinkUserInfo(c, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(f, null), + new IdentityLinkUserInfo(e, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(g, null), + new IdentityLinkUserInfo(h, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(i, null), + new IdentityLinkUserInfo(h, null)), true); + + var linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(a, null)); + linkUsers.Count.ShouldBe(2); + + linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(f, null)); + linkUsers.Count.ShouldBe(1); + + linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(g, null)); + linkUsers.Count.ShouldBe(1); + } + + [Fact] + public async Task GetListAsync_Indirect_Test() + { + var a = Guid.NewGuid(); + var b = Guid.NewGuid(); + var c = Guid.NewGuid(); + var d = Guid.NewGuid(); + var e = Guid.NewGuid(); + var f = Guid.NewGuid(); + var g = Guid.NewGuid(); + var h = Guid.NewGuid(); + var i = Guid.NewGuid(); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(a, null), + new IdentityLinkUserInfo(b, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(c, null), + new IdentityLinkUserInfo(a, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(d, null), + new IdentityLinkUserInfo(c, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(e, null), + new IdentityLinkUserInfo(c, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(f, null), + new IdentityLinkUserInfo(e, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(g, null), + new IdentityLinkUserInfo(h, null)), true); + + await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( + Guid.NewGuid(), + new IdentityLinkUserInfo(i, null), + new IdentityLinkUserInfo(h, null)), true); + + var linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(a, null), includeIndirect: true); + linkUsers.Count.ShouldBe(5); + + linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(f, null), includeIndirect: true); + linkUsers.Count.ShouldBe(5); + + linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(g, null), includeIndirect: true); + linkUsers.Count.ShouldBe(2); + } + + [Fact] + public virtual async Task LinkAsync() { - protected IIdentityUserRepository UserRepository { get; } - protected IIdentityLinkUserRepository IdentityLinkUserRepository { get; } - protected IdentityLinkUserManager IdentityLinkUserManager { get; } - protected IdentityTestData TestData { get; } - - public IdentityLinkUserManager_Tests() - { - UserRepository = GetRequiredService(); - IdentityLinkUserRepository = GetRequiredService(); - IdentityLinkUserManager = GetRequiredService(); - TestData = GetRequiredService(); - } - - [Fact] - public async Task GetListAsync_Test() - { - var a = Guid.NewGuid(); - var b = Guid.NewGuid(); - var c = Guid.NewGuid(); - var d = Guid.NewGuid(); - var e = Guid.NewGuid(); - var f = Guid.NewGuid(); - var g = Guid.NewGuid(); - var h = Guid.NewGuid(); - var i = Guid.NewGuid(); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(a, null), - new IdentityLinkUserInfo(b, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(c, null), - new IdentityLinkUserInfo(a, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(d, null), - new IdentityLinkUserInfo(c, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(e, null), - new IdentityLinkUserInfo(c, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(f, null), - new IdentityLinkUserInfo(e, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(g, null), - new IdentityLinkUserInfo(h, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(i, null), - new IdentityLinkUserInfo(h, null)), true); - - var linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(a, null)); - linkUsers.Count.ShouldBe(2); - - linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(f, null)); - linkUsers.Count.ShouldBe(1); - - linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(g, null)); - linkUsers.Count.ShouldBe(1); - } - - [Fact] - public async Task GetListAsync_Indirect_Test() - { - var a = Guid.NewGuid(); - var b = Guid.NewGuid(); - var c = Guid.NewGuid(); - var d = Guid.NewGuid(); - var e = Guid.NewGuid(); - var f = Guid.NewGuid(); - var g = Guid.NewGuid(); - var h = Guid.NewGuid(); - var i = Guid.NewGuid(); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(a, null), - new IdentityLinkUserInfo(b, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(c, null), - new IdentityLinkUserInfo(a, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(d, null), - new IdentityLinkUserInfo(c, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(e, null), - new IdentityLinkUserInfo(c, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(f, null), - new IdentityLinkUserInfo(e, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(g, null), - new IdentityLinkUserInfo(h, null)), true); - - await IdentityLinkUserRepository.InsertAsync(new IdentityLinkUser( - Guid.NewGuid(), - new IdentityLinkUserInfo(i, null), - new IdentityLinkUserInfo(h, null)), true); - - var linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(a, null), includeIndirect: true); - linkUsers.Count.ShouldBe(5); - - linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(f, null), includeIndirect: true); - linkUsers.Count.ShouldBe(5); - - linkUsers = await IdentityLinkUserManager.GetListAsync(new IdentityLinkUserInfo(g, null), includeIndirect: true); - linkUsers.Count.ShouldBe(2); - } - - [Fact] - public virtual async Task LinkAsync() - { - var john = await UserRepository.GetAsync(TestData.UserJohnId); - var neo = await UserRepository.GetAsync(TestData.UserNeoId); - - (await IdentityLinkUserRepository.FindAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(neo.Id, neo.TenantId))).ShouldBeNull(); - - await IdentityLinkUserManager.LinkAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(neo.Id, neo.TenantId)); - - var linkUser = await IdentityLinkUserRepository.FindAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(neo.Id, neo.TenantId)); - - linkUser.ShouldNotBeNull(); - linkUser.SourceUserId.ShouldBe(john.Id); - linkUser.SourceTenantId.ShouldBe(john.TenantId); - - linkUser.TargetUserId.ShouldBe(neo.Id); - linkUser.TargetTenantId.ShouldBe(neo.TenantId); - } - - [Fact] - public virtual async Task UnlinkAsync() - { - var john = await UserRepository.GetAsync(TestData.UserJohnId); - var david = await UserRepository.GetAsync(TestData.UserDavidId); - - (await IdentityLinkUserRepository.FindAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(david.Id, david.TenantId))).ShouldNotBeNull(); - - await IdentityLinkUserManager.UnlinkAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(david.Id, david.TenantId)); - - (await IdentityLinkUserRepository.FindAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(david.Id, david.TenantId))).ShouldBeNull(); - } - - [Fact] - public virtual async Task IsLinkedAsync() - { - var john = await UserRepository.GetAsync(TestData.UserJohnId); - var david = await UserRepository.GetAsync(TestData.UserDavidId); - var neo = await UserRepository.GetAsync(TestData.UserNeoId); - - (await IdentityLinkUserManager.IsLinkedAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(david.Id, david.TenantId))).ShouldBeTrue(); - - (await IdentityLinkUserManager.IsLinkedAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(neo.Id, neo.TenantId))).ShouldBeFalse(); - } + var john = await UserRepository.GetAsync(TestData.UserJohnId); + var neo = await UserRepository.GetAsync(TestData.UserNeoId); + + (await IdentityLinkUserRepository.FindAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(neo.Id, neo.TenantId))).ShouldBeNull(); + + await IdentityLinkUserManager.LinkAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(neo.Id, neo.TenantId)); + + var linkUser = await IdentityLinkUserRepository.FindAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(neo.Id, neo.TenantId)); + + linkUser.ShouldNotBeNull(); + linkUser.SourceUserId.ShouldBe(john.Id); + linkUser.SourceTenantId.ShouldBe(john.TenantId); + + linkUser.TargetUserId.ShouldBe(neo.Id); + linkUser.TargetTenantId.ShouldBe(neo.TenantId); + } + + [Fact] + public virtual async Task UnlinkAsync() + { + var john = await UserRepository.GetAsync(TestData.UserJohnId); + var david = await UserRepository.GetAsync(TestData.UserDavidId); + + (await IdentityLinkUserRepository.FindAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(david.Id, david.TenantId))).ShouldNotBeNull(); + + await IdentityLinkUserManager.UnlinkAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(david.Id, david.TenantId)); + + (await IdentityLinkUserRepository.FindAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(david.Id, david.TenantId))).ShouldBeNull(); + } + + [Fact] + public virtual async Task IsLinkedAsync() + { + var john = await UserRepository.GetAsync(TestData.UserJohnId); + var david = await UserRepository.GetAsync(TestData.UserDavidId); + var neo = await UserRepository.GetAsync(TestData.UserNeoId); + + (await IdentityLinkUserManager.IsLinkedAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(david.Id, david.TenantId))).ShouldBeTrue(); + + (await IdentityLinkUserManager.IsLinkedAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(neo.Id, neo.TenantId))).ShouldBeFalse(); } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityOptions_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityOptions_Tests.cs index 0c9a682f67..c707feac5c 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityOptions_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityOptions_Tests.cs @@ -9,67 +9,66 @@ using Volo.Abp.Identity.Settings; using Volo.Abp.Settings; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityOptions_Tests : AbpIdentityDomainTestBase { - public class IdentityOptions_Tests : AbpIdentityDomainTestBase - { - private ISettingProvider _settingProvider; + private ISettingProvider _settingProvider; - protected override void AfterAddApplication(IServiceCollection services) - { - _settingProvider = Substitute.For(); - _settingProvider.GetOrNullAsync(Arg.Any()).Returns((string) null); - services.Replace(ServiceDescriptor.Singleton(_settingProvider)); - } + protected override void AfterAddApplication(IServiceCollection services) + { + _settingProvider = Substitute.For(); + _settingProvider.GetOrNullAsync(Arg.Any()).Returns((string)null); + services.Replace(ServiceDescriptor.Singleton(_settingProvider)); + } - [Fact] - public void Should_Resolve_AbpIdentityOptionsManager() - { - GetRequiredService>().ShouldBeOfType(typeof(AbpIdentityOptionsManager)); - } + [Fact] + public void Should_Resolve_AbpIdentityOptionsManager() + { + GetRequiredService>().ShouldBeOfType(typeof(AbpIdentityOptionsManager)); + } - [Fact] - public async Task Should_Get_Options_From_Custom_Settings_If_Available() + [Fact] + public async Task Should_Get_Options_From_Custom_Settings_If_Available() + { + using (var scope1 = ServiceProvider.CreateScope()) { - using (var scope1 = ServiceProvider.CreateScope()) - { - var options = scope1.ServiceProvider.GetRequiredService>(); + var options = scope1.ServiceProvider.GetRequiredService>(); - //Can not get the values from the SettingProvider without options.SetAsync(); + //Can not get the values from the SettingProvider without options.SetAsync(); - options.Value.Password.RequiredLength.ShouldBe(6); //Default value - options.Value.Password.RequiredUniqueChars.ShouldBe(1); //Default value - } + options.Value.Password.RequiredLength.ShouldBe(6); //Default value + options.Value.Password.RequiredUniqueChars.ShouldBe(1); //Default value + } - using (var scope2 = ServiceProvider.CreateScope()) - { - var options = scope2.ServiceProvider.GetRequiredService>(); - var optionsValue = options.Value; + using (var scope2 = ServiceProvider.CreateScope()) + { + var options = scope2.ServiceProvider.GetRequiredService>(); + var optionsValue = options.Value; - await options.SetAsync(); + await options.SetAsync(); - //Still the default values because SettingProvider has not been configured yet + //Still the default values because SettingProvider has not been configured yet - optionsValue.Password.RequiredLength.ShouldBe(6); //Default value - optionsValue.Password.RequiredUniqueChars.ShouldBe(1); //Default value - } + optionsValue.Password.RequiredLength.ShouldBe(6); //Default value + optionsValue.Password.RequiredUniqueChars.ShouldBe(1); //Default value + } - _settingProvider - .GetOrNullAsync(IdentitySettingNames.Password.RequiredLength) - .Returns(Task.FromResult("42")); + _settingProvider + .GetOrNullAsync(IdentitySettingNames.Password.RequiredLength) + .Returns(Task.FromResult("42")); - using (var scope2 = ServiceProvider.CreateScope()) - { - var options = scope2.ServiceProvider.GetRequiredService>(); - var optionsValue = options.Value; + using (var scope2 = ServiceProvider.CreateScope()) + { + var options = scope2.ServiceProvider.GetRequiredService>(); + var optionsValue = options.Value; - await options.SetAsync(); + await options.SetAsync(); - //Get the value from SettingProvider + //Get the value from SettingProvider - optionsValue.Password.RequiredLength.ShouldBe(42); //Setting value - optionsValue.Password.RequiredUniqueChars.ShouldBe(1); //Default value - } + optionsValue.Password.RequiredLength.ShouldBe(42); //Setting value + optionsValue.Password.RequiredUniqueChars.ShouldBe(1); //Default value } } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityRoleManager_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityRoleManager_Tests.cs index 4314f3eac6..0598cb7d0b 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityRoleManager_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityRoleManager_Tests.cs @@ -7,54 +7,53 @@ using Shouldly; using Volo.Abp.Uow; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityRoleManager_Tests : AbpIdentityDomainTestBase { - public class IdentityRoleManager_Tests : AbpIdentityDomainTestBase + private readonly IdentityRoleManager _identityRoleManager; + private readonly IIdentityRoleRepository _identityRoleRepository; + private readonly ILookupNormalizer _lookupNormalizer; + private readonly IdentityTestData _testData; + + public IdentityRoleManager_Tests() { - private readonly IdentityRoleManager _identityRoleManager; - private readonly IIdentityRoleRepository _identityRoleRepository; - private readonly ILookupNormalizer _lookupNormalizer; - private readonly IdentityTestData _testData; - - public IdentityRoleManager_Tests() - { - _identityRoleManager = GetRequiredService(); - _identityRoleRepository = GetRequiredService(); - _lookupNormalizer = GetRequiredService(); - _testData = GetRequiredService(); - } - - - [Fact] - public async Task GetByIdAsync() - { - var role = await _identityRoleManager.FindByIdAsync(_testData.RoleModeratorId.ToString()); - - role.ShouldNotBeNull(); - role.Name.ShouldBe("moderator"); - } - - [Fact] - public async Task SetRoleNameAsync() - { - var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); - role.ShouldNotBeNull(); - - (await _identityRoleManager.SetRoleNameAsync(role, "teacher")).Succeeded.ShouldBeTrue(); - - role.Name.ShouldBe("teacher"); - } - - [Fact] - public async Task DeleteAsync() - { - var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); - role.ShouldNotBeNull(); - - await _identityRoleManager.DeleteAsync(role); - - (await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator"))).ShouldBeNull(); - } + _identityRoleManager = GetRequiredService(); + _identityRoleRepository = GetRequiredService(); + _lookupNormalizer = GetRequiredService(); + _testData = GetRequiredService(); + } + + [Fact] + public async Task GetByIdAsync() + { + var role = await _identityRoleManager.FindByIdAsync(_testData.RoleModeratorId.ToString()); + + role.ShouldNotBeNull(); + role.Name.ShouldBe("moderator"); } + + [Fact] + public async Task SetRoleNameAsync() + { + var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role.ShouldNotBeNull(); + + (await _identityRoleManager.SetRoleNameAsync(role, "teacher")).Succeeded.ShouldBeTrue(); + + role.Name.ShouldBe("teacher"); + } + + [Fact] + public async Task DeleteAsync() + { + var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role.ShouldNotBeNull(); + + await _identityRoleManager.DeleteAsync(role); + + (await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator"))).ShouldBeNull(); + } + } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityRoleStore_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityRoleStore_Tests.cs index 8f3ce4c2b0..42e81597d8 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityRoleStore_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityRoleStore_Tests.cs @@ -8,190 +8,189 @@ using Shouldly; using Volo.Abp.Uow; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityRoleStore_Tests : AbpIdentityDomainTestBase { - public class IdentityRoleStore_Tests : AbpIdentityDomainTestBase + private readonly IdentityRoleStore _identityRoleStore; + private readonly ILookupNormalizer _lookupNormalizer; + private readonly IIdentityRoleRepository _identityRoleRepository; + private readonly IdentityTestData _testData; + private readonly IUnitOfWorkManager _unitOfWorkManager; + + public IdentityRoleStore_Tests() { - private readonly IdentityRoleStore _identityRoleStore; - private readonly ILookupNormalizer _lookupNormalizer; - private readonly IIdentityRoleRepository _identityRoleRepository; - private readonly IdentityTestData _testData; - private readonly IUnitOfWorkManager _unitOfWorkManager; + _identityRoleStore = GetRequiredService(); + _lookupNormalizer = GetRequiredService(); + _identityRoleRepository = GetRequiredService(); + _testData = GetRequiredService(); + _unitOfWorkManager = GetRequiredService(); + } - public IdentityRoleStore_Tests() - { - _identityRoleStore = GetRequiredService(); - _lookupNormalizer = GetRequiredService(); - _identityRoleRepository = GetRequiredService(); - _testData = GetRequiredService(); - _unitOfWorkManager = GetRequiredService(); - } + [Fact] + public async Task CreateAsync() + { + var roleId = Guid.NewGuid(); + var role = new IdentityRole(roleId, "teacher"); + (await _identityRoleStore.CreateAsync(role)).Succeeded.ShouldBeTrue(); - [Fact] - public async Task CreateAsync() - { - var roleId = Guid.NewGuid(); - var role = new IdentityRole(roleId, "teacher"); - (await _identityRoleStore.CreateAsync(role)).Succeeded.ShouldBeTrue(); + var teacher = await _identityRoleStore.FindByIdAsync(roleId.ToString()); - var teacher = await _identityRoleStore.FindByIdAsync(roleId.ToString()); + teacher.ShouldNotBeNull(); + teacher.Name.ShouldBe("teacher"); + } - teacher.ShouldNotBeNull(); - teacher.Name.ShouldBe("teacher"); - } + [Fact] + public async Task UpdateAsync() + { + var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role.ShouldNotBeNull(); - [Fact] - public async Task UpdateAsync() - { - var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); - role.ShouldNotBeNull(); + role.IsDefault = true; + await _identityRoleStore.UpdateAsync(role); - role.IsDefault = true; - await _identityRoleStore.UpdateAsync(role); + role.IsDefault.ShouldBeTrue(); + } - role.IsDefault.ShouldBeTrue(); - } + [Fact] + public async Task DeleteAsync() + { + var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role.ShouldNotBeNull(); - [Fact] - public async Task DeleteAsync() - { - var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); - role.ShouldNotBeNull(); + await _identityRoleStore.DeleteAsync(role); - await _identityRoleStore.DeleteAsync(role); + (await _identityRoleStore.FindByIdAsync(_testData.RoleModeratorId.ToString())).ShouldBeNull(); + } - (await _identityRoleStore.FindByIdAsync(_testData.RoleModeratorId.ToString())).ShouldBeNull(); - } + [Fact] + public async Task GetRoleIdAsync() + { + var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role.ShouldNotBeNull(); - [Fact] - public async Task GetRoleIdAsync() - { - var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); - role.ShouldNotBeNull(); + (await _identityRoleStore.GetRoleIdAsync(role)).ShouldBe(_testData.RoleModeratorId.ToString()); + } - (await _identityRoleStore.GetRoleIdAsync(role)).ShouldBe(_testData.RoleModeratorId.ToString()); - } + [Fact] + public async Task GetRoleNameAsync() + { + var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role.ShouldNotBeNull(); - [Fact] - public async Task GetRoleNameAsync() - { - var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); - role.ShouldNotBeNull(); + (await _identityRoleStore.GetRoleNameAsync(role)).ShouldBe(role.Name); + } - (await _identityRoleStore.GetRoleNameAsync(role)).ShouldBe(role.Name); - } + [Fact] + public async Task SetRoleNameAsync() + { + var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role.ShouldNotBeNull(); - [Fact] - public async Task SetRoleNameAsync() - { - var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); - role.ShouldNotBeNull(); + await _identityRoleStore.SetRoleNameAsync(role, "teacher"); - await _identityRoleStore.SetRoleNameAsync(role, "teacher"); + role.Name.ShouldBe("teacher"); + } - role.Name.ShouldBe("teacher"); - } + [Fact] + public async Task FindByIdAsync() + { + var role = await _identityRoleStore.FindByIdAsync(_testData.RoleModeratorId.ToString()); - [Fact] - public async Task FindByIdAsync() - { - var role = await _identityRoleStore.FindByIdAsync(_testData.RoleModeratorId.ToString()); + role.ShouldNotBeNull(); + role.Name.ShouldBe("moderator"); + } - role.ShouldNotBeNull(); - role.Name.ShouldBe("moderator"); - } + [Fact] + public async Task FindByNameAsync() + { + var role = await _identityRoleStore.FindByNameAsync(_lookupNormalizer.NormalizeName("moderator")); - [Fact] - public async Task FindByNameAsync() - { - var role = await _identityRoleStore.FindByNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role.ShouldNotBeNull(); + role.Name.ShouldBe("moderator"); + } - role.ShouldNotBeNull(); - role.Name.ShouldBe("moderator"); - } + [Fact] + public async Task GetNormalizedRoleNameAsync() + { + var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role.ShouldNotBeNull(); - [Fact] - public async Task GetNormalizedRoleNameAsync() - { - var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); - role.ShouldNotBeNull(); + (await _identityRoleStore.GetNormalizedRoleNameAsync(role)).ShouldBe(role.NormalizedName); + } - (await _identityRoleStore.GetNormalizedRoleNameAsync(role)).ShouldBe(role.NormalizedName); - } + [Fact] + public async Task SetNormalizedRoleNameAsync() + { + var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role.ShouldNotBeNull(); + + await _identityRoleStore.SetNormalizedRoleNameAsync(role, _lookupNormalizer.NormalizeName("teacher")); + + role.NormalizedName.ShouldBe(_lookupNormalizer.NormalizeName("teacher")); + } - [Fact] - public async Task SetNormalizedRoleNameAsync() + [Fact] + public async Task GetClaimsAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); role.ShouldNotBeNull(); - await _identityRoleStore.SetNormalizedRoleNameAsync(role, _lookupNormalizer.NormalizeName("teacher")); + var claims = await _identityRoleStore.GetClaimsAsync(role); + + claims.ShouldNotBeEmpty(); + claims.ShouldContain(x => x.Type == "test-claim" && x.Value == "test-value"); - role.NormalizedName.ShouldBe(_lookupNormalizer.NormalizeName("teacher")); + await uow.CompleteAsync(); } + } - [Fact] - public async Task GetClaimsAsync() + [Fact] + public async Task AddClaimAsync() + { + try { using (var uow = _unitOfWorkManager.Begin()) { var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); role.ShouldNotBeNull(); - var claims = await _identityRoleStore.GetClaimsAsync(role); + role.Claims.Add(new IdentityRoleClaim(Guid.NewGuid(), role.Id, "my-claim", "my-value", role.TenantId)); + //await _identityRoleStore.AddClaimAsync(role, new Claim("my-claim", "my-value")); - claims.ShouldNotBeEmpty(); - claims.ShouldContain(x => x.Type == "test-claim" && x.Value == "test-value"); + //role.Claims.ShouldContain(x => x.ClaimType == "my-claim" && x.ClaimValue == "my-value"); await uow.CompleteAsync(); } - } - [Fact] - public async Task AddClaimAsync() + } + catch { - try - { - using (var uow = _unitOfWorkManager.Begin()) - { - var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); - role.ShouldNotBeNull(); - - role.Claims.Add(new IdentityRoleClaim(Guid.NewGuid(), role.Id, "my-claim", "my-value", role.TenantId)); - //await _identityRoleStore.AddClaimAsync(role, new Claim("my-claim", "my-value")); - - //role.Claims.ShouldContain(x => x.ClaimType == "my-claim" && x.ClaimValue == "my-value"); - - await uow.CompleteAsync(); - } - - } - catch - { - throw; - } - - var role2 = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); - role2.ShouldNotBeNull(); - role2.Claims.ShouldContain(x => x.ClaimType == "my-claim" && x.ClaimValue == "my-value"); + throw; } - [Fact] - public async Task RemoveClaimAsync() + var role2 = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role2.ShouldNotBeNull(); + role2.Claims.ShouldContain(x => x.ClaimType == "my-claim" && x.ClaimValue == "my-value"); + } + + [Fact] + public async Task RemoveClaimAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); - role.ShouldNotBeNull(); + var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("moderator")); + role.ShouldNotBeNull(); - await _identityRoleStore.RemoveClaimAsync(role, new Claim("test-claim", "test-value")); + await _identityRoleStore.RemoveClaimAsync(role, new Claim("test-claim", "test-value")); - role.Claims.ShouldNotContain(x => x.ClaimType == "test-claim" && x.ClaimValue == "test-value"); + role.Claims.ShouldNotContain(x => x.ClaimType == "test-claim" && x.ClaimValue == "test-value"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityTestPermissionDefinitionProvider.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityTestPermissionDefinitionProvider.cs index 323758cd9f..4024b5e2b8 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityTestPermissionDefinitionProvider.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityTestPermissionDefinitionProvider.cs @@ -1,17 +1,16 @@ using Volo.Abp.Authorization.Permissions; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityTestPermissionDefinitionProvider : PermissionDefinitionProvider { - public class IdentityTestPermissionDefinitionProvider : PermissionDefinitionProvider + public override void Define(IPermissionDefinitionContext context) { - public override void Define(IPermissionDefinitionContext context) - { - var testGroup = context.AddGroup(TestPermissionNames.Groups.TestGroup); + var testGroup = context.AddGroup(TestPermissionNames.Groups.TestGroup); - testGroup.AddPermission(TestPermissionNames.MyPermission1); + testGroup.AddPermission(TestPermissionNames.MyPermission1); - var myPermission2 = testGroup.AddPermission(TestPermissionNames.MyPermission2); - myPermission2.AddChild(TestPermissionNames.MyPermission2_ChildPermission1); - } + var myPermission2 = testGroup.AddPermission(TestPermissionNames.MyPermission2); + myPermission2.AddChild(TestPermissionNames.MyPermission2_ChildPermission1); } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityUserManager_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityUserManager_Tests.cs index e60227cafe..29b51a9b54 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityUserManager_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityUserManager_Tests.cs @@ -8,232 +8,231 @@ using Shouldly; using Volo.Abp.Uow; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUserManager_Tests : AbpIdentityDomainTestBase { - public class IdentityUserManager_Tests : AbpIdentityDomainTestBase + private readonly IdentityUserManager _identityUserManager; + private readonly IIdentityUserRepository _identityUserRepository; + private readonly IIdentityRoleRepository _identityRoleRepository; + private readonly IOrganizationUnitRepository _organizationUnitRepository; + private readonly ILookupNormalizer _lookupNormalizer; + private readonly IUnitOfWorkManager _unitOfWorkManager; + private readonly IdentityTestData _testData; + protected IOptions _identityOptions { get; } + + public IdentityUserManager_Tests() { - private readonly IdentityUserManager _identityUserManager; - private readonly IIdentityUserRepository _identityUserRepository; - private readonly IIdentityRoleRepository _identityRoleRepository; - private readonly IOrganizationUnitRepository _organizationUnitRepository; - private readonly ILookupNormalizer _lookupNormalizer; - private readonly IUnitOfWorkManager _unitOfWorkManager; - private readonly IdentityTestData _testData; - protected IOptions _identityOptions { get; } - - public IdentityUserManager_Tests() - { - _identityUserManager = GetRequiredService(); - _identityUserRepository = GetRequiredService(); - _identityRoleRepository = GetRequiredService(); - _organizationUnitRepository = GetRequiredService(); - _lookupNormalizer = GetRequiredService(); - _testData = GetRequiredService(); - _unitOfWorkManager = GetRequiredService(); - _identityOptions = GetRequiredService>(); - } + _identityUserManager = GetRequiredService(); + _identityUserRepository = GetRequiredService(); + _identityRoleRepository = GetRequiredService(); + _organizationUnitRepository = GetRequiredService(); + _lookupNormalizer = GetRequiredService(); + _testData = GetRequiredService(); + _unitOfWorkManager = GetRequiredService(); + _identityOptions = GetRequiredService>(); + } - [Fact] - public async Task GetByIdAsync() - { - var user = await _identityUserManager.GetByIdAsync(_testData.UserJohnId); + [Fact] + public async Task GetByIdAsync() + { + var user = await _identityUserManager.GetByIdAsync(_testData.UserJohnId); - user.ShouldNotBeNull(); - user.UserName.ShouldBe("john.nash"); - } + user.ShouldNotBeNull(); + user.UserName.ShouldBe("john.nash"); + } - [Fact] - public async Task SetRolesAsync() + [Fact] + public async Task SetRolesAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _identityUserRepository.FindByNormalizedUserNameAsync( - _lookupNormalizer.NormalizeName("david") - ); + var user = await _identityUserRepository.FindByNormalizedUserNameAsync( + _lookupNormalizer.NormalizeName("david") + ); - user.ShouldNotBeNull(); + user.ShouldNotBeNull(); - var identityResult = await _identityUserManager.SetRolesAsync(user, new List() + var identityResult = await _identityUserManager.SetRolesAsync(user, new List() { "moderator", }); - identityResult.Succeeded.ShouldBeTrue(); - user.Roles.ShouldContain(x => x.RoleId == _testData.RoleModeratorId); + identityResult.Succeeded.ShouldBeTrue(); + user.Roles.ShouldContain(x => x.RoleId == _testData.RoleModeratorId); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task SetRoles_Should_Remove_Other_Roles() + [Fact] + public async Task SetRoles_Should_Remove_Other_Roles() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var roleSupporter = - await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("supporter")); - roleSupporter.ShouldNotBeNull(); + var roleSupporter = + await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("supporter")); + roleSupporter.ShouldNotBeNull(); - var user = await _identityUserRepository.FindByNormalizedUserNameAsync( - _lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _identityUserRepository.FindByNormalizedUserNameAsync( + _lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - var identityResult = await _identityUserManager.SetRolesAsync(user, new List() + var identityResult = await _identityUserManager.SetRolesAsync(user, new List() { "admin", }); - identityResult.Succeeded.ShouldBeTrue(); - user.Roles.ShouldNotContain(x => x.RoleId == _testData.RoleModeratorId); - user.Roles.ShouldNotContain(x => x.RoleId == roleSupporter.Id); + identityResult.Succeeded.ShouldBeTrue(); + user.Roles.ShouldNotContain(x => x.RoleId == _testData.RoleModeratorId); + user.Roles.ShouldNotContain(x => x.RoleId == roleSupporter.Id); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task SetOrganizationUnitsAsync() + [Fact] + public async Task SetOrganizationUnitsAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _identityUserRepository.FindByNormalizedUserNameAsync( - _lookupNormalizer.NormalizeName("david")); - user.ShouldNotBeNull(); + var user = await _identityUserRepository.FindByNormalizedUserNameAsync( + _lookupNormalizer.NormalizeName("david")); + user.ShouldNotBeNull(); - var ou = await _organizationUnitRepository.GetAsync( - _lookupNormalizer.NormalizeName("OU11")); - ou.ShouldNotBeNull(); + var ou = await _organizationUnitRepository.GetAsync( + _lookupNormalizer.NormalizeName("OU11")); + ou.ShouldNotBeNull(); - await _identityUserManager.SetOrganizationUnitsAsync(user, new Guid[] - { + await _identityUserManager.SetOrganizationUnitsAsync(user, new Guid[] + { ou.Id - }); + }); - user = await _identityUserRepository.FindByNormalizedUserNameAsync( - _lookupNormalizer.NormalizeName("david")); - user.OrganizationUnits.Count.ShouldBeGreaterThan(0); - user.OrganizationUnits.FirstOrDefault(uou => uou.OrganizationUnitId == ou.Id).ShouldNotBeNull(); + user = await _identityUserRepository.FindByNormalizedUserNameAsync( + _lookupNormalizer.NormalizeName("david")); + user.OrganizationUnits.Count.ShouldBeGreaterThan(0); + user.OrganizationUnits.FirstOrDefault(uou => uou.OrganizationUnitId == ou.Id).ShouldNotBeNull(); - await uow.CompleteAsync(); + await uow.CompleteAsync(); - } } + } - [Fact] - public async Task AddDefaultRolesAsync_In_Same_Uow() - { - await _identityOptions.SetAsync(); + [Fact] + public async Task AddDefaultRolesAsync_In_Same_Uow() + { + await _identityOptions.SetAsync(); - await CreateRandomDefaultRoleAsync(); + await CreateRandomDefaultRoleAsync(); - using (var uow = _unitOfWorkManager.Begin()) - { - var user = CreateRandomUser(); + using (var uow = _unitOfWorkManager.Begin()) + { + var user = CreateRandomUser(); - (await _identityUserManager.CreateAsync(user)).CheckErrors(); + (await _identityUserManager.CreateAsync(user)).CheckErrors(); - user.Roles.Count.ShouldBe(0); + user.Roles.Count.ShouldBe(0); - await _identityUserManager.AddDefaultRolesAsync(user); + await _identityUserManager.AddDefaultRolesAsync(user); - user.Roles.Count.ShouldBeGreaterThan(0); + user.Roles.Count.ShouldBeGreaterThan(0); - foreach (var roleId in user.Roles.Select(r => r.RoleId)) - { - var role = await _identityRoleRepository.GetAsync(roleId); - role.IsDefault.ShouldBe(true); - } + foreach (var roleId in user.Roles.Select(r => r.RoleId)) + { + var role = await _identityRoleRepository.GetAsync(roleId); + role.IsDefault.ShouldBe(true); + } - await uow.CompleteAsync(); + await uow.CompleteAsync(); - } } + } - [Fact] - public async Task SetOrganizationUnits_Should_Remove() + [Fact] + public async Task SetOrganizationUnits_Should_Remove() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var ou = await _organizationUnitRepository.GetAsync( - _lookupNormalizer.NormalizeName("OU111")); - ou.ShouldNotBeNull(); + var ou = await _organizationUnitRepository.GetAsync( + _lookupNormalizer.NormalizeName("OU111")); + ou.ShouldNotBeNull(); - var user = await _identityUserRepository.FindByNormalizedUserNameAsync( - _lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _identityUserRepository.FindByNormalizedUserNameAsync( + _lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - var ouNew = await _organizationUnitRepository.GetAsync( - _lookupNormalizer.NormalizeName("OU2")); - ouNew.ShouldNotBeNull(); + var ouNew = await _organizationUnitRepository.GetAsync( + _lookupNormalizer.NormalizeName("OU2")); + ouNew.ShouldNotBeNull(); - await _identityUserManager.SetOrganizationUnitsAsync(user, new Guid[] - { + await _identityUserManager.SetOrganizationUnitsAsync(user, new Guid[] + { ouNew.Id - }); + }); - user.OrganizationUnits.ShouldNotContain(x => x.OrganizationUnitId == ou.Id); + user.OrganizationUnits.ShouldNotContain(x => x.OrganizationUnitId == ou.Id); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task AddDefaultRolesAsync_In_Different_Uow() - { - await _identityOptions.SetAsync(); - - await CreateRandomDefaultRoleAsync(); + [Fact] + public async Task AddDefaultRolesAsync_In_Different_Uow() + { + await _identityOptions.SetAsync(); - Guid userId; + await CreateRandomDefaultRoleAsync(); - using (var uow = _unitOfWorkManager.Begin()) - { - var user = CreateRandomUser(); - userId = user.Id; + Guid userId; - (await _identityUserManager.CreateAsync(user)).CheckErrors(); - user.Roles.Count.ShouldBe(0); - await uow.CompleteAsync(); - } + using (var uow = _unitOfWorkManager.Begin()) + { + var user = CreateRandomUser(); + userId = user.Id; - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _identityUserManager.GetByIdAsync(userId); + (await _identityUserManager.CreateAsync(user)).CheckErrors(); + user.Roles.Count.ShouldBe(0); + await uow.CompleteAsync(); + } - await _identityUserManager.AddDefaultRolesAsync(user); - user.Roles.Count.ShouldBeGreaterThan(0); + using (var uow = _unitOfWorkManager.Begin()) + { + var user = await _identityUserManager.GetByIdAsync(userId); - foreach (var roleId in user.Roles.Select(r => r.RoleId)) - { - var role = await _identityRoleRepository.GetAsync(roleId); - role.IsDefault.ShouldBe(true); - } + await _identityUserManager.AddDefaultRolesAsync(user); + user.Roles.Count.ShouldBeGreaterThan(0); - await uow.CompleteAsync(); + foreach (var roleId in user.Roles.Select(r => r.RoleId)) + { + var role = await _identityRoleRepository.GetAsync(roleId); + role.IsDefault.ShouldBe(true); } - } - private async Task CreateRandomDefaultRoleAsync() - { - await _identityRoleRepository.InsertAsync( - new IdentityRole( - Guid.NewGuid(), - Guid.NewGuid().ToString() - ) - { - IsDefault = true - } - ); + await uow.CompleteAsync(); } + } - private static IdentityUser CreateRandomUser() - { - return new IdentityUser( + private async Task CreateRandomDefaultRoleAsync() + { + await _identityRoleRepository.InsertAsync( + new IdentityRole( Guid.NewGuid(), - Guid.NewGuid().ToString(), - Guid.NewGuid().ToString() + "@abp.io" - ); - } + Guid.NewGuid().ToString() + ) + { + IsDefault = true + } + ); + } + + private static IdentityUser CreateRandomUser() + { + return new IdentityUser( + Guid.NewGuid(), + Guid.NewGuid().ToString(), + Guid.NewGuid().ToString() + "@abp.io" + ); } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityUserStore_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityUserStore_Tests.cs index 6e84a88450..8b08732378 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityUserStore_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/IdentityUserStore_Tests.cs @@ -7,764 +7,763 @@ using Shouldly; using Volo.Abp.Uow; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityUserStore_Tests : AbpIdentityDomainTestBase { - public class IdentityUserStore_Tests : AbpIdentityDomainTestBase + private readonly IdentityUserStore _identityUserStore; + private readonly ILookupNormalizer _lookupNormalizer; + private readonly IIdentityUserRepository _userRepository; + private readonly IdentityTestData _testData; + private readonly IUnitOfWorkManager _unitOfWorkManager; + + public IdentityUserStore_Tests() { - private readonly IdentityUserStore _identityUserStore; - private readonly ILookupNormalizer _lookupNormalizer; - private readonly IIdentityUserRepository _userRepository; - private readonly IdentityTestData _testData; - private readonly IUnitOfWorkManager _unitOfWorkManager; + _identityUserStore = GetRequiredService(); + _lookupNormalizer = GetRequiredService(); + _userRepository = GetRequiredService(); + _testData = GetRequiredService(); + _unitOfWorkManager = GetRequiredService(); + } - public IdentityUserStore_Tests() - { - _identityUserStore = GetRequiredService(); - _lookupNormalizer = GetRequiredService(); - _userRepository = GetRequiredService(); - _testData = GetRequiredService(); - _unitOfWorkManager = GetRequiredService(); - } + [Fact] + public async Task GetUserIdAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - [Fact] - public async Task GetUserIdAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + (await _identityUserStore.GetUserIdAsync(user)).ShouldBe(user.Id.ToString()); + } - (await _identityUserStore.GetUserIdAsync(user)).ShouldBe(user.Id.ToString()); - } + [Fact] + public async Task GetUserNameAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - [Fact] - public async Task GetUserNameAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + (await _identityUserStore.GetUserNameAsync(user)).ShouldBe(user.UserName); + } - (await _identityUserStore.GetUserNameAsync(user)).ShouldBe(user.UserName); - } + [Fact] + public async Task SetUserNameAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - [Fact] - public async Task SetUserNameAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + await _identityUserStore.SetUserNameAsync(user, "bob.lee"); + user.UserName.ShouldBe("bob.lee"); + //user.NormalizedUserName.ShouldBe(_lookupNormalizer.Normalize("bob.lee")); + } - await _identityUserStore.SetUserNameAsync(user, "bob.lee"); - user.UserName.ShouldBe("bob.lee"); - //user.NormalizedUserName.ShouldBe(_lookupNormalizer.Normalize("bob.lee")); - } - - [Fact] - public async Task GetNormalizedUserNameAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetNormalizedUserNameAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetNormalizedUserNameAsync(user)).ShouldBe(user.NormalizedUserName); - } + (await _identityUserStore.GetNormalizedUserNameAsync(user)).ShouldBe(user.NormalizedUserName); + } - [Fact] - public async Task SetNormalizedUserNameAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task SetNormalizedUserNameAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.SetNormalizedUserNameAsync(user, _lookupNormalizer.NormalizeName("bob.lee")); + await _identityUserStore.SetNormalizedUserNameAsync(user, _lookupNormalizer.NormalizeName("bob.lee")); - user.NormalizedUserName.ShouldBe(_lookupNormalizer.NormalizeName("bob.lee")); - } + user.NormalizedUserName.ShouldBe(_lookupNormalizer.NormalizeName("bob.lee")); + } - [Fact] - public async Task CreateAsync() - { - var userId = Guid.NewGuid(); - var user = new IdentityUser(userId, "bob.lee", "bob.lee@abp.io"); + [Fact] + public async Task CreateAsync() + { + var userId = Guid.NewGuid(); + var user = new IdentityUser(userId, "bob.lee", "bob.lee@abp.io"); - await _identityUserStore.CreateAsync(user); + await _identityUserStore.CreateAsync(user); - var bobLee = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("bob.lee")); - bobLee.ShouldNotBeNull(); - bobLee.UserName.ShouldBe("bob.lee"); - bobLee.Email.ShouldBe("bob.lee@abp.io"); - } + var bobLee = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("bob.lee")); + bobLee.ShouldNotBeNull(); + bobLee.UserName.ShouldBe("bob.lee"); + bobLee.Email.ShouldBe("bob.lee@abp.io"); + } - [Fact] - public async Task UpdateAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task UpdateAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - user.Name = "lee"; - (await _identityUserStore.UpdateAsync(user)).Succeeded.ShouldBeTrue(); + user.Name = "lee"; + (await _identityUserStore.UpdateAsync(user)).Succeeded.ShouldBeTrue(); - (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash"))).Name - .ShouldBe("lee"); - } + (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash"))).Name + .ShouldBe("lee"); + } - [Fact] - public async Task Update_Concurrency() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task Update_Concurrency() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.UpdateAsync(user)).Succeeded.ShouldBeTrue(); + (await _identityUserStore.UpdateAsync(user)).Succeeded.ShouldBeTrue(); - user.ConcurrencyStamp = Guid.NewGuid().ToString(); - var identityResult = await _identityUserStore.UpdateAsync(user); + user.ConcurrencyStamp = Guid.NewGuid().ToString(); + var identityResult = await _identityUserStore.UpdateAsync(user); - identityResult.Succeeded.ShouldBeFalse(); - identityResult.Errors.ShouldContain(x => - x.Code == nameof(IdentityErrorDescriber.ConcurrencyFailure)); + identityResult.Succeeded.ShouldBeFalse(); + identityResult.Errors.ShouldContain(x => + x.Code == nameof(IdentityErrorDescriber.ConcurrencyFailure)); - // && x.Description == Resources.PasswordMismatch); - } + // && x.Description == Resources.PasswordMismatch); + } - [Fact] - public async Task DeleteAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task DeleteAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.DeleteAsync(user)).Succeeded.ShouldBeTrue(); + (await _identityUserStore.DeleteAsync(user)).Succeeded.ShouldBeTrue(); - (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash"))).ShouldBeNull(); - } + (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash"))).ShouldBeNull(); + } - [Fact] - public async Task FindByIdAsync() - { - var user = await _identityUserStore.FindByIdAsync(_testData.UserJohnId.ToString()); + [Fact] + public async Task FindByIdAsync() + { + var user = await _identityUserStore.FindByIdAsync(_testData.UserJohnId.ToString()); - user.ShouldNotBeNull(); - user.UserName.ShouldBe("john.nash"); - } + user.ShouldNotBeNull(); + user.UserName.ShouldBe("john.nash"); + } - [Fact] - public async Task FindByNameAsync() - { - var user = await _identityUserStore.FindByNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + [Fact] + public async Task FindByNameAsync() + { + var user = await _identityUserStore.FindByNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - user.UserName.ShouldBe("john.nash"); - } + user.ShouldNotBeNull(); + user.UserName.ShouldBe("john.nash"); + } - [Fact] - public async Task SetPasswordHashAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - user.PasswordHash.ShouldBeNull(); + [Fact] + public async Task SetPasswordHashAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + user.PasswordHash.ShouldBeNull(); - await _identityUserStore.SetPasswordHashAsync(user, "P@ssw0rd"); - user.PasswordHash.ShouldBe("P@ssw0rd"); - } + await _identityUserStore.SetPasswordHashAsync(user, "P@ssw0rd"); + user.PasswordHash.ShouldBe("P@ssw0rd"); + } - [Fact] - public async Task GetPasswordHashAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - await _identityUserStore.SetPasswordHashAsync(user, "P@ssw0rd"); + [Fact] + public async Task GetPasswordHashAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + await _identityUserStore.SetPasswordHashAsync(user, "P@ssw0rd"); - (await _identityUserStore.GetPasswordHashAsync(user)).ShouldBe("P@ssw0rd"); - } + (await _identityUserStore.GetPasswordHashAsync(user)).ShouldBe("P@ssw0rd"); + } - [Fact] - public async Task HasPasswordAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - (await _identityUserStore.HasPasswordAsync(user)).ShouldBeFalse(); + [Fact] + public async Task HasPasswordAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + (await _identityUserStore.HasPasswordAsync(user)).ShouldBeFalse(); - await _identityUserStore.SetPasswordHashAsync(user, "P@ssw0rd"); - (await _identityUserStore.HasPasswordAsync(user)).ShouldBeTrue(); - } + await _identityUserStore.SetPasswordHashAsync(user, "P@ssw0rd"); + (await _identityUserStore.HasPasswordAsync(user)).ShouldBeTrue(); + } - [Fact] - public async Task AddToRoleAsync() + [Fact] + public async Task AddToRoleAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("david")); - user.ShouldNotBeNull(); - user.Roles.ShouldBeEmpty(); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("david")); + user.ShouldNotBeNull(); + user.Roles.ShouldBeEmpty(); - await _identityUserStore.AddToRoleAsync(user, _lookupNormalizer.NormalizeName("moderator")); + await _identityUserStore.AddToRoleAsync(user, _lookupNormalizer.NormalizeName("moderator")); - user.Roles.ShouldContain(x => x.RoleId == _testData.RoleModeratorId); + user.Roles.ShouldContain(x => x.RoleId == _testData.RoleModeratorId); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task RemoveFromRoleAsync() + [Fact] + public async Task RemoveFromRoleAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - user.Roles.ShouldContain(x => x.RoleId == _testData.RoleModeratorId); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + user.Roles.ShouldContain(x => x.RoleId == _testData.RoleModeratorId); - await _identityUserStore.RemoveFromRoleAsync(user, _lookupNormalizer.NormalizeName("moderator")); + await _identityUserStore.RemoveFromRoleAsync(user, _lookupNormalizer.NormalizeName("moderator")); - user.Roles.ShouldNotContain(x => x.RoleId == _testData.RoleModeratorId); + user.Roles.ShouldNotContain(x => x.RoleId == _testData.RoleModeratorId); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task GetRolesAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetRolesAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - var roleNames = await _identityUserStore.GetRolesAsync(user); - roleNames.ShouldNotBeEmpty(); - roleNames.ShouldContain(x => x == "moderator"); - roleNames.ShouldContain(x => x == "supporter"); - } + var roleNames = await _identityUserStore.GetRolesAsync(user); + roleNames.ShouldNotBeEmpty(); + roleNames.ShouldContain(x => x == "moderator"); + roleNames.ShouldContain(x => x == "supporter"); + } - [Fact] - public async Task IsInRoleAsync() + [Fact] + public async Task IsInRoleAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.IsInRoleAsync(user, _lookupNormalizer.NormalizeName("moderator"))).ShouldBeTrue(); - (await _identityUserStore.IsInRoleAsync(user, _lookupNormalizer.NormalizeName("moderatorNotExist"))).ShouldBeFalse(); + (await _identityUserStore.IsInRoleAsync(user, _lookupNormalizer.NormalizeName("moderator"))).ShouldBeTrue(); + (await _identityUserStore.IsInRoleAsync(user, _lookupNormalizer.NormalizeName("moderatorNotExist"))).ShouldBeFalse(); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task GetClaimsAsync() + [Fact] + public async Task GetClaimsAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - var claims = await _identityUserStore.GetClaimsAsync(user); - claims.ShouldNotBeEmpty(); - claims.ShouldContain(x => x.Type == "TestClaimType" && x.Value == "42"); + var claims = await _identityUserStore.GetClaimsAsync(user); + claims.ShouldNotBeEmpty(); + claims.ShouldContain(x => x.Type == "TestClaimType" && x.Value == "42"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task AddClaimsAsync() + [Fact] + public async Task AddClaimsAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - user.Claims.ShouldNotContain(x => x.ClaimType == "MyClaimType" && x.ClaimValue == "MyClaimValue"); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + user.Claims.ShouldNotContain(x => x.ClaimType == "MyClaimType" && x.ClaimValue == "MyClaimValue"); - await _identityUserStore.AddClaimsAsync(user, new List() + await _identityUserStore.AddClaimsAsync(user, new List() { new Claim("MyClaimType", "MyClaimValue") }); - user.Claims.ShouldContain(x => x.ClaimType == "MyClaimType" && x.ClaimValue == "MyClaimValue"); + user.Claims.ShouldContain(x => x.ClaimType == "MyClaimType" && x.ClaimValue == "MyClaimValue"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task ReplaceClaimAsync() + [Fact] + public async Task ReplaceClaimAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.ReplaceClaimAsync(user, new Claim("TestClaimType", "42"), new Claim("MyClaimType", "MyClaimValue")); + await _identityUserStore.ReplaceClaimAsync(user, new Claim("TestClaimType", "42"), new Claim("MyClaimType", "MyClaimValue")); - user.Claims.ShouldNotContain(x => x.ClaimType == "TestClaimType" && x.ClaimValue == "42"); - user.Claims.ShouldContain(x => x.ClaimType == "MyClaimType" && x.ClaimValue == "MyClaimValue"); + user.Claims.ShouldNotContain(x => x.ClaimType == "TestClaimType" && x.ClaimValue == "42"); + user.Claims.ShouldContain(x => x.ClaimType == "MyClaimType" && x.ClaimValue == "MyClaimValue"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } - - [Fact] - public async Task RemoveClaimsAsync() + } + + [Fact] + public async Task RemoveClaimsAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.RemoveClaimsAsync(user, new List() + await _identityUserStore.RemoveClaimsAsync(user, new List() { new Claim("TestClaimType", "42") }); - user.Claims.ShouldNotContain(x => x.ClaimType == "TestClaimType" && x.ClaimValue == "42"); + user.Claims.ShouldNotContain(x => x.ClaimType == "TestClaimType" && x.ClaimValue == "42"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task AddLoginAsync() + [Fact] + public async Task AddLoginAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - user.Logins.ShouldNotContain(x => x.LoginProvider == "facebook" && x.ProviderKey == "john"); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + user.Logins.ShouldNotContain(x => x.LoginProvider == "facebook" && x.ProviderKey == "john"); - await _identityUserStore.AddLoginAsync(user, new UserLoginInfo("facebook", "john", "John Nash")); + await _identityUserStore.AddLoginAsync(user, new UserLoginInfo("facebook", "john", "John Nash")); - user.Logins.ShouldContain(x => x.LoginProvider == "facebook" && x.ProviderKey == "john"); + user.Logins.ShouldContain(x => x.LoginProvider == "facebook" && x.ProviderKey == "john"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task RemoveLoginAsync() + [Fact] + public async Task RemoveLoginAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - user.Logins.ShouldContain(x => x.LoginProvider == "github" && x.ProviderKey == "john"); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + user.Logins.ShouldContain(x => x.LoginProvider == "github" && x.ProviderKey == "john"); - await _identityUserStore.RemoveLoginAsync(user, "github", "john"); + await _identityUserStore.RemoveLoginAsync(user, "github", "john"); - user.Logins.ShouldNotContain(x => x.LoginProvider == "github" && x.ProviderKey == "john"); + user.Logins.ShouldNotContain(x => x.LoginProvider == "github" && x.ProviderKey == "john"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task GetLoginsAsync() + [Fact] + public async Task GetLoginsAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - var logins = await _identityUserStore.GetLoginsAsync(user); + var logins = await _identityUserStore.GetLoginsAsync(user); - logins.ShouldNotBeNull(); - logins.ShouldContain(x => x.LoginProvider == "github" && x.ProviderKey == "john"); - logins.ShouldContain(x => x.LoginProvider == "twitter" && x.ProviderKey == "johnx"); + logins.ShouldNotBeNull(); + logins.ShouldContain(x => x.LoginProvider == "github" && x.ProviderKey == "john"); + logins.ShouldContain(x => x.LoginProvider == "twitter" && x.ProviderKey == "johnx"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task FindByLoginAsync() - { - var user = await _identityUserStore.FindByLoginAsync("github", "john"); - user.ShouldNotBeNull(); - user.UserName.ShouldBe("john.nash"); - } + [Fact] + public async Task FindByLoginAsync() + { + var user = await _identityUserStore.FindByLoginAsync("github", "john"); + user.ShouldNotBeNull(); + user.UserName.ShouldBe("john.nash"); + } - [Fact] - public async Task GetEmailConfirmedAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetEmailConfirmedAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetEmailConfirmedAsync(user)).ShouldBe(user.EmailConfirmed); - } + (await _identityUserStore.GetEmailConfirmedAsync(user)).ShouldBe(user.EmailConfirmed); + } - [Fact] - public async Task SetEmailConfirmedAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - var emailConfirmed = user.EmailConfirmed; + [Fact] + public async Task SetEmailConfirmedAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + var emailConfirmed = user.EmailConfirmed; - await _identityUserStore.SetEmailConfirmedAsync(user, !emailConfirmed); + await _identityUserStore.SetEmailConfirmedAsync(user, !emailConfirmed); - user.EmailConfirmed.ShouldBe(!emailConfirmed); - } + user.EmailConfirmed.ShouldBe(!emailConfirmed); + } - [Fact] - public async Task SetEmailAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task SetEmailAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.SetEmailAsync(user, "john.nash.kobe@abp.io"); + await _identityUserStore.SetEmailAsync(user, "john.nash.kobe@abp.io"); - user.Email.ShouldBe("john.nash.kobe@abp.io"); - //user.NormalizedEmail.ShouldBe(_lookupNormalizer.Normalize("john.nash.kobe@abp.io")); - } + user.Email.ShouldBe("john.nash.kobe@abp.io"); + //user.NormalizedEmail.ShouldBe(_lookupNormalizer.Normalize("john.nash.kobe@abp.io")); + } - [Fact] - public async Task GetEmailAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetEmailAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetEmailAsync(user)).ShouldBe(user.Email); - } + (await _identityUserStore.GetEmailAsync(user)).ShouldBe(user.Email); + } - [Fact] - public async Task GetNormalizedEmailAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetNormalizedEmailAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetNormalizedEmailAsync(user)).ShouldBe(user.NormalizedEmail); - } + (await _identityUserStore.GetNormalizedEmailAsync(user)).ShouldBe(user.NormalizedEmail); + } - [Fact] - public async Task SetNormalizedEmailAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task SetNormalizedEmailAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.SetNormalizedEmailAsync(user, _lookupNormalizer.NormalizeEmail("john.nash.kobe@abp.io")); + await _identityUserStore.SetNormalizedEmailAsync(user, _lookupNormalizer.NormalizeEmail("john.nash.kobe@abp.io")); - user.NormalizedEmail.ShouldBe(_lookupNormalizer.NormalizeEmail("john.nash.kobe@abp.io")); - } + user.NormalizedEmail.ShouldBe(_lookupNormalizer.NormalizeEmail("john.nash.kobe@abp.io")); + } - [Fact] - public async Task FindByEmailAsync() - { - var user = await _identityUserStore.FindByEmailAsync(_lookupNormalizer.NormalizeEmail("john.nash@abp.io")); + [Fact] + public async Task FindByEmailAsync() + { + var user = await _identityUserStore.FindByEmailAsync(_lookupNormalizer.NormalizeEmail("john.nash@abp.io")); - user.ShouldNotBeNull(); - user.Email.ShouldBe("john.nash@abp.io"); - } + user.ShouldNotBeNull(); + user.Email.ShouldBe("john.nash@abp.io"); + } - [Fact] - public async Task GetLockoutEndDateAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetLockoutEndDateAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetLockoutEndDateAsync(user)).ShouldBe(user.LockoutEnd); - } + (await _identityUserStore.GetLockoutEndDateAsync(user)).ShouldBe(user.LockoutEnd); + } - [Fact] - public async Task SetLockoutEndDateAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task SetLockoutEndDateAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.SetLockoutEndDateAsync(user, DateTimeOffset.Parse("01/01/2019")); + await _identityUserStore.SetLockoutEndDateAsync(user, DateTimeOffset.Parse("01/01/2019")); - user.LockoutEnd.ShouldBe(DateTimeOffset.Parse("01/01/2019")); - } + user.LockoutEnd.ShouldBe(DateTimeOffset.Parse("01/01/2019")); + } - [Fact] - public async Task IncrementAccessFailedCountAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - var count = user.AccessFailedCount; + [Fact] + public async Task IncrementAccessFailedCountAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + var count = user.AccessFailedCount; - await _identityUserStore.IncrementAccessFailedCountAsync(user); + await _identityUserStore.IncrementAccessFailedCountAsync(user); - user.AccessFailedCount.ShouldBe(count + 1); - } + user.AccessFailedCount.ShouldBe(count + 1); + } - [Fact] - public async Task ResetAccessFailedCountAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task ResetAccessFailedCountAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.ResetAccessFailedCountAsync(user); + await _identityUserStore.ResetAccessFailedCountAsync(user); - user.AccessFailedCount.ShouldBe(0); - } + user.AccessFailedCount.ShouldBe(0); + } - [Fact] - public async Task GetAccessFailedCountAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetAccessFailedCountAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetAccessFailedCountAsync(user)).ShouldBe(user.AccessFailedCount); - } + (await _identityUserStore.GetAccessFailedCountAsync(user)).ShouldBe(user.AccessFailedCount); + } - [Fact] - public async Task GetLockoutEnabledAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetLockoutEnabledAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetLockoutEnabledAsync(user)).ShouldBe(user.LockoutEnabled); - } + (await _identityUserStore.GetLockoutEnabledAsync(user)).ShouldBe(user.LockoutEnabled); + } - [Fact] - public async Task SetLockoutEnabledAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - var lockoutEnabled = user.LockoutEnabled; + [Fact] + public async Task SetLockoutEnabledAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + var lockoutEnabled = user.LockoutEnabled; - await _identityUserStore.SetLockoutEnabledAsync(user, !lockoutEnabled); + await _identityUserStore.SetLockoutEnabledAsync(user, !lockoutEnabled); - user.LockoutEnabled.ShouldBe(!lockoutEnabled); - } + user.LockoutEnabled.ShouldBe(!lockoutEnabled); + } - [Fact] - public async Task SetPhoneNumberAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task SetPhoneNumberAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.SetPhoneNumberAsync(user, "13800138000"); + await _identityUserStore.SetPhoneNumberAsync(user, "13800138000"); - user.PhoneNumber.ShouldBe("13800138000"); - } + user.PhoneNumber.ShouldBe("13800138000"); + } - [Fact] - public async Task GetPhoneNumberAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetPhoneNumberAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetPhoneNumberAsync(user)).ShouldBe(user.PhoneNumber); - } + (await _identityUserStore.GetPhoneNumberAsync(user)).ShouldBe(user.PhoneNumber); + } - [Fact] - public async Task GetPhoneNumberConfirmedAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetPhoneNumberConfirmedAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetPhoneNumberConfirmedAsync(user)).ShouldBe(user.PhoneNumberConfirmed); - } + (await _identityUserStore.GetPhoneNumberConfirmedAsync(user)).ShouldBe(user.PhoneNumberConfirmed); + } - [Fact] - public async Task SetPhoneNumberConfirmedAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - var phoneNumberConfirmed = user.PhoneNumberConfirmed; + [Fact] + public async Task SetPhoneNumberConfirmedAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + var phoneNumberConfirmed = user.PhoneNumberConfirmed; - await _identityUserStore.SetPhoneNumberConfirmedAsync(user, !phoneNumberConfirmed); + await _identityUserStore.SetPhoneNumberConfirmedAsync(user, !phoneNumberConfirmed); - user.PhoneNumberConfirmed.ShouldBe(!phoneNumberConfirmed); - } + user.PhoneNumberConfirmed.ShouldBe(!phoneNumberConfirmed); + } - [Fact] - public async Task SetSecurityStampAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - var securityStamp = Guid.NewGuid().ToString(); + [Fact] + public async Task SetSecurityStampAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + var securityStamp = Guid.NewGuid().ToString(); - await _identityUserStore.SetSecurityStampAsync(user, securityStamp); + await _identityUserStore.SetSecurityStampAsync(user, securityStamp); - user.SecurityStamp.ShouldBe(securityStamp); - } + user.SecurityStamp.ShouldBe(securityStamp); + } - [Fact] - public async Task GetSecurityStampAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetSecurityStampAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetSecurityStampAsync(user)).ShouldBe(user.SecurityStamp); - } + (await _identityUserStore.GetSecurityStampAsync(user)).ShouldBe(user.SecurityStamp); + } - [Fact] - public async Task SetTwoFactorEnabledAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - var twoFactorEnabled = user.TwoFactorEnabled; + [Fact] + public async Task SetTwoFactorEnabledAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + var twoFactorEnabled = user.TwoFactorEnabled; - await _identityUserStore.SetTwoFactorEnabledAsync(user, !twoFactorEnabled); + await _identityUserStore.SetTwoFactorEnabledAsync(user, !twoFactorEnabled); - user.TwoFactorEnabled.ShouldBe(!twoFactorEnabled); - } + user.TwoFactorEnabled.ShouldBe(!twoFactorEnabled); + } - [Fact] - public async Task GetTwoFactorEnabledAsync() - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + [Fact] + public async Task GetTwoFactorEnabledAsync() + { + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetTwoFactorEnabledAsync(user)).ShouldBe(user.TwoFactorEnabled); - } + (await _identityUserStore.GetTwoFactorEnabledAsync(user)).ShouldBe(user.TwoFactorEnabled); + } - [Fact] - public async Task GetUsersForClaimAsync() - { - var user = await _identityUserStore.GetUsersForClaimAsync(new Claim("TestClaimType", "42")); - user.ShouldNotBeNull(); - user.ShouldNotBeEmpty(); - user.ShouldContain(x => x.UserName == "john.nash"); - } + [Fact] + public async Task GetUsersForClaimAsync() + { + var user = await _identityUserStore.GetUsersForClaimAsync(new Claim("TestClaimType", "42")); + user.ShouldNotBeNull(); + user.ShouldNotBeEmpty(); + user.ShouldContain(x => x.UserName == "john.nash"); + } - [Fact] - public async Task GetUsersInRoleAsync() - { - var user = await _identityUserStore.GetUsersInRoleAsync(_lookupNormalizer.NormalizeName("moderator")); - user.ShouldNotBeNull(); - user.ShouldContain(x => x.UserName == "john.nash"); - } + [Fact] + public async Task GetUsersInRoleAsync() + { + var user = await _identityUserStore.GetUsersInRoleAsync(_lookupNormalizer.NormalizeName("moderator")); + user.ShouldNotBeNull(); + user.ShouldContain(x => x.UserName == "john.nash"); + } - [Fact] - public async Task SetTokenAsync() + [Fact] + public async Task SetTokenAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.SetTokenAsync(user, "test-provider", "test-name", "123123"); + await _identityUserStore.SetTokenAsync(user, "test-provider", "test-name", "123123"); - user.Tokens.ShouldNotBeEmpty(); - user.Tokens.ShouldContain(x => x.LoginProvider == "test-provider" && x.Name == "test-name" && x.Value == "123123"); + user.Tokens.ShouldNotBeEmpty(); + user.Tokens.ShouldContain(x => x.LoginProvider == "test-provider" && x.Name == "test-name" && x.Value == "123123"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task RemoveTokenAsync() + [Fact] + public async Task RemoveTokenAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.RemoveTokenAsync(user, "test-provider", "test-name"); + await _identityUserStore.RemoveTokenAsync(user, "test-provider", "test-name"); - user.Tokens.ShouldNotContain(x => x.LoginProvider == "test-provider" && x.Name == "test-name" && x.Value == "123123"); + user.Tokens.ShouldNotContain(x => x.LoginProvider == "test-provider" && x.Name == "test-name" && x.Value == "123123"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task GetTokenAsync() + [Fact] + public async Task GetTokenAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - (await _identityUserStore.GetTokenAsync(user, "test-provider", "test-name")).ShouldBe("test-value"); + (await _identityUserStore.GetTokenAsync(user, "test-provider", "test-name")).ShouldBe("test-value"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task SetAuthenticatorKeyAsync() + [Fact] + public async Task SetAuthenticatorKeyAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.SetAuthenticatorKeyAsync(user, "testKey"); + await _identityUserStore.SetAuthenticatorKeyAsync(user, "testKey"); - user.Tokens.ShouldContain(x => x.LoginProvider == "[AspNetUserStore]" && x.Name == "AuthenticatorKey" && x.Value == "testKey"); + user.Tokens.ShouldContain(x => x.LoginProvider == "[AspNetUserStore]" && x.Name == "AuthenticatorKey" && x.Value == "testKey"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task GetAuthenticatorKeyAsync() + [Fact] + public async Task GetAuthenticatorKeyAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - await _identityUserStore.SetAuthenticatorKeyAsync(user, "testKey"); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + await _identityUserStore.SetAuthenticatorKeyAsync(user, "testKey"); - (await _identityUserStore.GetAuthenticatorKeyAsync(user)).ShouldBe("testKey"); + (await _identityUserStore.GetAuthenticatorKeyAsync(user)).ShouldBe("testKey"); - await uow.CompleteAsync(); - } - + await uow.CompleteAsync(); } - [Fact] - public async Task CountCodesAsync() + } + + [Fact] + public async Task CountCodesAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - await _identityUserStore.SetTokenAsync(user, "[AspNetUserStore]", "RecoveryCodes", "testKey;testKey2"); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + await _identityUserStore.SetTokenAsync(user, "[AspNetUserStore]", "RecoveryCodes", "testKey;testKey2"); - (await _identityUserStore.CountCodesAsync(user)).ShouldBe(2); + (await _identityUserStore.CountCodesAsync(user)).ShouldBe(2); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task ReplaceCodesAsync() + [Fact] + public async Task ReplaceCodesAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); - await _identityUserStore.ReplaceCodesAsync(user, new List() + await _identityUserStore.ReplaceCodesAsync(user, new List() { "testKey", "testKey2" }); - user.Tokens.ShouldContain(x => x.LoginProvider == "[AspNetUserStore]" && x.Name == "RecoveryCodes" && x.Value == "testKey;testKey2"); + user.Tokens.ShouldContain(x => x.LoginProvider == "[AspNetUserStore]" && x.Name == "RecoveryCodes" && x.Value == "testKey;testKey2"); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task RedeemCodeAsync() + [Fact] + public async Task RedeemCodeAsync() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); - user.ShouldNotBeNull(); - await _identityUserStore.SetTokenAsync(user, "[AspNetUserStore]", "RecoveryCodes", "testKey;testKey2"); + var user = await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("john.nash")); + user.ShouldNotBeNull(); + await _identityUserStore.SetTokenAsync(user, "[AspNetUserStore]", "RecoveryCodes", "testKey;testKey2"); - (await _identityUserStore.RedeemCodeAsync(user, "testKey")).ShouldBeTrue(); + (await _identityUserStore.RedeemCodeAsync(user, "testKey")).ShouldBeTrue(); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Localization_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Localization_Tests.cs index 2a3c870eb3..14864e3d59 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Localization_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/Localization_Tests.cs @@ -4,22 +4,21 @@ using Volo.Abp.Identity; using Volo.Abp.Identity.Localization; using Xunit; -namespace Volo.Abp.TenantManagement +namespace Volo.Abp.TenantManagement; + +public class Localization_Tests : AbpIdentityDomainTestBase { - public class Localization_Tests : AbpIdentityDomainTestBase - { - private readonly IStringLocalizer _stringLocalizer; + private readonly IStringLocalizer _stringLocalizer; - public Localization_Tests() - { - _stringLocalizer = GetRequiredService>(); - } + public Localization_Tests() + { + _stringLocalizer = GetRequiredService>(); + } - [Fact] - public void Test() - { - _stringLocalizer["PersonalSettingsSavedMessage"].Value - .ShouldBe("Your personal settings has been saved successfully."); - } + [Fact] + public void Test() + { + _stringLocalizer["PersonalSettingsSavedMessage"].Value + .ShouldBe("Your personal settings has been saved successfully."); } -} \ No newline at end of file +} diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/OrganizationUnitManager_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/OrganizationUnitManager_Tests.cs index 2f9ac794ac..5b6ed9af27 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/OrganizationUnitManager_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/OrganizationUnitManager_Tests.cs @@ -6,116 +6,115 @@ using Volo.Abp.Guids; using Volo.Abp.Uow; using Xunit; -namespace Volo.Abp.Identity -{ - public class OrganizationUnitManager_Tests : AbpIdentityDomainTestBase - { - private readonly OrganizationUnitManager _organizationUnitManager; - private readonly IOrganizationUnitRepository _organizationUnitRepository; - private readonly IdentityTestData _testData; - private readonly IIdentityRoleRepository _identityRoleRepository; - private readonly ILookupNormalizer _lookupNormalizer; - private readonly IUnitOfWorkManager _unitOfWorkManager; - private readonly IGuidGenerator _guidGenerator; - public OrganizationUnitManager_Tests() - { - _organizationUnitManager = GetRequiredService(); - _organizationUnitRepository = GetRequiredService(); - _identityRoleRepository = GetRequiredService(); - _lookupNormalizer = GetRequiredService(); - _testData = GetRequiredService(); - _unitOfWorkManager = GetRequiredService(); - _guidGenerator = GetService(); - } - - [Fact] - public async Task CreateAsnyc() - { - await _organizationUnitManager.CreateAsync(new OrganizationUnit(_guidGenerator.Create(), "Root 1")); - - var root1 = await _organizationUnitRepository.GetAsync("Root 1"); - root1.ShouldNotBeNull(); - } - - [Fact] - public async Task UpdateAsync() - { - var ou = await _organizationUnitRepository.GetAsync("OU111"); - ou.DisplayName = "OU111 Updated"; - await _organizationUnitManager.UpdateAsync(ou); - - var ouAfterChange = await _organizationUnitRepository.GetAsync("OU111 Updated"); - ouAfterChange.DisplayName.ShouldContain("OU111 Updated"); - } - - [Fact] - public async Task DeleteAsync() - { - var ou = await _organizationUnitRepository.GetAsync("OU11"); - await _organizationUnitManager.DeleteAsync(ou.Id); - - (await _organizationUnitRepository.GetAsync("OU11")).ShouldBeNull(); - } - - [Fact] - public async Task MoveAsync() - { - var ou1 = await _organizationUnitRepository.GetAsync("OU1"); - var ou2 = await _organizationUnitRepository.GetAsync("OU2"); - - await _organizationUnitManager.MoveAsync(ou1.Id, ou2.Id); - - ou1 = await _organizationUnitRepository.GetAsync("OU1"); - ou1.ParentId.ShouldBe(ou2.Id); - ou1.Code.ShouldBe(OrganizationUnit.CreateCode(2, 2)); - - var ou11 = await _organizationUnitRepository.GetAsync("OU11"); - ou11.ParentId.ShouldBe(ou1.Id); - ou11.Code.ShouldBe(OrganizationUnit.CreateCode(2, 2, 1)); - - var ou111 = await _organizationUnitRepository.GetAsync("OU111"); - ou111.ParentId.ShouldBe(ou11.Id); - ou111.Code.ShouldBe(OrganizationUnit.CreateCode(2, 2, 1, 1)); - - var ou112 = await _organizationUnitRepository.GetAsync("OU112"); - ou112.ParentId.ShouldBe(ou11.Id); - ou112.Code.ShouldBe(OrganizationUnit.CreateCode(2, 2, 1, 2)); - - var ou12 = await _organizationUnitRepository.GetAsync("OU12"); - ou12.ParentId.ShouldBe(ou1.Id); - ou12.Code.ShouldBe(OrganizationUnit.CreateCode(2, 2, 2)); - } - - [Fact] - public async Task AddRoleToOrganizationUnitAsync() - { - OrganizationUnit ou = null; - IdentityRole adminRole = null; - - using (var uow = _unitOfWorkManager.Begin()) - { - ou = await _organizationUnitRepository.GetAsync("OU1", true); - adminRole = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin")); - await _organizationUnitManager.AddRoleToOrganizationUnitAsync(adminRole, ou); - await _organizationUnitRepository.UpdateAsync(ou); - - await uow.CompleteAsync(); - } - - ou = await _organizationUnitRepository.GetAsync("OU1", includeDetails: true); - ou.Roles.First().RoleId.ShouldBe(adminRole.Id); - } - - [Fact] - public async Task RemoveRoleFromOrganizationUnitAsync() - { - var ou = await _organizationUnitRepository.GetAsync("OU1", true); - var adminRole = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin")); - await _organizationUnitManager.AddRoleToOrganizationUnitAsync(adminRole.Id, ou.Id); - - await _organizationUnitManager.RemoveRoleFromOrganizationUnitAsync(adminRole.Id, ou.Id); - ou = await _organizationUnitRepository.GetAsync("OU1", includeDetails: true); - ou.Roles.FirstOrDefault(r => r.RoleId == adminRole.Id).ShouldBeNull(); - } - } +namespace Volo.Abp.Identity; + +public class OrganizationUnitManager_Tests : AbpIdentityDomainTestBase +{ + private readonly OrganizationUnitManager _organizationUnitManager; + private readonly IOrganizationUnitRepository _organizationUnitRepository; + private readonly IdentityTestData _testData; + private readonly IIdentityRoleRepository _identityRoleRepository; + private readonly ILookupNormalizer _lookupNormalizer; + private readonly IUnitOfWorkManager _unitOfWorkManager; + private readonly IGuidGenerator _guidGenerator; + public OrganizationUnitManager_Tests() + { + _organizationUnitManager = GetRequiredService(); + _organizationUnitRepository = GetRequiredService(); + _identityRoleRepository = GetRequiredService(); + _lookupNormalizer = GetRequiredService(); + _testData = GetRequiredService(); + _unitOfWorkManager = GetRequiredService(); + _guidGenerator = GetService(); + } + + [Fact] + public async Task CreateAsnyc() + { + await _organizationUnitManager.CreateAsync(new OrganizationUnit(_guidGenerator.Create(), "Root 1")); + + var root1 = await _organizationUnitRepository.GetAsync("Root 1"); + root1.ShouldNotBeNull(); + } + + [Fact] + public async Task UpdateAsync() + { + var ou = await _organizationUnitRepository.GetAsync("OU111"); + ou.DisplayName = "OU111 Updated"; + await _organizationUnitManager.UpdateAsync(ou); + + var ouAfterChange = await _organizationUnitRepository.GetAsync("OU111 Updated"); + ouAfterChange.DisplayName.ShouldContain("OU111 Updated"); + } + + [Fact] + public async Task DeleteAsync() + { + var ou = await _organizationUnitRepository.GetAsync("OU11"); + await _organizationUnitManager.DeleteAsync(ou.Id); + + (await _organizationUnitRepository.GetAsync("OU11")).ShouldBeNull(); + } + + [Fact] + public async Task MoveAsync() + { + var ou1 = await _organizationUnitRepository.GetAsync("OU1"); + var ou2 = await _organizationUnitRepository.GetAsync("OU2"); + + await _organizationUnitManager.MoveAsync(ou1.Id, ou2.Id); + + ou1 = await _organizationUnitRepository.GetAsync("OU1"); + ou1.ParentId.ShouldBe(ou2.Id); + ou1.Code.ShouldBe(OrganizationUnit.CreateCode(2, 2)); + + var ou11 = await _organizationUnitRepository.GetAsync("OU11"); + ou11.ParentId.ShouldBe(ou1.Id); + ou11.Code.ShouldBe(OrganizationUnit.CreateCode(2, 2, 1)); + + var ou111 = await _organizationUnitRepository.GetAsync("OU111"); + ou111.ParentId.ShouldBe(ou11.Id); + ou111.Code.ShouldBe(OrganizationUnit.CreateCode(2, 2, 1, 1)); + + var ou112 = await _organizationUnitRepository.GetAsync("OU112"); + ou112.ParentId.ShouldBe(ou11.Id); + ou112.Code.ShouldBe(OrganizationUnit.CreateCode(2, 2, 1, 2)); + + var ou12 = await _organizationUnitRepository.GetAsync("OU12"); + ou12.ParentId.ShouldBe(ou1.Id); + ou12.Code.ShouldBe(OrganizationUnit.CreateCode(2, 2, 2)); + } + + [Fact] + public async Task AddRoleToOrganizationUnitAsync() + { + OrganizationUnit ou = null; + IdentityRole adminRole = null; + + using (var uow = _unitOfWorkManager.Begin()) + { + ou = await _organizationUnitRepository.GetAsync("OU1", true); + adminRole = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin")); + await _organizationUnitManager.AddRoleToOrganizationUnitAsync(adminRole, ou); + await _organizationUnitRepository.UpdateAsync(ou); + + await uow.CompleteAsync(); + } + + ou = await _organizationUnitRepository.GetAsync("OU1", includeDetails: true); + ou.Roles.First().RoleId.ShouldBe(adminRole.Id); + } + + [Fact] + public async Task RemoveRoleFromOrganizationUnitAsync() + { + var ou = await _organizationUnitRepository.GetAsync("OU1", true); + var adminRole = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin")); + await _organizationUnitManager.AddRoleToOrganizationUnitAsync(adminRole.Id, ou.Id); + + await _organizationUnitManager.RemoveRoleFromOrganizationUnitAsync(adminRole.Id, ou.Id); + ou = await _organizationUnitRepository.GetAsync("OU1", includeDetails: true); + ou.Roles.FirstOrDefault(r => r.RoleId == adminRole.Id).ShouldBeNull(); + } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/PermissionManager_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/PermissionManager_Tests.cs index 621cb4621f..e0cfe2169c 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/PermissionManager_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/PermissionManager_Tests.cs @@ -7,114 +7,113 @@ using Volo.Abp.Authorization.Permissions; using Volo.Abp.PermissionManagement; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class PermissionManager_Tests : AbpIdentityDomainTestBase { - public class PermissionManager_Tests : AbpIdentityDomainTestBase + private readonly IPermissionManager _permissionManager; + private readonly IPermissionStore _permissionStore; + + public PermissionManager_Tests() + { + _permissionManager = GetRequiredService(); + _permissionStore = GetRequiredService(); + } + + [Fact] + public async Task Roles_Should_Have_Configured_Permissions() + { + //admin + var grantInfos = await _permissionManager.GetAllForRoleAsync("admin"); + RoleShouldHavePermission(grantInfos, "admin", TestPermissionNames.MyPermission1); + RoleShouldHavePermission(grantInfos, "admin", TestPermissionNames.MyPermission2); + RoleShouldHavePermission(grantInfos, "admin", TestPermissionNames.MyPermission2_ChildPermission1); + + //moderator + grantInfos = await _permissionManager.GetAllForRoleAsync("moderator"); + RoleShouldHavePermission(grantInfos, "moderator", TestPermissionNames.MyPermission1); + RoleShouldHavePermission(grantInfos, "moderator", TestPermissionNames.MyPermission2); + ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2_ChildPermission1); + + //supporter + grantInfos = await _permissionManager.GetAllForRoleAsync("supporter"); + RoleShouldHavePermission(grantInfos, "supporter", TestPermissionNames.MyPermission1); + ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2); + ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2_ChildPermission1); + } + + [Fact] + public async Task Should_Grant_Permission_To_Role() + { + (await _permissionManager.GetForRoleAsync("supporter", TestPermissionNames.MyPermission2)).IsGranted.ShouldBeFalse(); + (await _permissionStore.IsGrantedAsync(TestPermissionNames.MyPermission2, RolePermissionValueProvider.ProviderName, "supporter")).ShouldBeFalse(); + + await _permissionManager.SetForRoleAsync("supporter", TestPermissionNames.MyPermission2, true); + + (await _permissionManager.GetForRoleAsync("supporter", TestPermissionNames.MyPermission2)).IsGranted.ShouldBeTrue(); + (await _permissionStore.IsGrantedAsync(TestPermissionNames.MyPermission2, RolePermissionValueProvider.ProviderName, "supporter")).ShouldBeTrue(); + } + + [Fact] + public async Task Should_Revoke_Permission_From_Role() + { + (await _permissionManager.GetForRoleAsync("moderator", TestPermissionNames.MyPermission1)).IsGranted.ShouldBeTrue(); + await _permissionManager.SetForRoleAsync("moderator", TestPermissionNames.MyPermission1, false); + (await _permissionManager.GetForRoleAsync("moderator", TestPermissionNames.MyPermission1)).IsGranted.ShouldBeFalse(); + } + + [Fact] + public async Task Users_Should_Have_Configured_Values() + { + //administrator + var user = GetUser("administrator"); + var grantInfos = await _permissionManager.GetAllForUserAsync(user.Id); + UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission1, "admin"); + UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission2, "admin"); + UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission2_ChildPermission1, "admin"); + + //john.nash + user = GetUser("john.nash"); + grantInfos = await _permissionManager.GetAllForUserAsync(user.Id); + UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission1, "moderator", "supporter"); + UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission2, "moderator"); + ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2_ChildPermission1); + + //john.nash + user = GetUser("david"); + grantInfos = await _permissionManager.GetAllForUserAsync(user.Id); + UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission1); + ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2); + ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2_ChildPermission1); + } + + private static void RoleShouldHavePermission(List grantInfos, string roleName, string permissionName) + { + grantInfos.ShouldContain( + p => p.Name == permissionName && + p.IsGranted && + p.Providers.Count == 1 && + p.Providers.Any( + pr => pr.Name == RolePermissionValueProvider.ProviderName && + pr.Key == roleName + ) + ); + } + + private static void UserShouldHavePermission(List grantInfos, Guid userId, string permissionName, params string[] inheritedRolesForThisPermission) + { + grantInfos.ShouldContain( + p => p.Name == permissionName && + p.IsGranted + ); + } + + private static void ShouldNotHavePermission(List grantInfos, string permissionName) { - private readonly IPermissionManager _permissionManager; - private readonly IPermissionStore _permissionStore; - - public PermissionManager_Tests() - { - _permissionManager = GetRequiredService(); - _permissionStore = GetRequiredService(); - } - - [Fact] - public async Task Roles_Should_Have_Configured_Permissions() - { - //admin - var grantInfos = await _permissionManager.GetAllForRoleAsync("admin"); - RoleShouldHavePermission(grantInfos, "admin", TestPermissionNames.MyPermission1); - RoleShouldHavePermission(grantInfos, "admin", TestPermissionNames.MyPermission2); - RoleShouldHavePermission(grantInfos, "admin", TestPermissionNames.MyPermission2_ChildPermission1); - - //moderator - grantInfos = await _permissionManager.GetAllForRoleAsync("moderator"); - RoleShouldHavePermission(grantInfos, "moderator", TestPermissionNames.MyPermission1); - RoleShouldHavePermission(grantInfos, "moderator", TestPermissionNames.MyPermission2); - ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2_ChildPermission1); - - //supporter - grantInfos = await _permissionManager.GetAllForRoleAsync("supporter"); - RoleShouldHavePermission(grantInfos, "supporter", TestPermissionNames.MyPermission1); - ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2); - ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2_ChildPermission1); - } - - [Fact] - public async Task Should_Grant_Permission_To_Role() - { - (await _permissionManager.GetForRoleAsync("supporter", TestPermissionNames.MyPermission2)).IsGranted.ShouldBeFalse(); - (await _permissionStore.IsGrantedAsync(TestPermissionNames.MyPermission2, RolePermissionValueProvider.ProviderName, "supporter")).ShouldBeFalse(); - - await _permissionManager.SetForRoleAsync("supporter", TestPermissionNames.MyPermission2, true); - - (await _permissionManager.GetForRoleAsync("supporter", TestPermissionNames.MyPermission2)).IsGranted.ShouldBeTrue(); - (await _permissionStore.IsGrantedAsync(TestPermissionNames.MyPermission2, RolePermissionValueProvider.ProviderName, "supporter")).ShouldBeTrue(); - } - - [Fact] - public async Task Should_Revoke_Permission_From_Role() - { - (await _permissionManager.GetForRoleAsync("moderator", TestPermissionNames.MyPermission1)).IsGranted.ShouldBeTrue(); - await _permissionManager.SetForRoleAsync("moderator", TestPermissionNames.MyPermission1, false); - (await _permissionManager.GetForRoleAsync("moderator", TestPermissionNames.MyPermission1)).IsGranted.ShouldBeFalse(); - } - - [Fact] - public async Task Users_Should_Have_Configured_Values() - { - //administrator - var user = GetUser("administrator"); - var grantInfos = await _permissionManager.GetAllForUserAsync(user.Id); - UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission1, "admin"); - UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission2, "admin"); - UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission2_ChildPermission1, "admin"); - - //john.nash - user = GetUser("john.nash"); - grantInfos = await _permissionManager.GetAllForUserAsync(user.Id); - UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission1, "moderator", "supporter"); - UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission2, "moderator"); - ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2_ChildPermission1); - - //john.nash - user = GetUser("david"); - grantInfos = await _permissionManager.GetAllForUserAsync(user.Id); - UserShouldHavePermission(grantInfos, user.Id, TestPermissionNames.MyPermission1); - ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2); - ShouldNotHavePermission(grantInfos, TestPermissionNames.MyPermission2_ChildPermission1); - } - - private static void RoleShouldHavePermission(List grantInfos, string roleName, string permissionName) - { - grantInfos.ShouldContain( - p => p.Name == permissionName && - p.IsGranted && - p.Providers.Count == 1 && - p.Providers.Any( - pr => pr.Name == RolePermissionValueProvider.ProviderName && - pr.Key == roleName - ) - ); - } - - private static void UserShouldHavePermission(List grantInfos, Guid userId, string permissionName, params string[] inheritedRolesForThisPermission) - { - grantInfos.ShouldContain( - p => p.Name == permissionName && - p.IsGranted - ); - } - - private static void ShouldNotHavePermission(List grantInfos, string permissionName) - { - grantInfos.ShouldContain( - p => p.Name == permissionName && - !p.IsGranted && - p.Providers.Count == 0 - ); - } + grantInfos.ShouldContain( + p => p.Name == permissionName && + !p.IsGranted && + p.Providers.Count == 0 + ); } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/TestPermissionDataBuilder.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/TestPermissionDataBuilder.cs index 77dd103132..301e0ece70 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/TestPermissionDataBuilder.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/TestPermissionDataBuilder.cs @@ -6,57 +6,56 @@ using Volo.Abp.Guids; using Volo.Abp.PermissionManagement; using Volo.Abp.Threading; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class TestPermissionDataBuilder : ITransientDependency { - public class TestPermissionDataBuilder : ITransientDependency + private readonly IGuidGenerator _guidGenerator; + private readonly IIdentityUserRepository _userRepository; + private readonly IPermissionGrantRepository _permissionGrantRepository; + private readonly ILookupNormalizer _lookupNormalizer; + + public TestPermissionDataBuilder( + IGuidGenerator guidGenerator, + IIdentityUserRepository userRepository, + IPermissionGrantRepository permissionGrantRepository, + ILookupNormalizer lookupNormalizer) + { + _guidGenerator = guidGenerator; + _userRepository = userRepository; + _permissionGrantRepository = permissionGrantRepository; + _lookupNormalizer = lookupNormalizer; + } + + public async Task Build() + { + await AddRolePermissions(); + await AddUserPermissions(); + } + + private async Task AddRolePermissions() + { + await AddPermission(TestPermissionNames.MyPermission1, RolePermissionValueProvider.ProviderName, "moderator"); + await AddPermission(TestPermissionNames.MyPermission2, RolePermissionValueProvider.ProviderName, "moderator"); + + await AddPermission(TestPermissionNames.MyPermission1, RolePermissionValueProvider.ProviderName, "supporter"); + } + + private async Task AddUserPermissions() + { + var david = AsyncHelper.RunSync(() => _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("david"))); + await AddPermission(TestPermissionNames.MyPermission1, UserPermissionValueProvider.ProviderName, david.Id.ToString()); + } + + private async Task AddPermission(string permissionName, string providerName, string providerKey) { - private readonly IGuidGenerator _guidGenerator; - private readonly IIdentityUserRepository _userRepository; - private readonly IPermissionGrantRepository _permissionGrantRepository; - private readonly ILookupNormalizer _lookupNormalizer; - - public TestPermissionDataBuilder( - IGuidGenerator guidGenerator, - IIdentityUserRepository userRepository, - IPermissionGrantRepository permissionGrantRepository, - ILookupNormalizer lookupNormalizer) - { - _guidGenerator = guidGenerator; - _userRepository = userRepository; - _permissionGrantRepository = permissionGrantRepository; - _lookupNormalizer = lookupNormalizer; - } - - public async Task Build() - { - await AddRolePermissions(); - await AddUserPermissions(); - } - - private async Task AddRolePermissions() - { - await AddPermission(TestPermissionNames.MyPermission1, RolePermissionValueProvider.ProviderName, "moderator"); - await AddPermission(TestPermissionNames.MyPermission2, RolePermissionValueProvider.ProviderName, "moderator"); - - await AddPermission(TestPermissionNames.MyPermission1, RolePermissionValueProvider.ProviderName, "supporter"); - } - - private async Task AddUserPermissions() - { - var david = AsyncHelper.RunSync(() => _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("david"))); - await AddPermission(TestPermissionNames.MyPermission1, UserPermissionValueProvider.ProviderName, david.Id.ToString()); - } - - private async Task AddPermission(string permissionName, string providerName, string providerKey) - { - await _permissionGrantRepository.InsertAsync( - new PermissionGrant( - _guidGenerator.Create(), - permissionName, - providerName, - providerKey - ) - ); - } + await _permissionGrantRepository.InsertAsync( + new PermissionGrant( + _guidGenerator.Create(), + permissionName, + providerName, + providerKey + ) + ); } } diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/TestPermissionNames.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/TestPermissionNames.cs index 1e65171eae..b89b34644d 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/TestPermissionNames.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/TestPermissionNames.cs @@ -1,14 +1,13 @@ -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public static class TestPermissionNames { - public static class TestPermissionNames + public static class Groups { - public static class Groups - { - public const string TestGroup = "TestGroup"; - } - - public const string MyPermission1 = "MyPermission1"; - public const string MyPermission2 = "MyPermission2"; - public const string MyPermission2_ChildPermission1 = "MyPermission2.ChildPermission1"; + public const string TestGroup = "TestGroup"; } -} \ No newline at end of file + + public const string MyPermission1 = "MyPermission1"; + public const string MyPermission2 = "MyPermission2"; + public const string MyPermission2_ChildPermission1 = "MyPermission2.ChildPermission1"; +} diff --git a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/UserRoleFinder_Tests.cs b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/UserRoleFinder_Tests.cs index ef06949500..524c7c25f3 100644 --- a/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/UserRoleFinder_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.Domain.Tests/Volo/Abp/Identity/UserRoleFinder_Tests.cs @@ -5,26 +5,25 @@ using System.Threading.Tasks; using Shouldly; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class UserRoleFinder_Tests : AbpIdentityDomainTestBase { - public class UserRoleFinder_Tests : AbpIdentityDomainTestBase - { - private readonly IUserRoleFinder _userRoleFinder; - private readonly IdentityTestData _testData; + private readonly IUserRoleFinder _userRoleFinder; + private readonly IdentityTestData _testData; - public UserRoleFinder_Tests() - { - _userRoleFinder = GetRequiredService(); - _testData = GetRequiredService(); - } + public UserRoleFinder_Tests() + { + _userRoleFinder = GetRequiredService(); + _testData = GetRequiredService(); + } - [Fact] - public async Task GetRolesAsync() - { - var roleNames = await _userRoleFinder.GetRolesAsync(_testData.UserJohnId); - roleNames.ShouldNotBeEmpty(); - roleNames.ShouldContain(x => x == "moderator"); - roleNames.ShouldContain(x => x == "supporter"); - } + [Fact] + public async Task GetRolesAsync() + { + var roleNames = await _userRoleFinder.GetRolesAsync(_testData.UserJohnId); + roleNames.ShouldNotBeEmpty(); + roleNames.ShouldContain(x => x == "moderator"); + roleNames.ShouldContain(x => x == "supporter"); } } diff --git a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreTestModule.cs b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreTestModule.cs index 8a2778d6c2..2d633ef03f 100644 --- a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreTestModule.cs +++ b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreTestModule.cs @@ -7,43 +7,42 @@ using Volo.Abp.EntityFrameworkCore.Sqlite; using Volo.Abp.Modularity; using Volo.Abp.PermissionManagement.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +[DependsOn( + typeof(AbpIdentityTestBaseModule), + typeof(AbpPermissionManagementEntityFrameworkCoreModule), + typeof(AbpIdentityEntityFrameworkCoreModule), + typeof(AbpEntityFrameworkCoreSqliteModule) + )] +public class AbpIdentityEntityFrameworkCoreTestModule : AbpModule { - [DependsOn( - typeof(AbpIdentityTestBaseModule), - typeof(AbpPermissionManagementEntityFrameworkCoreModule), - typeof(AbpIdentityEntityFrameworkCoreModule), - typeof(AbpEntityFrameworkCoreSqliteModule) - )] - public class AbpIdentityEntityFrameworkCoreTestModule : AbpModule + public override void ConfigureServices(ServiceConfigurationContext context) { - public override void ConfigureServices(ServiceConfigurationContext context) - { - var sqliteConnection = CreateDatabaseAndGetConnection(); + var sqliteConnection = CreateDatabaseAndGetConnection(); - Configure(options => + Configure(options => + { + options.Configure(abpDbContextConfigurationContext => { - options.Configure(abpDbContextConfigurationContext => - { - abpDbContextConfigurationContext.DbContextOptions.UseSqlite(sqliteConnection); - }); + abpDbContextConfigurationContext.DbContextOptions.UseSqlite(sqliteConnection); }); - } - - private static SqliteConnection CreateDatabaseAndGetConnection() - { - var connection = new SqliteConnection("Data Source=:memory:"); - connection.Open(); + }); + } + + private static SqliteConnection CreateDatabaseAndGetConnection() + { + var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); - new IdentityDbContext( - new DbContextOptionsBuilder().UseSqlite(connection).Options - ).GetService().CreateTables(); + new IdentityDbContext( + new DbContextOptionsBuilder().UseSqlite(connection).Options + ).GetService().CreateTables(); - new PermissionManagementDbContext( - new DbContextOptionsBuilder().UseSqlite(connection).Options - ).GetService().CreateTables(); + new PermissionManagementDbContext( + new DbContextOptionsBuilder().UseSqlite(connection).Options + ).GetService().CreateTables(); - return connection; - } + return connection; } } diff --git a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityClaimTypeRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityClaimTypeRepository_Tests.cs index 07f830ba86..51cf98533f 100644 --- a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityClaimTypeRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityClaimTypeRepository_Tests.cs @@ -1,9 +1,8 @@ using Volo.Abp.Identity.EntityFrameworkCore; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +public class IdentityClaimTypeRepository_Tests : IdentityClaimTypeRepository_Tests { - public class IdentityClaimTypeRepository_Tests : IdentityClaimTypeRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityDataSeeder_Tests.cs b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityDataSeeder_Tests.cs index 8cc434b2d0..f6f1baa3ac 100644 --- a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityDataSeeder_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityDataSeeder_Tests.cs @@ -1,7 +1,6 @@ -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class IdentityDataSeeder_Tests : IdentityDataSeeder_Tests { - public class IdentityDataSeeder_Tests : IdentityDataSeeder_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityLinkUserRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityLinkUserRepository_Tests.cs index 8e490fee8b..9d05980070 100644 --- a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityLinkUserRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityLinkUserRepository_Tests.cs @@ -1,7 +1,6 @@ -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class IdentityLinkUserRepository_Tests : IdentityLinkUserRepository_Tests { - public class IdentityLinkUserRepository_Tests : IdentityLinkUserRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityRoleRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityRoleRepository_Tests.cs index ebd435c98d..b34a5fe81f 100644 --- a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityRoleRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityRoleRepository_Tests.cs @@ -1,7 +1,6 @@ -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class IdentityRoleRepository_Tests : IdentityRoleRepository_Tests { - public class IdentityRoleRepository_Tests : IdentityRoleRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentitySecurityLogRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentitySecurityLogRepository_Tests.cs index 434f74706d..5742f93017 100644 --- a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentitySecurityLogRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentitySecurityLogRepository_Tests.cs @@ -1,7 +1,6 @@ -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class IdentitySecurityLogRepository_Tests : IdentitySecurityLogRepository_Tests { - public class IdentitySecurityLogRepository_Tests : IdentitySecurityLogRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityUserRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityUserRepository_Tests.cs index 5c164dea44..651e799578 100644 --- a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityUserRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityUserRepository_Tests.cs @@ -1,7 +1,6 @@ -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class IdentityUserRepository_Tests : IdentityUserRepository_Tests { - public class IdentityUserRepository_Tests : IdentityUserRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/Identity_Repository_Resolve_Tests.cs b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/Identity_Repository_Resolve_Tests.cs index c05bdf6437..4ff0552af3 100644 --- a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/Identity_Repository_Resolve_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/Identity_Repository_Resolve_Tests.cs @@ -2,9 +2,8 @@ using System.Collections.Generic; using System.Text; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class Identity_Repository_Resolve_Tests : Identity_Repository_Resolve_Tests { - public class Identity_Repository_Resolve_Tests : Identity_Repository_Resolve_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/LazyLoading_Tests.cs b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/LazyLoading_Tests.cs index ddc85f86cf..7fddde408f 100644 --- a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/LazyLoading_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/LazyLoading_Tests.cs @@ -2,19 +2,18 @@ using Microsoft.Extensions.DependencyInjection; using Volo.Abp.EntityFrameworkCore; -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class LazyLoading_Tests : LazyLoading_Tests { - public class LazyLoading_Tests : LazyLoading_Tests + protected override void BeforeAddApplication(IServiceCollection services) { - protected override void BeforeAddApplication(IServiceCollection services) + services.Configure(options => { - services.Configure(options => + options.PreConfigure(context => { - options.PreConfigure(context => - { - context.DbContextOptions.UseLazyLoadingProxies(); - }); + context.DbContextOptions.UseLazyLoadingProxies(); }); - } + }); } } diff --git a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/OrganizationUnitRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/OrganizationUnitRepository_Tests.cs index 3e8de4f511..69c06fba88 100644 --- a/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/OrganizationUnitRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/OrganizationUnitRepository_Tests.cs @@ -1,6 +1,5 @@ -namespace Volo.Abp.Identity.EntityFrameworkCore +namespace Volo.Abp.Identity.EntityFrameworkCore; + +public class OrganizationUnitRepository_Tests : OrganizationUnitRepository_Tests { - public class OrganizationUnitRepository_Tests : OrganizationUnitRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbTestModule.cs b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbTestModule.cs index 1ff966f309..6d906f7cb4 100644 --- a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbTestModule.cs +++ b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/AbpIdentityMongoDbTestModule.cs @@ -4,31 +4,30 @@ using Volo.Abp.Modularity; using Volo.Abp.PermissionManagement.MongoDB; using Volo.Abp.Uow; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[DependsOn( + typeof(AbpIdentityTestBaseModule), + typeof(AbpPermissionManagementMongoDbModule), + typeof(AbpIdentityMongoDbModule) +)] +public class AbpIdentityMongoDbTestModule : AbpModule { - [DependsOn( - typeof(AbpIdentityTestBaseModule), - typeof(AbpPermissionManagementMongoDbModule), - typeof(AbpIdentityMongoDbModule) - )] - public class AbpIdentityMongoDbTestModule : AbpModule + public override void ConfigureServices(ServiceConfigurationContext context) { - public override void ConfigureServices(ServiceConfigurationContext context) - { - var stringArray = MongoDbFixture.ConnectionString.Split('?'); - var connectionString = stringArray[0].EnsureEndsWith('/') + - "Db_" + - Guid.NewGuid().ToString("N") + "/?" + stringArray[1]; + var stringArray = MongoDbFixture.ConnectionString.Split('?'); + var connectionString = stringArray[0].EnsureEndsWith('/') + + "Db_" + + Guid.NewGuid().ToString("N") + "/?" + stringArray[1]; - Configure(options => - { - options.ConnectionStrings.Default = connectionString; - }); + Configure(options => + { + options.ConnectionStrings.Default = connectionString; + }); - Configure(options => - { - options.TransactionBehavior = UnitOfWorkTransactionBehavior.Disabled; - }); - } + Configure(options => + { + options.TransactionBehavior = UnitOfWorkTransactionBehavior.Disabled; + }); } } diff --git a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityClaimTypeRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityClaimTypeRepository_Tests.cs index cc66856c06..d81afbcbfd 100644 --- a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityClaimTypeRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityClaimTypeRepository_Tests.cs @@ -1,10 +1,9 @@ using Xunit; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[Collection(MongoTestCollection.Name)] +public class IdentityClaimTypeRepository_Tests : IdentityClaimTypeRepository_Tests { - [Collection(MongoTestCollection.Name)] - public class IdentityClaimTypeRepository_Tests : IdentityClaimTypeRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityDataSeeder_Tests.cs b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityDataSeeder_Tests.cs index d614807395..adc342e3d0 100644 --- a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityDataSeeder_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityDataSeeder_Tests.cs @@ -1,10 +1,9 @@ using Xunit; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[Collection(MongoTestCollection.Name)] +public class IdentityDataSeeder_Tests : IdentityDataSeeder_Tests { - [Collection(MongoTestCollection.Name)] - public class IdentityDataSeeder_Tests : IdentityDataSeeder_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityLinkUserRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityLinkUserRepository_Tests.cs index c7c9f29a55..dc2a431318 100644 --- a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityLinkUserRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityLinkUserRepository_Tests.cs @@ -1,10 +1,9 @@ using Xunit; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[Collection(MongoTestCollection.Name)] +public class IdentityLinkUserRepository_Tests : IdentityLinkUserRepository_Tests { - [Collection(MongoTestCollection.Name)] - public class IdentityLinkUserRepository_Tests : IdentityLinkUserRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityRoleRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityRoleRepository_Tests.cs index 8fde9dbb2c..ef9711b24b 100644 --- a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityRoleRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityRoleRepository_Tests.cs @@ -1,10 +1,9 @@ using Xunit; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[Collection(MongoTestCollection.Name)] +public class IdentityRoleRepository_Tests : IdentityRoleRepository_Tests { - [Collection(MongoTestCollection.Name)] - public class IdentityRoleRepository_Tests : IdentityRoleRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentitySecurityLogRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentitySecurityLogRepository_Tests.cs index 85d496fdb2..a2a8bd3941 100644 --- a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentitySecurityLogRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentitySecurityLogRepository_Tests.cs @@ -1,10 +1,9 @@ using Xunit; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[Collection(MongoTestCollection.Name)] +public class IdentitySecurityLogRepository_Tests : IdentitySecurityLogRepository_Tests { - [Collection(MongoTestCollection.Name)] - public class IdentitySecurityLogRepository_Tests : IdentitySecurityLogRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityUserRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityUserRepository_Tests.cs index e29a216ca7..bc2391c2d3 100644 --- a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityUserRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/IdentityUserRepository_Tests.cs @@ -1,10 +1,9 @@ using Xunit; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[Collection(MongoTestCollection.Name)] +public class IdentityUserRepository_Tests : IdentityUserRepository_Tests { - [Collection(MongoTestCollection.Name)] - public class IdentityUserRepository_Tests : IdentityUserRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/Identity_Repository_Resolve_Tests.cs b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/Identity_Repository_Resolve_Tests.cs index 42020a4170..228123c8e4 100644 --- a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/Identity_Repository_Resolve_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/Identity_Repository_Resolve_Tests.cs @@ -1,9 +1,8 @@ using Xunit; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[Collection(MongoTestCollection.Name)] +public class Identity_Repository_Resolve_Tests : Identity_Repository_Resolve_Tests { - [Collection(MongoTestCollection.Name)] - public class Identity_Repository_Resolve_Tests : Identity_Repository_Resolve_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/MongoDbFixture.cs b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/MongoDbFixture.cs index 8563470a27..0a9752e8c5 100644 --- a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/MongoDbFixture.cs +++ b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/MongoDbFixture.cs @@ -1,22 +1,21 @@ using System; using Mongo2Go; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +public class MongoDbFixture : IDisposable { - public class MongoDbFixture : IDisposable - { - private static readonly MongoDbRunner MongoDbRunner; - public static readonly string ConnectionString; + private static readonly MongoDbRunner MongoDbRunner; + public static readonly string ConnectionString; - static MongoDbFixture() - { - MongoDbRunner = MongoDbRunner.Start(singleNodeReplSet: true, singleNodeReplSetWaitTimeout: 20); - ConnectionString = MongoDbRunner.ConnectionString; - } + static MongoDbFixture() + { + MongoDbRunner = MongoDbRunner.Start(singleNodeReplSet: true, singleNodeReplSetWaitTimeout: 20); + ConnectionString = MongoDbRunner.ConnectionString; + } - public void Dispose() - { - MongoDbRunner?.Dispose(); - } + public void Dispose() + { + MongoDbRunner?.Dispose(); } } diff --git a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/MongoTestCollection.cs b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/MongoTestCollection.cs index ae01262908..377771b55e 100644 --- a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/MongoTestCollection.cs +++ b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/MongoTestCollection.cs @@ -1,10 +1,9 @@ using Xunit; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[CollectionDefinition(Name)] +public class MongoTestCollection : ICollectionFixture { - [CollectionDefinition(Name)] - public class MongoTestCollection : ICollectionFixture - { - public const string Name = "MongoDB Collection"; - } -} \ No newline at end of file + public const string Name = "MongoDB Collection"; +} diff --git a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/OrganizationUnitRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/OrganizationUnitRepository_Tests.cs index dc134f9974..927c9875bb 100644 --- a/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/OrganizationUnitRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.MongoDB.Tests/Volo/Abp/Identity/MongoDB/OrganizationUnitRepository_Tests.cs @@ -3,10 +3,9 @@ using System.Collections.Generic; using System.Text; using Xunit; -namespace Volo.Abp.Identity.MongoDB +namespace Volo.Abp.Identity.MongoDB; + +[Collection(MongoTestCollection.Name)] +public class OrganizationUnitRepository_Tests : OrganizationUnitRepository_Tests { - [Collection(MongoTestCollection.Name)] - public class OrganizationUnitRepository_Tests : OrganizationUnitRepository_Tests - { - } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestBase.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestBase.cs index ac75b16b02..204e232889 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestBase.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestBase.cs @@ -1,14 +1,13 @@ using Volo.Abp.Modularity; using Volo.Abp.Testing; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class AbpIdentityTestBase : AbpIntegratedTest + where TStartupModule : IAbpModule { - public abstract class AbpIdentityTestBase : AbpIntegratedTest - where TStartupModule : IAbpModule + protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options) { - protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options) - { - options.UseAutofac(); - } + options.UseAutofac(); } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestBaseModule.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestBaseModule.cs index 4b956ab16d..6a9694ef7b 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestBaseModule.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestBaseModule.cs @@ -5,39 +5,38 @@ using Volo.Abp.Data; using Volo.Abp.Modularity; using Volo.Abp.Threading; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +[DependsOn( + typeof(AbpAutofacModule), + typeof(AbpTestBaseModule), + typeof(AbpIdentityDomainModule), + typeof(AbpAuthorizationModule) + )] +public class AbpIdentityTestBaseModule : AbpModule { - [DependsOn( - typeof(AbpAutofacModule), - typeof(AbpTestBaseModule), - typeof(AbpIdentityDomainModule), - typeof(AbpAuthorizationModule) - )] - public class AbpIdentityTestBaseModule : AbpModule + public override void ConfigureServices(ServiceConfigurationContext context) { - public override void ConfigureServices(ServiceConfigurationContext context) - { - context.Services.AddAlwaysAllowAuthorization(); - } + context.Services.AddAlwaysAllowAuthorization(); + } - public override void OnApplicationInitialization(ApplicationInitializationContext context) - { - SeedTestData(context); - } + public override void OnApplicationInitialization(ApplicationInitializationContext context) + { + SeedTestData(context); + } - private static void SeedTestData(ApplicationInitializationContext context) + private static void SeedTestData(ApplicationInitializationContext context) + { + using (var scope = context.ServiceProvider.CreateScope()) { - using (var scope = context.ServiceProvider.CreateScope()) + var dataSeeder = scope.ServiceProvider.GetRequiredService(); + AsyncHelper.RunSync(async () => { - var dataSeeder = scope.ServiceProvider.GetRequiredService(); - AsyncHelper.RunSync(async () => - { - await dataSeeder.SeedAsync(); - await scope.ServiceProvider - .GetRequiredService() - .Build(); - }); - } + await dataSeeder.SeedAsync(); + await scope.ServiceProvider + .GetRequiredService() + .Build(); + }); } } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestDataBuilder.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestDataBuilder.cs index a6e0f0c310..2381748d68 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestDataBuilder.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/AbpIdentityTestDataBuilder.cs @@ -6,192 +6,191 @@ using Volo.Abp.DependencyInjection; using Volo.Abp.Guids; using Volo.Abp.SecurityLog; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class AbpIdentityTestDataBuilder : ITransientDependency { - public class AbpIdentityTestDataBuilder : ITransientDependency + private readonly IGuidGenerator _guidGenerator; + private readonly IIdentityUserRepository _userRepository; + private readonly IdentityUserManager _userManager; + private readonly IIdentityClaimTypeRepository _identityClaimTypeRepository; + private readonly IIdentityRoleRepository _roleRepository; + private readonly IOrganizationUnitRepository _organizationUnitRepository; + private readonly IIdentitySecurityLogRepository _identitySecurityLogRepository; + private readonly ILookupNormalizer _lookupNormalizer; + private readonly IdentityTestData _testData; + private readonly OrganizationUnitManager _organizationUnitManager; + private readonly IIdentityLinkUserRepository _identityLinkUserRepository; + private readonly IdentityLinkUserManager _identityLinkUserManager; + + private IdentityRole _adminRole; + private IdentityRole _moderatorRole; + private IdentityRole _supporterRole; + private IdentityRole _managerRole; + private OrganizationUnit _ou111; + private OrganizationUnit _ou112; + + public AbpIdentityTestDataBuilder( + IGuidGenerator guidGenerator, + IIdentityUserRepository userRepository, + IdentityUserManager userManager, + IIdentityClaimTypeRepository identityClaimTypeRepository, + IIdentityRoleRepository roleRepository, + IOrganizationUnitRepository organizationUnitRepository, + IIdentitySecurityLogRepository identitySecurityLogRepository, + ILookupNormalizer lookupNormalizer, + IdentityTestData testData, + OrganizationUnitManager organizationUnitManager, + IIdentityLinkUserRepository identityLinkUserRepository, + IdentityLinkUserManager identityLinkUserManager) { - private readonly IGuidGenerator _guidGenerator; - private readonly IIdentityUserRepository _userRepository; - private readonly IdentityUserManager _userManager; - private readonly IIdentityClaimTypeRepository _identityClaimTypeRepository; - private readonly IIdentityRoleRepository _roleRepository; - private readonly IOrganizationUnitRepository _organizationUnitRepository; - private readonly IIdentitySecurityLogRepository _identitySecurityLogRepository; - private readonly ILookupNormalizer _lookupNormalizer; - private readonly IdentityTestData _testData; - private readonly OrganizationUnitManager _organizationUnitManager; - private readonly IIdentityLinkUserRepository _identityLinkUserRepository; - private readonly IdentityLinkUserManager _identityLinkUserManager; - - private IdentityRole _adminRole; - private IdentityRole _moderatorRole; - private IdentityRole _supporterRole; - private IdentityRole _managerRole; - private OrganizationUnit _ou111; - private OrganizationUnit _ou112; - - public AbpIdentityTestDataBuilder( - IGuidGenerator guidGenerator, - IIdentityUserRepository userRepository, - IdentityUserManager userManager, - IIdentityClaimTypeRepository identityClaimTypeRepository, - IIdentityRoleRepository roleRepository, - IOrganizationUnitRepository organizationUnitRepository, - IIdentitySecurityLogRepository identitySecurityLogRepository, - ILookupNormalizer lookupNormalizer, - IdentityTestData testData, - OrganizationUnitManager organizationUnitManager, - IIdentityLinkUserRepository identityLinkUserRepository, - IdentityLinkUserManager identityLinkUserManager) - { - _guidGenerator = guidGenerator; - _userRepository = userRepository; - _userManager = userManager; - _identityClaimTypeRepository = identityClaimTypeRepository; - _roleRepository = roleRepository; - _lookupNormalizer = lookupNormalizer; - _testData = testData; - _organizationUnitRepository = organizationUnitRepository; - _organizationUnitManager = organizationUnitManager; - _identityLinkUserRepository = identityLinkUserRepository; - _identityLinkUserManager = identityLinkUserManager; - _identitySecurityLogRepository = identitySecurityLogRepository; - } - - public async Task Build() - { - await AddRoles(); - await AddOrganizationUnits(); - await AddUsers(); - await AddLinkUsers(); - await AddClaimTypes(); - await AddSecurityLogs(); - } - - private async Task AddRoles() - { - _adminRole = await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin")); - - _moderatorRole = new IdentityRole(_testData.RoleModeratorId, "moderator"); - _moderatorRole.AddClaim(_guidGenerator, new Claim("test-claim", "test-value")); - await _roleRepository.InsertAsync(_moderatorRole); - - _supporterRole = new IdentityRole(_guidGenerator.Create(), "supporter"); - await _roleRepository.InsertAsync(_supporterRole); - - _managerRole = new IdentityRole(_guidGenerator.Create(), "manager"); - await _roleRepository.InsertAsync(_managerRole); - } - - /* Creates OU tree as shown below: - * - * - OU1 - * - OU11 - * - OU111 - * - OU112 - * - OU12 - * - OU2 - * - OU21 - */ - private async Task AddOrganizationUnits() - { - var ou1 = await CreateOU("OU1", OrganizationUnit.CreateCode(1)); - var ou11 = await CreateOU("OU11", OrganizationUnit.CreateCode(1, 1), ou1.Id); - _ou112 = await CreateOU("OU112", OrganizationUnit.CreateCode(1, 1, 2), ou11.Id); - var ou12 = await CreateOU("OU12", OrganizationUnit.CreateCode(1, 2), ou1.Id); - var ou2 = await CreateOU("OU2", OrganizationUnit.CreateCode(2)); - var ou21 = await CreateOU("OU21", OrganizationUnit.CreateCode(2, 1), ou2.Id); - - _ou111 = new OrganizationUnit(_guidGenerator.Create(), "OU111", ou11.Id); - _ou111.Code = OrganizationUnit.CreateCode(1, 1, 1); - _ou111.AddRole(_moderatorRole.Id); - _ou111.AddRole(_managerRole.Id); - await _organizationUnitRepository.InsertAsync(_ou111); - } - - private async Task AddUsers() - { - var adminUser = new IdentityUser(_guidGenerator.Create(), "administrator", "admin@abp.io"); - adminUser.AddRole(_adminRole.Id); - adminUser.AddClaim(_guidGenerator, new Claim("TestClaimType", "42")); - await _userRepository.InsertAsync(adminUser); - - var john = new IdentityUser(_testData.UserJohnId, "john.nash", "john.nash@abp.io"); - john.AddRole(_moderatorRole.Id); - john.AddRole(_supporterRole.Id); - john.AddOrganizationUnit(_ou111.Id); - john.AddOrganizationUnit(_ou112.Id); - john.AddLogin(new UserLoginInfo("github", "john", "John Nash")); - john.AddLogin(new UserLoginInfo("twitter", "johnx", "John Nash")); - john.AddClaim(_guidGenerator, new Claim("TestClaimType", "42")); - john.SetToken("test-provider", "test-name", "test-value"); - await _userRepository.InsertAsync(john); - - var david = new IdentityUser(_testData.UserDavidId, "david", "david@abp.io"); - david.AddOrganizationUnit(_ou112.Id); - await _userRepository.InsertAsync(david); - - var neo = new IdentityUser(_testData.UserNeoId, "neo", "neo@abp.io"); - neo.AddRole(_supporterRole.Id); - neo.AddClaim(_guidGenerator, new Claim("TestClaimType", "43")); - neo.AddOrganizationUnit(_ou111.Id); - await _userRepository.InsertAsync(neo); - - var bob = new IdentityUser(_testData.UserBobId, "bob", "bob@abp.io"); - bob.SetIsActive(false); - await _userManager.CreateAsync(bob, "1q2w3E*"); - } - - private async Task AddLinkUsers() - { - var john = await _userRepository.GetAsync(_testData.UserJohnId); - var david = await _userRepository.GetAsync(_testData.UserDavidId); - var neo = await _userRepository.GetAsync(_testData.UserNeoId); + _guidGenerator = guidGenerator; + _userRepository = userRepository; + _userManager = userManager; + _identityClaimTypeRepository = identityClaimTypeRepository; + _roleRepository = roleRepository; + _lookupNormalizer = lookupNormalizer; + _testData = testData; + _organizationUnitRepository = organizationUnitRepository; + _organizationUnitManager = organizationUnitManager; + _identityLinkUserRepository = identityLinkUserRepository; + _identityLinkUserManager = identityLinkUserManager; + _identitySecurityLogRepository = identitySecurityLogRepository; + } - await _identityLinkUserManager.LinkAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(david.Id, david.TenantId)); - await _identityLinkUserManager.LinkAsync(new IdentityLinkUserInfo(david.Id, david.TenantId), - new IdentityLinkUserInfo(neo.Id, neo.TenantId)); - } + public async Task Build() + { + await AddRoles(); + await AddOrganizationUnits(); + await AddUsers(); + await AddLinkUsers(); + await AddClaimTypes(); + await AddSecurityLogs(); + } - private async Task AddClaimTypes() - { - var ageClaim = new IdentityClaimType(_testData.AgeClaimId, "Age", false, false, null, null, null, IdentityClaimValueType.Int); - await _identityClaimTypeRepository.InsertAsync(ageClaim); + private async Task AddRoles() + { + _adminRole = await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin")); + + _moderatorRole = new IdentityRole(_testData.RoleModeratorId, "moderator"); + _moderatorRole.AddClaim(_guidGenerator, new Claim("test-claim", "test-value")); + await _roleRepository.InsertAsync(_moderatorRole); - var educationClaim = new IdentityClaimType(_testData.EducationClaimId, "Education", true, false, null, null, null); - await _identityClaimTypeRepository.InsertAsync(educationClaim); - } + _supporterRole = new IdentityRole(_guidGenerator.Create(), "supporter"); + await _roleRepository.InsertAsync(_supporterRole); - private async Task CreateOU(string displayName, string code, Guid? parentId = null) + _managerRole = new IdentityRole(_guidGenerator.Create(), "manager"); + await _roleRepository.InsertAsync(_managerRole); + } + + /* Creates OU tree as shown below: + * + * - OU1 + * - OU11 + * - OU111 + * - OU112 + * - OU12 + * - OU2 + * - OU21 + */ + private async Task AddOrganizationUnits() + { + var ou1 = await CreateOU("OU1", OrganizationUnit.CreateCode(1)); + var ou11 = await CreateOU("OU11", OrganizationUnit.CreateCode(1, 1), ou1.Id); + _ou112 = await CreateOU("OU112", OrganizationUnit.CreateCode(1, 1, 2), ou11.Id); + var ou12 = await CreateOU("OU12", OrganizationUnit.CreateCode(1, 2), ou1.Id); + var ou2 = await CreateOU("OU2", OrganizationUnit.CreateCode(2)); + var ou21 = await CreateOU("OU21", OrganizationUnit.CreateCode(2, 1), ou2.Id); + + _ou111 = new OrganizationUnit(_guidGenerator.Create(), "OU111", ou11.Id); + _ou111.Code = OrganizationUnit.CreateCode(1, 1, 1); + _ou111.AddRole(_moderatorRole.Id); + _ou111.AddRole(_managerRole.Id); + await _organizationUnitRepository.InsertAsync(_ou111); + } + + private async Task AddUsers() + { + var adminUser = new IdentityUser(_guidGenerator.Create(), "administrator", "admin@abp.io"); + adminUser.AddRole(_adminRole.Id); + adminUser.AddClaim(_guidGenerator, new Claim("TestClaimType", "42")); + await _userRepository.InsertAsync(adminUser); + + var john = new IdentityUser(_testData.UserJohnId, "john.nash", "john.nash@abp.io"); + john.AddRole(_moderatorRole.Id); + john.AddRole(_supporterRole.Id); + john.AddOrganizationUnit(_ou111.Id); + john.AddOrganizationUnit(_ou112.Id); + john.AddLogin(new UserLoginInfo("github", "john", "John Nash")); + john.AddLogin(new UserLoginInfo("twitter", "johnx", "John Nash")); + john.AddClaim(_guidGenerator, new Claim("TestClaimType", "42")); + john.SetToken("test-provider", "test-name", "test-value"); + await _userRepository.InsertAsync(john); + + var david = new IdentityUser(_testData.UserDavidId, "david", "david@abp.io"); + david.AddOrganizationUnit(_ou112.Id); + await _userRepository.InsertAsync(david); + + var neo = new IdentityUser(_testData.UserNeoId, "neo", "neo@abp.io"); + neo.AddRole(_supporterRole.Id); + neo.AddClaim(_guidGenerator, new Claim("TestClaimType", "43")); + neo.AddOrganizationUnit(_ou111.Id); + await _userRepository.InsertAsync(neo); + + var bob = new IdentityUser(_testData.UserBobId, "bob", "bob@abp.io"); + bob.SetIsActive(false); + await _userManager.CreateAsync(bob, "1q2w3E*"); + } + + private async Task AddLinkUsers() + { + var john = await _userRepository.GetAsync(_testData.UserJohnId); + var david = await _userRepository.GetAsync(_testData.UserDavidId); + var neo = await _userRepository.GetAsync(_testData.UserNeoId); + + await _identityLinkUserManager.LinkAsync(new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(david.Id, david.TenantId)); + await _identityLinkUserManager.LinkAsync(new IdentityLinkUserInfo(david.Id, david.TenantId), + new IdentityLinkUserInfo(neo.Id, neo.TenantId)); + } + + private async Task AddClaimTypes() + { + var ageClaim = new IdentityClaimType(_testData.AgeClaimId, "Age", false, false, null, null, null, IdentityClaimValueType.Int); + await _identityClaimTypeRepository.InsertAsync(ageClaim); + + var educationClaim = new IdentityClaimType(_testData.EducationClaimId, "Education", true, false, null, null, null); + await _identityClaimTypeRepository.InsertAsync(educationClaim); + } + + private async Task CreateOU(string displayName, string code, Guid? parentId = null) + { + var ou = await _organizationUnitRepository.InsertAsync(new OrganizationUnit(_guidGenerator.Create(), displayName, parentId) { Code = code }); + return ou; + } + + private async Task AddSecurityLogs() + { + await _identitySecurityLogRepository.InsertAsync(new IdentitySecurityLog(_guidGenerator, new SecurityLogInfo { - var ou = await _organizationUnitRepository.InsertAsync(new OrganizationUnit(_guidGenerator.Create(), displayName, parentId) { Code = code }); - return ou; - } + ApplicationName = "Test-ApplicationName", + Identity = "Test-Identity", + Action = "Test-Action", + UserId = _testData.UserJohnId, + UserName = "john.nash", + + CreationTime = new DateTime(2020, 01, 01, 10, 0, 0) + })); - private async Task AddSecurityLogs() + await _identitySecurityLogRepository.InsertAsync(new IdentitySecurityLog(_guidGenerator, new SecurityLogInfo { - await _identitySecurityLogRepository.InsertAsync(new IdentitySecurityLog(_guidGenerator, new SecurityLogInfo - { - ApplicationName = "Test-ApplicationName", - Identity = "Test-Identity", - Action = "Test-Action", - UserId = _testData.UserJohnId, - UserName = "john.nash", - - CreationTime = new DateTime(2020, 01, 01, 10, 0, 0) - })); - - await _identitySecurityLogRepository.InsertAsync(new IdentitySecurityLog(_guidGenerator, new SecurityLogInfo - { - ApplicationName = "Test-ApplicationName", - Identity = "Test-Identity", - Action = "Test-Action", - UserId = _testData.UserDavidId, - UserName = "david", - - CreationTime = new DateTime(2020, 01, 02, 10, 0, 0) - })); - } + ApplicationName = "Test-ApplicationName", + Identity = "Test-Identity", + Action = "Test-Action", + UserId = _testData.UserDavidId, + UserName = "david", + + CreationTime = new DateTime(2020, 01, 02, 10, 0, 0) + })); } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityClaimTypeRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityClaimTypeRepository_Tests.cs index c4483aeefa..07cc4e7f60 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityClaimTypeRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityClaimTypeRepository_Tests.cs @@ -9,38 +9,37 @@ using Volo.Abp.Guids; using Volo.Abp.Modularity; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class IdentityClaimTypeRepository_Tests : AbpIdentityTestBase + where TStartupModule : IAbpModule { - public abstract class IdentityClaimTypeRepository_Tests : AbpIdentityTestBase - where TStartupModule : IAbpModule - { - protected IIdentityClaimTypeRepository ClaimTypeRepository { get; } - protected IGuidGenerator GuidGenerator { get; } + protected IIdentityClaimTypeRepository ClaimTypeRepository { get; } + protected IGuidGenerator GuidGenerator { get; } - public IdentityClaimTypeRepository_Tests() - { - ClaimTypeRepository = ServiceProvider.GetRequiredService(); - GuidGenerator = ServiceProvider.GetRequiredService(); - } + public IdentityClaimTypeRepository_Tests() + { + ClaimTypeRepository = ServiceProvider.GetRequiredService(); + GuidGenerator = ServiceProvider.GetRequiredService(); + } - [Fact] - public async Task Should_Check_Name_If_It_Is_Uniquee() - { - var claim = (await ClaimTypeRepository.GetListAsync()).FirstOrDefault(); + [Fact] + public async Task Should_Check_Name_If_It_Is_Uniquee() + { + var claim = (await ClaimTypeRepository.GetListAsync()).FirstOrDefault(); - var result1 = await ClaimTypeRepository.AnyAsync(claim.Name); + var result1 = await ClaimTypeRepository.AnyAsync(claim.Name); - result1.ShouldBe(true); + result1.ShouldBe(true); - var result2 = await ClaimTypeRepository.AnyAsync(Guid.NewGuid().ToString()); + var result2 = await ClaimTypeRepository.AnyAsync(Guid.NewGuid().ToString()); - result2.ShouldBe(false); - } + result2.ShouldBe(false); + } - [Fact] - public async Task GetCountAsync_With_Filter() - { - (await ClaimTypeRepository.GetCountAsync("Age")).ShouldBe(1); - } + [Fact] + public async Task GetCountAsync_With_Filter() + { + (await ClaimTypeRepository.GetCountAsync("Age")).ShouldBe(1); } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityDataSeeder_Tests.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityDataSeeder_Tests.cs index e74c216ea4..e79e62d97f 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityDataSeeder_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityDataSeeder_Tests.cs @@ -6,54 +6,53 @@ using Volo.Abp.Modularity; using Volo.Abp.MultiTenancy; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class IdentityDataSeeder_Tests : AbpIdentityTestBase + where TStartupModule : IAbpModule { - public abstract class IdentityDataSeeder_Tests : AbpIdentityTestBase - where TStartupModule : IAbpModule - { - private readonly IIdentityDataSeeder _identityDataSeeder; - private readonly IIdentityUserRepository _userRepository; - private readonly IIdentityRoleRepository _roleRepository; - private readonly ILookupNormalizer _lookupNormalizer; - private readonly ICurrentTenant _currentTenant; + private readonly IIdentityDataSeeder _identityDataSeeder; + private readonly IIdentityUserRepository _userRepository; + private readonly IIdentityRoleRepository _roleRepository; + private readonly ILookupNormalizer _lookupNormalizer; + private readonly ICurrentTenant _currentTenant; - protected IdentityDataSeeder_Tests() - { - _identityDataSeeder = GetRequiredService(); - _userRepository = GetRequiredService(); - _roleRepository = GetRequiredService(); - _lookupNormalizer = GetRequiredService(); - _currentTenant = GetRequiredService(); - } + protected IdentityDataSeeder_Tests() + { + _identityDataSeeder = GetRequiredService(); + _userRepository = GetRequiredService(); + _roleRepository = GetRequiredService(); + _lookupNormalizer = GetRequiredService(); + _currentTenant = GetRequiredService(); + } - [Fact] - public async Task Should_Create_Admin_User_And_Role() - { - await _identityDataSeeder.SeedAsync("admin@abp.io", "1q2w3E*"); + [Fact] + public async Task Should_Create_Admin_User_And_Role() + { + await _identityDataSeeder.SeedAsync("admin@abp.io", "1q2w3E*"); - (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin"))).ShouldNotBeNull(); - (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin"))).Name.ShouldBe("admin"); - (await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin"))).ShouldNotBeNull(); - } + (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin"))).ShouldNotBeNull(); + (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin"))).Name.ShouldBe("admin"); + (await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin"))).ShouldNotBeNull(); + } - [Fact] - public async Task Should_Create_Admin_User_And_Role_With_TenantId() - { - var tenantId = Guid.NewGuid(); + [Fact] + public async Task Should_Create_Admin_User_And_Role_With_TenantId() + { + var tenantId = Guid.NewGuid(); - await _identityDataSeeder.SeedAsync("admin@tenant.abp.io", "1q2w3E*", tenantId); + await _identityDataSeeder.SeedAsync("admin@tenant.abp.io", "1q2w3E*", tenantId); - (await _userRepository.FindByNormalizedEmailAsync(_lookupNormalizer.NormalizeEmail("admin@tenant.abp.io"))).ShouldBeNull(); + (await _userRepository.FindByNormalizedEmailAsync(_lookupNormalizer.NormalizeEmail("admin@tenant.abp.io"))).ShouldBeNull(); - using (_currentTenant.Change(tenantId)) - { - (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin"))).ShouldNotBeNull(); - (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin"))).Name.ShouldBe("admin"); - (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin"))).TenantId.ShouldBe(tenantId); + using (_currentTenant.Change(tenantId)) + { + (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin"))).ShouldNotBeNull(); + (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin"))).Name.ShouldBe("admin"); + (await _userRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName("admin"))).TenantId.ShouldBe(tenantId); - (await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin"))).ShouldNotBeNull(); - (await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin"))).TenantId.ShouldBe(tenantId); - } + (await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin"))).ShouldNotBeNull(); + (await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin"))).TenantId.ShouldBe(tenantId); } } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityLinkUserRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityLinkUserRepository_Tests.cs index 64dd9c5d20..fec2f57e59 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityLinkUserRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityLinkUserRepository_Tests.cs @@ -4,77 +4,76 @@ using Shouldly; using Volo.Abp.Modularity; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class IdentityLinkUserRepository_Tests : AbpIdentityTestBase + where TStartupModule : IAbpModule { - public abstract class IdentityLinkUserRepository_Tests : AbpIdentityTestBase - where TStartupModule : IAbpModule - { - protected IIdentityUserRepository UserRepository { get; } - protected IIdentityLinkUserRepository IdentityLinkUserRepository { get; } - protected IdentityTestData TestData { get; } + protected IIdentityUserRepository UserRepository { get; } + protected IIdentityLinkUserRepository IdentityLinkUserRepository { get; } + protected IdentityTestData TestData { get; } - public IdentityLinkUserRepository_Tests() - { - UserRepository = GetRequiredService(); - IdentityLinkUserRepository = GetRequiredService(); - TestData = GetRequiredService(); - } + public IdentityLinkUserRepository_Tests() + { + UserRepository = GetRequiredService(); + IdentityLinkUserRepository = GetRequiredService(); + TestData = GetRequiredService(); + } - [Fact] - public async Task FindAsync() - { - var john = await UserRepository.GetAsync(TestData.UserJohnId); - var david = await UserRepository.GetAsync(TestData.UserDavidId); - var neo = await UserRepository.GetAsync(TestData.UserNeoId); + [Fact] + public async Task FindAsync() + { + var john = await UserRepository.GetAsync(TestData.UserJohnId); + var david = await UserRepository.GetAsync(TestData.UserDavidId); + var neo = await UserRepository.GetAsync(TestData.UserNeoId); - var johnAndDavidLinkUser = await IdentityLinkUserRepository.FindAsync( - new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(david.Id, david.TenantId)); + var johnAndDavidLinkUser = await IdentityLinkUserRepository.FindAsync( + new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(david.Id, david.TenantId)); - johnAndDavidLinkUser.ShouldNotBeNull(); - johnAndDavidLinkUser.SourceUserId.ShouldBe(john.Id); - johnAndDavidLinkUser.SourceTenantId.ShouldBe(john.TenantId); - johnAndDavidLinkUser.TargetUserId.ShouldBe(david.Id); - johnAndDavidLinkUser.TargetTenantId.ShouldBe(david.TenantId); + johnAndDavidLinkUser.ShouldNotBeNull(); + johnAndDavidLinkUser.SourceUserId.ShouldBe(john.Id); + johnAndDavidLinkUser.SourceTenantId.ShouldBe(john.TenantId); + johnAndDavidLinkUser.TargetUserId.ShouldBe(david.Id); + johnAndDavidLinkUser.TargetTenantId.ShouldBe(david.TenantId); - (await IdentityLinkUserRepository.FindAsync( - new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(neo.Id, neo.TenantId))).ShouldBeNull(); - } + (await IdentityLinkUserRepository.FindAsync( + new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(neo.Id, neo.TenantId))).ShouldBeNull(); + } - [Fact] - public async Task GetListAsync() - { - var john = await UserRepository.GetAsync(TestData.UserJohnId); - var david = await UserRepository.GetAsync(TestData.UserDavidId); - var neo = await UserRepository.GetAsync(TestData.UserNeoId); + [Fact] + public async Task GetListAsync() + { + var john = await UserRepository.GetAsync(TestData.UserJohnId); + var david = await UserRepository.GetAsync(TestData.UserDavidId); + var neo = await UserRepository.GetAsync(TestData.UserNeoId); - var davidLinkUsers = await IdentityLinkUserRepository.GetListAsync(new IdentityLinkUserInfo(david.Id, david.TenantId)); - davidLinkUsers.ShouldNotBeNull(); + var davidLinkUsers = await IdentityLinkUserRepository.GetListAsync(new IdentityLinkUserInfo(david.Id, david.TenantId)); + davidLinkUsers.ShouldNotBeNull(); - davidLinkUsers.ShouldContain(x => x.SourceUserId == john.Id && x.SourceTenantId == john.TenantId); - davidLinkUsers.ShouldContain(x => x.TargetUserId == neo.Id && x.TargetTenantId == neo.TenantId); - } + davidLinkUsers.ShouldContain(x => x.SourceUserId == john.Id && x.SourceTenantId == john.TenantId); + davidLinkUsers.ShouldContain(x => x.TargetUserId == neo.Id && x.TargetTenantId == neo.TenantId); + } - [Fact] - public async Task DeleteAsync() - { - var john = await UserRepository.GetAsync(TestData.UserJohnId); - var david = await UserRepository.GetAsync(TestData.UserDavidId); + [Fact] + public async Task DeleteAsync() + { + var john = await UserRepository.GetAsync(TestData.UserJohnId); + var david = await UserRepository.GetAsync(TestData.UserDavidId); - (await IdentityLinkUserRepository.FindAsync( - new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(david.Id, david.TenantId))).ShouldNotBeNull(); + (await IdentityLinkUserRepository.FindAsync( + new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(david.Id, david.TenantId))).ShouldNotBeNull(); - await IdentityLinkUserRepository.DeleteAsync(new IdentityLinkUserInfo(david.Id, david.TenantId)); + await IdentityLinkUserRepository.DeleteAsync(new IdentityLinkUserInfo(david.Id, david.TenantId)); - (await IdentityLinkUserRepository.FindAsync( - new IdentityLinkUserInfo(john.Id, john.TenantId), - new IdentityLinkUserInfo(david.Id, david.TenantId))).ShouldBeNull(); + (await IdentityLinkUserRepository.FindAsync( + new IdentityLinkUserInfo(john.Id, john.TenantId), + new IdentityLinkUserInfo(david.Id, david.TenantId))).ShouldBeNull(); - (await IdentityLinkUserRepository.FindAsync( - new IdentityLinkUserInfo(david.Id, david.TenantId), - new IdentityLinkUserInfo(john.Id, john.TenantId))).ShouldBeNull(); - } + (await IdentityLinkUserRepository.FindAsync( + new IdentityLinkUserInfo(david.Id, david.TenantId), + new IdentityLinkUserInfo(john.Id, john.TenantId))).ShouldBeNull(); } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityRoleRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityRoleRepository_Tests.cs index d170a5b838..795ba45f42 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityRoleRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityRoleRepository_Tests.cs @@ -6,65 +6,64 @@ using Shouldly; using Volo.Abp.Modularity; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class IdentityRoleRepository_Tests : AbpIdentityTestBase + where TStartupModule : IAbpModule { - public abstract class IdentityRoleRepository_Tests : AbpIdentityTestBase - where TStartupModule : IAbpModule + protected IIdentityRoleRepository RoleRepository { get; } + protected ILookupNormalizer LookupNormalizer { get; } + + protected IdentityRoleRepository_Tests() { - protected IIdentityRoleRepository RoleRepository { get; } - protected ILookupNormalizer LookupNormalizer { get; } + RoleRepository = ServiceProvider.GetRequiredService(); + LookupNormalizer = ServiceProvider.GetRequiredService(); + } - protected IdentityRoleRepository_Tests() - { - RoleRepository = ServiceProvider.GetRequiredService(); - LookupNormalizer = ServiceProvider.GetRequiredService(); - } + [Fact] + public async Task FindByNormalizedNameAsync() + { + (await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("admin"))).ShouldNotBeNull(); + (await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("undefined-role"))).ShouldBeNull(); + } - [Fact] - public async Task FindByNormalizedNameAsync() - { - (await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("admin"))).ShouldNotBeNull(); - (await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("undefined-role"))).ShouldBeNull(); - } + [Fact] + public async Task GetListAsync() + { + var roles = await RoleRepository.GetListAsync(); + roles.ShouldContain(r => r.Name == "admin"); + roles.ShouldContain(r => r.Name == "moderator"); + roles.ShouldContain(r => r.Name == "supporter"); + } - [Fact] - public async Task GetListAsync() - { - var roles = await RoleRepository.GetListAsync(); - roles.ShouldContain(r => r.Name == "admin"); - roles.ShouldContain(r => r.Name == "moderator"); - roles.ShouldContain(r => r.Name == "supporter"); - } + [Fact] + public async Task GetDefaultOnesAsync() + { + var roles = await RoleRepository.GetDefaultOnesAsync(); - [Fact] - public async Task GetDefaultOnesAsync() + foreach (var role in roles) { - var roles = await RoleRepository.GetDefaultOnesAsync(); - - foreach (var role in roles) - { - role.IsDefault.ShouldBe(true); - } + role.IsDefault.ShouldBe(true); } + } - [Fact] - public async Task GetCountAsync() - { - (await RoleRepository.GetCountAsync()).ShouldBeGreaterThan(0); - } + [Fact] + public async Task GetCountAsync() + { + (await RoleRepository.GetCountAsync()).ShouldBeGreaterThan(0); + } - [Fact] - public async Task GetCountAsync_With_Filter() - { - (await RoleRepository.GetCountAsync("admin")).ShouldBe(1); - } + [Fact] + public async Task GetCountAsync_With_Filter() + { + (await RoleRepository.GetCountAsync("admin")).ShouldBe(1); + } - [Fact] - public async Task Should_Eager_Load_Role_Collections() - { - var role = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("moderator")); - role.Claims.ShouldNotBeNull(); - role.Claims.Any().ShouldBeTrue(); - } + [Fact] + public async Task Should_Eager_Load_Role_Collections() + { + var role = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("moderator")); + role.Claims.ShouldNotBeNull(); + role.Claims.Any().ShouldBeTrue(); } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentitySecurityLogRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentitySecurityLogRepository_Tests.cs index 13ff8a06a3..d930425076 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentitySecurityLogRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentitySecurityLogRepository_Tests.cs @@ -3,34 +3,33 @@ using Shouldly; using Volo.Abp.Modularity; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class IdentitySecurityLogRepository_Tests : AbpIdentityTestBase + where TStartupModule : IAbpModule { - public abstract class IdentitySecurityLogRepository_Tests : AbpIdentityTestBase - where TStartupModule : IAbpModule - { - protected IIdentitySecurityLogRepository RoleRepository { get; } - protected IdentityTestData TestData { get; } + protected IIdentitySecurityLogRepository RoleRepository { get; } + protected IdentityTestData TestData { get; } - protected IdentitySecurityLogRepository_Tests() - { - RoleRepository = GetRequiredService(); - TestData = GetRequiredService(); - } + protected IdentitySecurityLogRepository_Tests() + { + RoleRepository = GetRequiredService(); + TestData = GetRequiredService(); + } - [Fact] - public async Task GetListAsync() - { - var logs = await RoleRepository.GetListAsync(); - logs.ShouldNotBeEmpty(); - logs.ShouldContain(x => x.ApplicationName == "Test-ApplicationName" && x.UserId == TestData.UserJohnId); - logs.ShouldContain(x => x.ApplicationName == "Test-ApplicationName" && x.UserId == TestData.UserDavidId); - } + [Fact] + public async Task GetListAsync() + { + var logs = await RoleRepository.GetListAsync(); + logs.ShouldNotBeEmpty(); + logs.ShouldContain(x => x.ApplicationName == "Test-ApplicationName" && x.UserId == TestData.UserJohnId); + logs.ShouldContain(x => x.ApplicationName == "Test-ApplicationName" && x.UserId == TestData.UserDavidId); + } - [Fact] - public async Task GetCountAsync() - { - var count = await RoleRepository.GetCountAsync(); - count.ShouldBe(2); - } + [Fact] + public async Task GetCountAsync() + { + var count = await RoleRepository.GetCountAsync(); + count.ShouldBe(2); } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityTestData.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityTestData.cs index d2cb0f19b4..24a435aca1 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityTestData.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityTestData.cs @@ -1,17 +1,16 @@ using System; using Volo.Abp.DependencyInjection; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public class IdentityTestData : ISingletonDependency { - public class IdentityTestData : ISingletonDependency - { - public Guid RoleModeratorId { get; } = Guid.NewGuid(); + public Guid RoleModeratorId { get; } = Guid.NewGuid(); - public Guid UserJohnId { get; } = Guid.NewGuid(); - public Guid UserDavidId { get; } = Guid.NewGuid(); - public Guid UserNeoId { get; } = Guid.NewGuid(); - public Guid UserBobId { get; } = Guid.NewGuid(); - public Guid AgeClaimId { get; } = Guid.NewGuid(); - public Guid EducationClaimId { get; } = Guid.NewGuid(); - } + public Guid UserJohnId { get; } = Guid.NewGuid(); + public Guid UserDavidId { get; } = Guid.NewGuid(); + public Guid UserNeoId { get; } = Guid.NewGuid(); + public Guid UserBobId { get; } = Guid.NewGuid(); + public Guid AgeClaimId { get; } = Guid.NewGuid(); + public Guid EducationClaimId { get; } = Guid.NewGuid(); } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityUserRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityUserRepository_Tests.cs index 1d6728c0ae..de7f23cb4b 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityUserRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/IdentityUserRepository_Tests.cs @@ -8,172 +8,171 @@ using Shouldly; using Volo.Abp.Modularity; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class IdentityUserRepository_Tests : AbpIdentityTestBase + where TStartupModule : IAbpModule { - public abstract class IdentityUserRepository_Tests : AbpIdentityTestBase - where TStartupModule : IAbpModule + protected IIdentityUserRepository UserRepository { get; } + protected ILookupNormalizer LookupNormalizer { get; } + protected IOrganizationUnitRepository OrganizationUnitRepository { get; } + + protected IdentityUserRepository_Tests() { - protected IIdentityUserRepository UserRepository { get; } - protected ILookupNormalizer LookupNormalizer { get; } - protected IOrganizationUnitRepository OrganizationUnitRepository { get; } + UserRepository = ServiceProvider.GetRequiredService(); + LookupNormalizer = ServiceProvider.GetRequiredService(); + OrganizationUnitRepository = ServiceProvider.GetRequiredService(); + } - protected IdentityUserRepository_Tests() - { - UserRepository = ServiceProvider.GetRequiredService(); - LookupNormalizer = ServiceProvider.GetRequiredService(); - OrganizationUnitRepository = ServiceProvider.GetRequiredService(); - } + [Fact] + public async Task FindByNormalizedUserNameAsync() + { + (await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("john.nash"))).ShouldNotBeNull(); + (await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("undefined-user"))).ShouldBeNull(); + } - [Fact] - public async Task FindByNormalizedUserNameAsync() - { - (await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("john.nash"))).ShouldNotBeNull(); - (await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("undefined-user"))).ShouldBeNull(); - } + [Fact] + public async Task FindByNormalizedEmailAsync() + { + (await UserRepository.FindByNormalizedEmailAsync(LookupNormalizer.NormalizeEmail("john.nash@abp.io"))).ShouldNotBeNull(); + (await UserRepository.FindByNormalizedEmailAsync(LookupNormalizer.NormalizeEmail("david@abp.io"))).ShouldNotBeNull(); + (await UserRepository.FindByNormalizedEmailAsync(LookupNormalizer.NormalizeEmail("undefined-user@abp.io"))).ShouldBeNull(); + } - [Fact] - public async Task FindByNormalizedEmailAsync() - { - (await UserRepository.FindByNormalizedEmailAsync(LookupNormalizer.NormalizeEmail("john.nash@abp.io"))).ShouldNotBeNull(); - (await UserRepository.FindByNormalizedEmailAsync(LookupNormalizer.NormalizeEmail("david@abp.io"))).ShouldNotBeNull(); - (await UserRepository.FindByNormalizedEmailAsync(LookupNormalizer.NormalizeEmail("undefined-user@abp.io"))).ShouldBeNull(); - } + [Fact] + public async Task GetRoleNamesAsync() + { + var john = await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("john.nash")); + var roles = await UserRepository.GetRoleNamesAsync(john.Id); + roles.Count.ShouldBe(3); + roles.ShouldContain("moderator"); + roles.ShouldContain("supporter"); + roles.ShouldContain("manager"); + } - [Fact] - public async Task GetRoleNamesAsync() - { - var john = await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("john.nash")); - var roles = await UserRepository.GetRoleNamesAsync(john.Id); - roles.Count.ShouldBe(3); - roles.ShouldContain("moderator"); - roles.ShouldContain("supporter"); - roles.ShouldContain("manager"); - } + [Fact] + public async Task FindByLoginAsync() + { + var user = await UserRepository.FindByLoginAsync("github", "john"); + user.ShouldNotBeNull(); + user.UserName.ShouldBe("john.nash"); - [Fact] - public async Task FindByLoginAsync() - { - var user = await UserRepository.FindByLoginAsync("github", "john"); - user.ShouldNotBeNull(); - user.UserName.ShouldBe("john.nash"); + user = await UserRepository.FindByLoginAsync("twitter", "johnx"); + user.ShouldNotBeNull(); + user.UserName.ShouldBe("john.nash"); - user = await UserRepository.FindByLoginAsync("twitter", "johnx"); - user.ShouldNotBeNull(); - user.UserName.ShouldBe("john.nash"); + (await UserRepository.FindByLoginAsync("github", "undefinedid")).ShouldBeNull(); + } - (await UserRepository.FindByLoginAsync("github", "undefinedid")).ShouldBeNull(); - } + [Fact] + public async Task GetListByClaimAsync() + { + var users = await UserRepository.GetListByClaimAsync(new Claim("TestClaimType", "42")); + users.Count.ShouldBe(2); + users.ShouldContain(u => u.UserName == "administrator"); + users.ShouldContain(u => u.UserName == "john.nash"); - [Fact] - public async Task GetListByClaimAsync() - { - var users = await UserRepository.GetListByClaimAsync(new Claim("TestClaimType", "42")); - users.Count.ShouldBe(2); - users.ShouldContain(u => u.UserName == "administrator"); - users.ShouldContain(u => u.UserName == "john.nash"); + users = await UserRepository.GetListByClaimAsync(new Claim("TestClaimType", "43")); + users.Count.ShouldBe(1); + users.ShouldContain(u => u.UserName == "neo"); - users = await UserRepository.GetListByClaimAsync(new Claim("TestClaimType", "43")); - users.Count.ShouldBe(1); - users.ShouldContain(u => u.UserName == "neo"); + users = await UserRepository.GetListByClaimAsync(new Claim("TestClaimType", "undefined")); + users.Count.ShouldBe(0); + } - users = await UserRepository.GetListByClaimAsync(new Claim("TestClaimType", "undefined")); - users.Count.ShouldBe(0); - } + [Fact] + public async Task GetListByNormalizedRoleNameAsync() + { + var users = await UserRepository.GetListByNormalizedRoleNameAsync(LookupNormalizer.NormalizeName("supporter")); + users.Count.ShouldBe(2); + users.ShouldContain(u => u.UserName == "john.nash"); + users.ShouldContain(u => u.UserName == "neo"); + } - [Fact] - public async Task GetListByNormalizedRoleNameAsync() - { - var users = await UserRepository.GetListByNormalizedRoleNameAsync(LookupNormalizer.NormalizeName("supporter")); - users.Count.ShouldBe(2); - users.ShouldContain(u => u.UserName == "john.nash"); - users.ShouldContain(u => u.UserName == "neo"); - } + [Fact] + public async Task GetListAsync() + { + var users = await UserRepository.GetListAsync("UserName DESC", 5, 0, "n"); - [Fact] - public async Task GetListAsync() - { - var users = await UserRepository.GetListAsync("UserName DESC", 5, 0, "n"); - - users.Count.ShouldBeGreaterThan(1); - users.Count.ShouldBeLessThanOrEqualTo(5); - - //Filter check - users.ShouldAllBe(u => u.UserName.Contains("n") || u.Email.Contains("n")); - - //Order check - for (var i = 0; i < users.Count - 1; i++) - { - string.Compare( - users[i].UserName, - users[i + 1].UserName, - StringComparison.OrdinalIgnoreCase - ).ShouldBeGreaterThan(0); - } - - users = await UserRepository.GetListAsync(null, 999, 0, "undefined-username"); - users.Count.ShouldBe(0); - } + users.Count.ShouldBeGreaterThan(1); + users.Count.ShouldBeLessThanOrEqualTo(5); - [Fact] - public async Task GetRolesAsync() - { - var john = await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("john.nash")); - var roles = await UserRepository.GetRolesAsync(john.Id); - roles.Count.ShouldBe(3); - roles.ShouldContain(r => r.Name == "moderator"); - roles.ShouldContain(r => r.Name == "supporter"); - roles.ShouldContain(r => r.Name == "manager"); - } + //Filter check + users.ShouldAllBe(u => u.UserName.Contains("n") || u.Email.Contains("n")); - [Fact] - public async Task GetCountAsync() + //Order check + for (var i = 0; i < users.Count - 1; i++) { - (await UserRepository.GetCountAsync("n")).ShouldBeGreaterThan(1); - (await UserRepository.GetCountAsync("undefined-username")).ShouldBe(0); + string.Compare( + users[i].UserName, + users[i + 1].UserName, + StringComparison.OrdinalIgnoreCase + ).ShouldBeGreaterThan(0); } - [Fact] - public async Task GetUsersInOrganizationUnitAsync() - { - var users = await UserRepository.GetUsersInOrganizationUnitAsync((await GetOU("OU111")).Id); - users.ShouldNotBeNull(); - users.Count.ShouldBeGreaterThan(0); - } + users = await UserRepository.GetListAsync(null, 999, 0, "undefined-username"); + users.Count.ShouldBe(0); + } - [Fact] - public async Task GetUsersInOrganizationUnitWithChildrenAsync() - { - var users = await UserRepository.GetUsersInOrganizationUnitWithChildrenAsync((await GetOU("OU111")).Code); - users.ShouldNotBeNull(); - users.Count.ShouldBeGreaterThan(0); - } + [Fact] + public async Task GetRolesAsync() + { + var john = await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("john.nash")); + var roles = await UserRepository.GetRolesAsync(john.Id); + roles.Count.ShouldBe(3); + roles.ShouldContain(r => r.Name == "moderator"); + roles.ShouldContain(r => r.Name == "supporter"); + roles.ShouldContain(r => r.Name == "manager"); + } - [Fact] - public async Task Should_Eager_Load_User_Collections() - { - var john = await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("john.nash")); + [Fact] + public async Task GetCountAsync() + { + (await UserRepository.GetCountAsync("n")).ShouldBeGreaterThan(1); + (await UserRepository.GetCountAsync("undefined-username")).ShouldBe(0); + } - john.Roles.ShouldNotBeNull(); - john.Roles.Any().ShouldBeTrue(); + [Fact] + public async Task GetUsersInOrganizationUnitAsync() + { + var users = await UserRepository.GetUsersInOrganizationUnitAsync((await GetOU("OU111")).Id); + users.ShouldNotBeNull(); + users.Count.ShouldBeGreaterThan(0); + } - john.Logins.ShouldNotBeNull(); - john.Logins.Any().ShouldBeTrue(); + [Fact] + public async Task GetUsersInOrganizationUnitWithChildrenAsync() + { + var users = await UserRepository.GetUsersInOrganizationUnitWithChildrenAsync((await GetOU("OU111")).Code); + users.ShouldNotBeNull(); + users.Count.ShouldBeGreaterThan(0); + } - john.Claims.ShouldNotBeNull(); - john.Claims.Any().ShouldBeTrue(); + [Fact] + public async Task Should_Eager_Load_User_Collections() + { + var john = await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("john.nash")); - john.Tokens.ShouldNotBeNull(); - john.Tokens.Any().ShouldBeTrue(); + john.Roles.ShouldNotBeNull(); + john.Roles.Any().ShouldBeTrue(); - john.OrganizationUnits.ShouldNotBeNull(); - john.OrganizationUnits.Any().ShouldBeTrue(); - } + john.Logins.ShouldNotBeNull(); + john.Logins.Any().ShouldBeTrue(); - private async Task GetOU(string diplayName) - { - var organizationUnit = await OrganizationUnitRepository.GetAsync(diplayName); - organizationUnit.ShouldNotBeNull(); - return organizationUnit; - } + john.Claims.ShouldNotBeNull(); + john.Claims.Any().ShouldBeTrue(); + + john.Tokens.ShouldNotBeNull(); + john.Tokens.Any().ShouldBeTrue(); + + john.OrganizationUnits.ShouldNotBeNull(); + john.OrganizationUnits.Any().ShouldBeTrue(); + } + + private async Task GetOU(string diplayName) + { + var organizationUnit = await OrganizationUnitRepository.GetAsync(diplayName); + organizationUnit.ShouldNotBeNull(); + return organizationUnit; } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/Identity_Repository_Resolve_Tests.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/Identity_Repository_Resolve_Tests.cs index 6d541d5987..a71059840f 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/Identity_Repository_Resolve_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/Identity_Repository_Resolve_Tests.cs @@ -5,23 +5,22 @@ using Volo.Abp.Domain.Repositories; using Volo.Abp.Modularity; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class Identity_Repository_Resolve_Tests : AbpIdentityTestBase + where TStartupModule : IAbpModule { - public abstract class Identity_Repository_Resolve_Tests : AbpIdentityTestBase - where TStartupModule : IAbpModule + [Fact] //Move this test to Volo.Abp.EntityFrameworkCore.Tests since it's actually testing the EF Core repository registration! + public void Should_Resolve_Repositories() { - [Fact] //Move this test to Volo.Abp.EntityFrameworkCore.Tests since it's actually testing the EF Core repository registration! - public void Should_Resolve_Repositories() - { - ServiceProvider.GetService>().ShouldNotBeNull(); - ServiceProvider.GetService>().ShouldNotBeNull(); - ServiceProvider.GetService().ShouldNotBeNull(); + ServiceProvider.GetService>().ShouldNotBeNull(); + ServiceProvider.GetService>().ShouldNotBeNull(); + ServiceProvider.GetService().ShouldNotBeNull(); - ServiceProvider.GetService>().ShouldNotBeNull(); - ServiceProvider.GetService>().ShouldNotBeNull(); - ServiceProvider.GetService().ShouldNotBeNull(); + ServiceProvider.GetService>().ShouldNotBeNull(); + ServiceProvider.GetService>().ShouldNotBeNull(); + ServiceProvider.GetService().ShouldNotBeNull(); - ServiceProvider.GetService().ShouldNotBeNull(); - } + ServiceProvider.GetService().ShouldNotBeNull(); } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/LazyLoading_Tests.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/LazyLoading_Tests.cs index eae5ee5c1d..ed655cf77e 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/LazyLoading_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/LazyLoading_Tests.cs @@ -7,74 +7,73 @@ using Volo.Abp.Modularity; using Volo.Abp.Uow; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class LazyLoading_Tests : AbpIdentityTestBase + where TStartupModule : IAbpModule { - public abstract class LazyLoading_Tests : AbpIdentityTestBase - where TStartupModule : IAbpModule - { - protected IIdentityUserRepository UserRepository { get; } - protected IIdentityRoleRepository RoleRepository { get; } - protected IOrganizationUnitRepository OrganizationUnitRepository { get; } - protected ILookupNormalizer LookupNormalizer { get; } + protected IIdentityUserRepository UserRepository { get; } + protected IIdentityRoleRepository RoleRepository { get; } + protected IOrganizationUnitRepository OrganizationUnitRepository { get; } + protected ILookupNormalizer LookupNormalizer { get; } - protected LazyLoading_Tests() - { - UserRepository = ServiceProvider.GetRequiredService(); - RoleRepository = ServiceProvider.GetRequiredService(); - LookupNormalizer = ServiceProvider.GetRequiredService(); - OrganizationUnitRepository = ServiceProvider.GetRequiredService(); - } + protected LazyLoading_Tests() + { + UserRepository = ServiceProvider.GetRequiredService(); + RoleRepository = ServiceProvider.GetRequiredService(); + LookupNormalizer = ServiceProvider.GetRequiredService(); + OrganizationUnitRepository = ServiceProvider.GetRequiredService(); + } - [Fact] - public async Task Should_Lazy_Load_Role_Collections() + [Fact] + public async Task Should_Lazy_Load_Role_Collections() + { + using (var uow = GetRequiredService().Begin()) { - using (var uow = GetRequiredService().Begin()) - { - var role = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("moderator"), includeDetails: false); - role.Claims.ShouldNotBeNull(); - role.Claims.Any().ShouldBeTrue(); + var role = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("moderator"), includeDetails: false); + role.Claims.ShouldNotBeNull(); + role.Claims.Any().ShouldBeTrue(); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task Should_Lazy_Load_User_Collections() + [Fact] + public async Task Should_Lazy_Load_User_Collections() + { + using (var uow = GetRequiredService().Begin()) { - using (var uow = GetRequiredService().Begin()) - { - var john = await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("john.nash"), includeDetails: false); + var john = await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName("john.nash"), includeDetails: false); - john.Roles.ShouldNotBeNull(); - john.Roles.Any().ShouldBeTrue(); + john.Roles.ShouldNotBeNull(); + john.Roles.Any().ShouldBeTrue(); - john.Logins.ShouldNotBeNull(); - john.Logins.Any().ShouldBeTrue(); + john.Logins.ShouldNotBeNull(); + john.Logins.Any().ShouldBeTrue(); - john.Claims.ShouldNotBeNull(); - john.Claims.Any().ShouldBeTrue(); + john.Claims.ShouldNotBeNull(); + john.Claims.Any().ShouldBeTrue(); - john.Tokens.ShouldNotBeNull(); - john.Tokens.Any().ShouldBeTrue(); + john.Tokens.ShouldNotBeNull(); + john.Tokens.Any().ShouldBeTrue(); - john.OrganizationUnits.ShouldNotBeNull(); - john.OrganizationUnits.Any().ShouldBeTrue(); + john.OrganizationUnits.ShouldNotBeNull(); + john.OrganizationUnits.Any().ShouldBeTrue(); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task Should_Lazy_Load_OrganizationUnit_Collections() + [Fact] + public async Task Should_Lazy_Load_OrganizationUnit_Collections() + { + using (var uow = GetRequiredService().Begin()) { - using (var uow = GetRequiredService().Begin()) - { - var ou = await OrganizationUnitRepository.GetAsync(LookupNormalizer.NormalizeName("OU111"), includeDetails: false); - ou.Roles.ShouldNotBeNull(); //? - ou.Roles.Any().ShouldBeTrue(); + var ou = await OrganizationUnitRepository.GetAsync(LookupNormalizer.NormalizeName("OU111"), includeDetails: false); + ou.Roles.ShouldNotBeNull(); //? + ou.Roles.Any().ShouldBeTrue(); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } } } diff --git a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/OrganizationUnitRepository_Tests.cs b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/OrganizationUnitRepository_Tests.cs index a671ba3284..04deba09fe 100644 --- a/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/OrganizationUnitRepository_Tests.cs +++ b/modules/identity/test/Volo.Abp.Identity.TestBase/Volo/Abp/Identity/OrganizationUnitRepository_Tests.cs @@ -10,317 +10,316 @@ using Volo.Abp.Modularity; using Volo.Abp.Uow; using Xunit; -namespace Volo.Abp.Identity +namespace Volo.Abp.Identity; + +public abstract class OrganizationUnitRepository_Tests : AbpIdentityTestBase + where TStartupModule : IAbpModule { - public abstract class OrganizationUnitRepository_Tests : AbpIdentityTestBase - where TStartupModule : IAbpModule + private readonly IOrganizationUnitRepository _organizationUnitRepository; + private readonly IIdentityRoleRepository _identityRoleRepository; + private readonly ILookupNormalizer _lookupNormalizer; + private readonly IdentityTestData _testData; + private readonly IGuidGenerator _guidGenerator; + private readonly OrganizationUnitManager _organizationUnitManager; + private readonly IdentityUserManager _identityUserManager; + private readonly IUnitOfWorkManager _unitOfWorkManager; + private readonly IIdentityUserRepository _identityUserRepository; + + public OrganizationUnitRepository_Tests() { - private readonly IOrganizationUnitRepository _organizationUnitRepository; - private readonly IIdentityRoleRepository _identityRoleRepository; - private readonly ILookupNormalizer _lookupNormalizer; - private readonly IdentityTestData _testData; - private readonly IGuidGenerator _guidGenerator; - private readonly OrganizationUnitManager _organizationUnitManager; - private readonly IdentityUserManager _identityUserManager; - private readonly IUnitOfWorkManager _unitOfWorkManager; - private readonly IIdentityUserRepository _identityUserRepository; - - public OrganizationUnitRepository_Tests() - { - _organizationUnitRepository = ServiceProvider.GetRequiredService(); - _identityRoleRepository = ServiceProvider.GetRequiredService(); - _lookupNormalizer = ServiceProvider.GetRequiredService(); - _testData = GetRequiredService(); - _guidGenerator = GetRequiredService(); - _organizationUnitManager = GetRequiredService(); - _identityUserManager = GetRequiredService(); - _unitOfWorkManager = GetRequiredService(); - _identityUserRepository = GetRequiredService(); - } + _organizationUnitRepository = ServiceProvider.GetRequiredService(); + _identityRoleRepository = ServiceProvider.GetRequiredService(); + _lookupNormalizer = ServiceProvider.GetRequiredService(); + _testData = GetRequiredService(); + _guidGenerator = GetRequiredService(); + _organizationUnitManager = GetRequiredService(); + _identityUserManager = GetRequiredService(); + _unitOfWorkManager = GetRequiredService(); + _identityUserRepository = GetRequiredService(); + } - [Fact] - public async Task GetChildrenAsync() - { - (await _organizationUnitRepository.GetChildrenAsync(_testData.RoleModeratorId)).ShouldNotBeNull(); - } + [Fact] + public async Task GetChildrenAsync() + { + (await _organizationUnitRepository.GetChildrenAsync(_testData.RoleModeratorId)).ShouldNotBeNull(); + } - [Fact] - public async Task GetAllChildrenWithParentCodeAsync() - { - (await _organizationUnitRepository.GetAllChildrenWithParentCodeAsync(OrganizationUnit.CreateCode(0), - _guidGenerator.Create())).ShouldNotBeNull(); - } + [Fact] + public async Task GetAllChildrenWithParentCodeAsync() + { + (await _organizationUnitRepository.GetAllChildrenWithParentCodeAsync(OrganizationUnit.CreateCode(0), + _guidGenerator.Create())).ShouldNotBeNull(); + } - [Fact] - public async Task GetListAsync() - { - var ouIds = (await _organizationUnitRepository.GetListAsync(includeDetails: true)) - .Select(ou => ou.Id).Take(2); - var ous = await _organizationUnitRepository.GetListAsync(ouIds); - ous.Count.ShouldBe(2); - ous.ShouldContain(ou => ou.Id == ouIds.First()); - } + [Fact] + public async Task GetListAsync() + { + var ouIds = (await _organizationUnitRepository.GetListAsync(includeDetails: true)) + .Select(ou => ou.Id).Take(2); + var ous = await _organizationUnitRepository.GetListAsync(ouIds); + ous.Count.ShouldBe(2); + ous.ShouldContain(ou => ou.Id == ouIds.First()); + } - [Fact] - public async Task AddMemberToOrganizationUnit() + [Fact] + public async Task AddMemberToOrganizationUnit() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var ou111 = await _organizationUnitRepository.GetAsync( - _lookupNormalizer.NormalizeName("OU111")); - var user = await _identityUserRepository.FindByNormalizedUserNameAsync( - _lookupNormalizer.NormalizeName("david")); - user.ShouldNotBeNull(); + var ou111 = await _organizationUnitRepository.GetAsync( + _lookupNormalizer.NormalizeName("OU111")); + var user = await _identityUserRepository.FindByNormalizedUserNameAsync( + _lookupNormalizer.NormalizeName("david")); + user.ShouldNotBeNull(); - user.OrganizationUnits.Count.ShouldBe(1); - await _identityUserManager.AddToOrganizationUnitAsync(user.Id, ou111.Id); + user.OrganizationUnits.Count.ShouldBe(1); + await _identityUserManager.AddToOrganizationUnitAsync(user.Id, ou111.Id); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); + } - var updatedUser = await _identityUserRepository.FindByNormalizedUserNameAsync( - _lookupNormalizer.NormalizeName("david")); - updatedUser.OrganizationUnits.Count.ShouldBe(2); + var updatedUser = await _identityUserRepository.FindByNormalizedUserNameAsync( + _lookupNormalizer.NormalizeName("david")); + updatedUser.OrganizationUnits.Count.ShouldBe(2); + } + + [Fact] + public async Task AddRoleToOrganizationUnit() + { + using (var uow = _unitOfWorkManager.Begin()) + { + var ou111 = await _organizationUnitRepository.GetAsync( + _lookupNormalizer.NormalizeName("OU111")); + ou111.Roles.Count.ShouldBe(2); + var roleSupporter = await _identityRoleRepository.FindByNormalizedNameAsync( + _lookupNormalizer.NormalizeName("supporter")); + + await _organizationUnitManager.AddRoleToOrganizationUnitAsync(roleSupporter.Id, ou111.Id); + await uow.CompleteAsync(); } - [Fact] - public async Task AddRoleToOrganizationUnit() + var ou111Updated = await _organizationUnitRepository.GetAsync( + _lookupNormalizer.NormalizeName("OU111")); + ou111Updated.Roles.Count.ShouldBeGreaterThan(2); + } + + [Fact] + public async Task RemoveRoleFromOrganizationUnit() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var ou111 = await _organizationUnitRepository.GetAsync( - _lookupNormalizer.NormalizeName("OU111")); - ou111.Roles.Count.ShouldBe(2); - var roleSupporter = await _identityRoleRepository.FindByNormalizedNameAsync( - _lookupNormalizer.NormalizeName("supporter")); - - await _organizationUnitManager.AddRoleToOrganizationUnitAsync(roleSupporter.Id, ou111.Id); - await uow.CompleteAsync(); - } - - var ou111Updated = await _organizationUnitRepository.GetAsync( + var ou111 = await _organizationUnitRepository.GetAsync( _lookupNormalizer.NormalizeName("OU111")); - ou111Updated.Roles.Count.ShouldBeGreaterThan(2); + ou111.Roles.ShouldContain(q => q.RoleId == _testData.RoleModeratorId); + + await _organizationUnitManager.RemoveRoleFromOrganizationUnitAsync(_testData.RoleModeratorId, ou111.Id); + await uow.CompleteAsync(); } - [Fact] - public async Task RemoveRoleFromOrganizationUnit() + var ou111Updated = await _organizationUnitRepository.GetAsync( + _lookupNormalizer.NormalizeName("OU111")); + ou111Updated.Roles.ShouldNotContain(q => q.RoleId == _testData.RoleModeratorId); + } + + [Fact] + public async Task RemoveOrganizationUnitFromUser() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - var ou111 = await _organizationUnitRepository.GetAsync( - _lookupNormalizer.NormalizeName("OU111")); - ou111.Roles.ShouldContain(q => q.RoleId == _testData.RoleModeratorId); + var ou112 = await _organizationUnitRepository.GetAsync( + _lookupNormalizer.NormalizeName("OU112")); + var user = await _identityUserRepository.FindByNormalizedUserNameAsync( + _lookupNormalizer.NormalizeName("david")); - await _organizationUnitManager.RemoveRoleFromOrganizationUnitAsync(_testData.RoleModeratorId, ou111.Id); - await uow.CompleteAsync(); - } + user.OrganizationUnits.Count.ShouldBe(1); + user.OrganizationUnits.ShouldContain(q => q.OrganizationUnitId == ou112.Id); - var ou111Updated = await _organizationUnitRepository.GetAsync( - _lookupNormalizer.NormalizeName("OU111")); - ou111Updated.Roles.ShouldNotContain(q => q.RoleId == _testData.RoleModeratorId); + await _identityUserManager.RemoveFromOrganizationUnitAsync(user.Id, ou112.Id); + await uow.CompleteAsync(); } - [Fact] - public async Task RemoveOrganizationUnitFromUser() - { - using (var uow = _unitOfWorkManager.Begin()) - { - var ou112 = await _organizationUnitRepository.GetAsync( - _lookupNormalizer.NormalizeName("OU112")); - var user = await _identityUserRepository.FindByNormalizedUserNameAsync( - _lookupNormalizer.NormalizeName("david")); + var updatedUser = await _identityUserRepository.FindByNormalizedUserNameAsync( + _lookupNormalizer.NormalizeName("david")); + updatedUser.OrganizationUnits.Count.ShouldBe(0); + } - user.OrganizationUnits.Count.ShouldBe(1); - user.OrganizationUnits.ShouldContain(q => q.OrganizationUnitId == ou112.Id); + [Fact] + public async Task GetOrganizationUnitAsync() + { + var organizationUnit = await _organizationUnitRepository.GetAsync("OU111"); + organizationUnit.ShouldNotBeNull(); + } - await _identityUserManager.RemoveFromOrganizationUnitAsync(user.Id, ou112.Id); - await uow.CompleteAsync(); - } + [Fact] + public async Task GetCountAsync() + { + (await _organizationUnitRepository.GetCountAsync()).ShouldBeGreaterThan(0); + } - var updatedUser = await _identityUserRepository.FindByNormalizedUserNameAsync( - _lookupNormalizer.NormalizeName("david")); - updatedUser.OrganizationUnits.Count.ShouldBe(0); - } + [Fact] + public async Task Should_Eager_Load_OrganizationUnit_Collections() + { + var ou = (await _organizationUnitRepository.GetListAsync(includeDetails: true)) + .FirstOrDefault(ou => ou.DisplayName == "OU111"); + ou.Roles.ShouldNotBeNull(); + ou.Roles.Any().ShouldBeTrue(); + } - [Fact] - public async Task GetOrganizationUnitAsync() - { - var organizationUnit = await _organizationUnitRepository.GetAsync("OU111"); - organizationUnit.ShouldNotBeNull(); - } + [Fact] + public async Task GetOrganizationUnitRolesAsync() + { + OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", includeDetails: true); - [Fact] - public async Task GetCountAsync() - { - (await _organizationUnitRepository.GetCountAsync()).ShouldBeGreaterThan(0); - } + var ou111Roles = await _organizationUnitRepository.GetRolesAsync(ou, includeDetails: true); + ou111Roles.Count.ShouldBe(2); + ou111Roles.ShouldContain(n => n.Name == "manager"); + ou111Roles.ShouldContain(n => n.Name == "moderator"); + } - [Fact] - public async Task Should_Eager_Load_OrganizationUnit_Collections() - { - var ou = (await _organizationUnitRepository.GetListAsync(includeDetails: true)) - .FirstOrDefault(ou => ou.DisplayName == "OU111"); - ou.Roles.ShouldNotBeNull(); - ou.Roles.Any().ShouldBeTrue(); - } + [Fact] + public async Task GetOrganizationUnitRolesWithPagingAsync() + { + OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", includeDetails: true); - [Fact] - public async Task GetOrganizationUnitRolesAsync() - { - OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", includeDetails: true); + var ou111Roles = await _organizationUnitRepository.GetRolesAsync(ou, sorting: "name desc", + maxResultCount: 1, includeDetails: true); + ou111Roles.Count.ShouldBe(1); + ou111Roles.ShouldContain(n => n.Name == "moderator"); + } - var ou111Roles = await _organizationUnitRepository.GetRolesAsync(ou, includeDetails: true); - ou111Roles.Count.ShouldBe(2); - ou111Roles.ShouldContain(n => n.Name == "manager"); - ou111Roles.ShouldContain(n => n.Name == "moderator"); - } + [Fact] + public async Task GetMembersInOrganizationUnitListAsync() + { + OrganizationUnit ou1 = await _organizationUnitRepository.GetAsync("OU111", true); + OrganizationUnit ou2 = await _organizationUnitRepository.GetAsync("OU112", true); + var users = await _identityUserRepository.GetUsersInOrganizationsListAsync(new List { ou1.Id, ou2.Id }); + users.Count.ShouldBeGreaterThan(0); + } - [Fact] - public async Task GetOrganizationUnitRolesWithPagingAsync() - { - OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", includeDetails: true); + [Fact] + public async Task GetMembersInOrganizationUnitWithParamsAsync() + { + OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); + var users = await _organizationUnitRepository.GetMembersAsync(ou, "UserName DESC", 5, 0, "n"); - var ou111Roles = await _organizationUnitRepository.GetRolesAsync(ou, sorting: "name desc", - maxResultCount: 1, includeDetails: true); - ou111Roles.Count.ShouldBe(1); - ou111Roles.ShouldContain(n => n.Name == "moderator"); - } + users.Count.ShouldBeGreaterThan(1); + users.Count.ShouldBeLessThanOrEqualTo(5); - [Fact] - public async Task GetMembersInOrganizationUnitListAsync() - { - OrganizationUnit ou1 = await _organizationUnitRepository.GetAsync("OU111", true); - OrganizationUnit ou2 = await _organizationUnitRepository.GetAsync("OU112", true); - var users = await _identityUserRepository.GetUsersInOrganizationsListAsync(new List {ou1.Id, ou2.Id}); - users.Count.ShouldBeGreaterThan(0); - } + //Filter check + users.ShouldAllBe(u => u.UserName.Contains("ne") || u.Email.Contains("n")); - [Fact] - public async Task GetMembersInOrganizationUnitWithParamsAsync() + //Order check + for (var i = 0; i < users.Count - 1; i++) { - OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); - var users = await _organizationUnitRepository.GetMembersAsync(ou, "UserName DESC", 5, 0, "n"); - - users.Count.ShouldBeGreaterThan(1); - users.Count.ShouldBeLessThanOrEqualTo(5); - - //Filter check - users.ShouldAllBe(u => u.UserName.Contains("ne") || u.Email.Contains("n")); - - //Order check - for (var i = 0; i < users.Count - 1; i++) - { - string.Compare( - users[i].UserName, - users[i + 1].UserName, - StringComparison.OrdinalIgnoreCase - ).ShouldBeGreaterThan(0); - } - - users = await _organizationUnitRepository.GetMembersAsync(ou, null, 999, 0, "undefined-username"); - users.Count.ShouldBe(0); + string.Compare( + users[i].UserName, + users[i + 1].UserName, + StringComparison.OrdinalIgnoreCase + ).ShouldBeGreaterThan(0); } - [Fact] - public async Task GetMembersCountOfOrganizationUnit() - { - OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); - var usersCount = await _organizationUnitRepository.GetMembersCountAsync(ou); + users = await _organizationUnitRepository.GetMembersAsync(ou, null, 999, 0, "undefined-username"); + users.Count.ShouldBe(0); + } - usersCount.ShouldBeGreaterThan(1); - } + [Fact] + public async Task GetMembersCountOfOrganizationUnit() + { + OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); + var usersCount = await _organizationUnitRepository.GetMembersCountAsync(ou); - [Fact] - public async Task GetMembersCountOfOrganizationUnitWithParamsAsync() - { - OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); - var usersCount = await _organizationUnitRepository.GetMembersCountAsync(ou, "n"); + usersCount.ShouldBeGreaterThan(1); + } - usersCount.ShouldBeGreaterThan(1); - usersCount.ShouldBeLessThanOrEqualTo(5); + [Fact] + public async Task GetMembersCountOfOrganizationUnitWithParamsAsync() + { + OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); + var usersCount = await _organizationUnitRepository.GetMembersCountAsync(ou, "n"); - usersCount = await _organizationUnitRepository.GetMembersCountAsync(ou, "undefined-username"); - usersCount.ShouldBe(0); - } + usersCount.ShouldBeGreaterThan(1); + usersCount.ShouldBeLessThanOrEqualTo(5); - [Fact] - public async Task GetRolesCountOfOrganizationUnit() - { - OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); - var rolesCount = await _organizationUnitRepository.GetRolesCountAsync(ou); + usersCount = await _organizationUnitRepository.GetMembersCountAsync(ou, "undefined-username"); + usersCount.ShouldBe(0); + } - rolesCount.ShouldBeGreaterThan(1); - } + [Fact] + public async Task GetRolesCountOfOrganizationUnit() + { + OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); + var rolesCount = await _organizationUnitRepository.GetRolesCountAsync(ou); - [Fact] - public async Task RemoveAllMembersOfOrganizationUnit() - { - OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); - var membersCount = await _organizationUnitRepository.GetMembersCountAsync(ou); - membersCount.ShouldBeGreaterThan(1); + rolesCount.ShouldBeGreaterThan(1); + } - await _organizationUnitRepository.RemoveAllMembersAsync(ou); - var newCount = await _organizationUnitRepository.GetMembersCountAsync(ou); - newCount.ShouldBe(0); - } + [Fact] + public async Task RemoveAllMembersOfOrganizationUnit() + { + OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); + var membersCount = await _organizationUnitRepository.GetMembersCountAsync(ou); + membersCount.ShouldBeGreaterThan(1); + + await _organizationUnitRepository.RemoveAllMembersAsync(ou); + var newCount = await _organizationUnitRepository.GetMembersCountAsync(ou); + newCount.ShouldBe(0); + } - [Fact] - public async Task RemoveAllRolesOfOrganizationUnit() + [Fact] + public async Task RemoveAllRolesOfOrganizationUnit() + { + using (var uow = _unitOfWorkManager.Begin()) { - using (var uow = _unitOfWorkManager.Begin()) - { - OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); - var rolesCount = await _organizationUnitRepository.GetRolesCountAsync(ou); - rolesCount.ShouldBeGreaterThan(1); + OrganizationUnit ou = await _organizationUnitRepository.GetAsync("OU111", true); + var rolesCount = await _organizationUnitRepository.GetRolesCountAsync(ou); + rolesCount.ShouldBeGreaterThan(1); - await _organizationUnitRepository.RemoveAllRolesAsync(ou); + await _organizationUnitRepository.RemoveAllRolesAsync(ou); - await uow.SaveChangesAsync(); + await uow.SaveChangesAsync(); - var newCount = await _organizationUnitRepository.GetRolesCountAsync(ou); - newCount.ShouldBe(0); + var newCount = await _organizationUnitRepository.GetRolesCountAsync(ou); + newCount.ShouldBe(0); - await uow.CompleteAsync(); - } + await uow.CompleteAsync(); } + } - [Fact] - public async Task GetUnaddedUsersOfOrganizationUnitAsync() - { - var ou = await _organizationUnitRepository.GetAsync("OU111", true); - var unaddedUsers = await _organizationUnitRepository.GetUnaddedUsersAsync(ou); + [Fact] + public async Task GetUnaddedUsersOfOrganizationUnitAsync() + { + var ou = await _organizationUnitRepository.GetAsync("OU111", true); + var unaddedUsers = await _organizationUnitRepository.GetUnaddedUsersAsync(ou); - unaddedUsers.ShouldNotContain(u => u.UserName == "john.nash"); - unaddedUsers.ShouldContain(u => u.UserName == "administrator"); - } + unaddedUsers.ShouldNotContain(u => u.UserName == "john.nash"); + unaddedUsers.ShouldContain(u => u.UserName == "administrator"); + } - [Fact] - public async Task GetUnaddedRolesOfOrganizationUnitAsync() - { - var ou = await _organizationUnitRepository.GetAsync("OU111", true); - var unaddedRoles = await _organizationUnitRepository.GetUnaddedRolesAsync(ou); + [Fact] + public async Task GetUnaddedRolesOfOrganizationUnitAsync() + { + var ou = await _organizationUnitRepository.GetAsync("OU111", true); + var unaddedRoles = await _organizationUnitRepository.GetUnaddedRolesAsync(ou); - unaddedRoles.ShouldNotContain(u => u.Name == "manager"); - unaddedRoles.ShouldNotContain(u => u.Name == "moderator"); - unaddedRoles.ShouldContain(u => u.Name.Contains("admin")); - } + unaddedRoles.ShouldNotContain(u => u.Name == "manager"); + unaddedRoles.ShouldNotContain(u => u.Name == "moderator"); + unaddedRoles.ShouldContain(u => u.Name.Contains("admin")); + } - [Fact] - public async Task GetUnaddedUsersCountOfOrganizationUnitAsync() - { - var ou = await _organizationUnitRepository.GetAsync("OU111", true); - var count = await _organizationUnitRepository.GetUnaddedUsersCountAsync(ou); - count.ShouldBeGreaterThan(0); + [Fact] + public async Task GetUnaddedUsersCountOfOrganizationUnitAsync() + { + var ou = await _organizationUnitRepository.GetAsync("OU111", true); + var count = await _organizationUnitRepository.GetUnaddedUsersCountAsync(ou); + count.ShouldBeGreaterThan(0); - } + } - [Fact] - public async Task GetUnaddedRolesCountOfOrganizationUnitAsync() - { - var ou = await _organizationUnitRepository.GetAsync("OU111", true); - var count = await _organizationUnitRepository.GetUnaddedRolesCountAsync(ou); - count.ShouldBeGreaterThan(0); - } + [Fact] + public async Task GetUnaddedRolesCountOfOrganizationUnitAsync() + { + var ou = await _organizationUnitRepository.GetAsync("OU111", true); + var count = await _organizationUnitRepository.GetUnaddedRolesCountAsync(ou); + count.ShouldBeGreaterThan(0); } }