Browse Source

use file-scoped namespacing for identity module

pull/10696/head
Ahmet Çotur 5 years ago
parent
commit
579d898ba1
  1. 63
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/AbpIdentityApplicationContractsModule.cs
  2. 9
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityRolesInput.cs
  3. 9
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityUsersInput.cs
  4. 21
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityRoleAppService.cs
  5. 29
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityUserAppService.cs
  6. 17
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IIdentityUserLookupAppService.cs
  7. 45
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityPermissionDefinitionProvider.cs
  8. 57
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityPermissions.cs
  9. 11
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRemoteServiceConsts.cs
  10. 9
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleCreateDto.cs
  11. 25
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleCreateOrUpdateDtoBase.cs
  12. 21
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleDto.cs
  13. 11
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleUpdateDto.cs
  14. 17
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserCreateDto.cs
  15. 45
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserCreateOrUpdateDtoBase.cs
  16. 31
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserDto.cs
  17. 19
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserUpdateDto.cs
  18. 13
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserUpdateRolesDto.cs
  19. 11
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/UserLookupCountInputDto.cs
  20. 11
      modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/UserLookupSearchInputDto.cs
  21. 33
      modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/AbpIdentityApplicationModule.cs
  22. 17
      modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/AbpIdentityApplicationModuleAutoMapperProfile.cs
  23. 13
      modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityAppServiceBase.cs
  24. 149
      modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityRoleAppService.cs
  25. 273
      modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityUserAppService.cs
  26. 85
      modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityUserLookupAppService.cs
  27. 61
      modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreModule.cs
  28. 15
      modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreOptions.cs
  29. 67
      modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSecurityStampValidator.cs
  30. 37
      modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSecurityStampValidatorCallback.cs
  31. 107
      modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSignInManager.cs
  32. 17
      modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/LinkUserTokenProvider.cs
  33. 47
      modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/SignInResultExtensions.cs
  34. 15
      modules/identity/src/Volo.Abp.Identity.Blazor.Server/AbpIdentityBlazorServerModule.cs
  35. 17
      modules/identity/src/Volo.Abp.Identity.Blazor.WebAssembly/AbpIdentityBlazorWebAssemblyModule.cs
  36. 23
      modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityBlazorAutoMapperProfile.cs
  37. 87
      modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityBlazorModule.cs
  38. 43
      modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityWebMainMenuContributor.cs
  39. 13
      modules/identity/src/Volo.Abp.Identity.Blazor/IdentityMenuNames.cs
  40. 125
      modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/RoleManagement.razor.cs
  41. 11
      modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/RoleNameComponent.razor.cs
  42. 227
      modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/UserManagement.razor.cs
  43. 49
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/AbpIdentityDomainSharedModule.cs
  44. 9
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IUserRoleFinder.cs
  45. 45
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimTypeConsts.cs
  46. 27
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimTypeEto.cs
  47. 15
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimValueType.cs
  48. 23
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityErrorCodes.cs
  49. 11
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleClaimConsts.cs
  50. 25
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleConsts.cs
  51. 27
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleEto.cs
  52. 19
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleNameChangedEto.cs
  53. 35
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogActionConsts.cs
  54. 99
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogConsts.cs
  55. 13
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentitySecurityLogIdentityConsts.cs
  56. 23
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserClaimConsts.cs
  57. 53
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserConsts.cs
  58. 35
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserLoginConsts.cs
  59. 23
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserTokenConsts.cs
  60. 13
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/LinkUserTokenProviderConsts.cs
  61. 11
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Localization/IdentityResource.cs
  62. 39
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/OrganizationUnitConsts.cs
  63. 19
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/OrganizationUnitEto.cs
  64. 95
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Settings/IdentitySettingNames.cs
  65. 71
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfiguration.cs
  66. 21
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfigurationDictionaryExtensions.cs
  67. 23
      modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConsts.cs
  68. 195
      modules/identity/src/Volo.Abp.Identity.Domain/Microsoft/AspNetCore/Identity/AbpIdentityResultExtensions.cs
  69. 49
      modules/identity/src/Volo.Abp.Identity.Domain/Microsoft/Extensions/DependencyInjection/AbpIdentityServiceCollectionExtensions.cs
  70. 13
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityDbProperties.cs
  71. 127
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityDomainModule.cs
  72. 15
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityOptions.cs
  73. 47
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityOptionsManager.cs
  74. 55
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityResultException.cs
  75. 201
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentitySettingDefinitionProvider.cs
  76. 103
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpUserClaimsPrincipalFactory.cs
  77. 231
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderBase.cs
  78. 19
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderDictionary.cs
  79. 32
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderInfo.cs
  80. 45
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginUserInfo.cs
  81. 51
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IExternalLoginProvider.cs
  82. 59
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIDentityClaimTypeRepository.cs
  83. 17
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityDataSeeder.cs
  84. 29
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityLinkUserRepository.cs
  85. 59
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityRoleRepository.cs
  86. 69
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentitySecurityLogRepository.cs
  87. 167
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityUserRepository.cs
  88. 215
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IOrganizationUnitRepository.cs
  89. 101
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaim.cs
  90. 71
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimType.cs
  91. 49
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimTypeManager.cs
  92. 39
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeedContributor.cs
  93. 13
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeedResult.cs
  94. 153
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeeder.cs
  95. 19
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDomainMappingProfile.cs
  96. 57
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUser.cs
  97. 19
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserInfo.cs
  98. 193
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserManager.cs
  99. 191
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRole.cs
  100. 75
      modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleClaim.cs

63
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.Users;
using Volo.Abp.Threading; 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( private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
typeof(AbpIdentityDomainSharedModule),
typeof(AbpUsersAbstractionModule),
typeof(AbpAuthorizationModule),
typeof(AbpPermissionManagementApplicationContractsModule)
)]
public class AbpIdentityApplicationContractsModule : AbpModule
{
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,
ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToApi( IdentityModuleExtensionConsts.EntityNames.Role,
IdentityModuleExtensionConsts.ModuleName, getApiTypes: new[] { typeof(IdentityRoleDto) },
IdentityModuleExtensionConsts.EntityNames.Role, createApiTypes: new[] { typeof(IdentityRoleCreateDto) },
getApiTypes: new[] { typeof(IdentityRoleDto) }, updateApiTypes: new[] { typeof(IdentityRoleUpdateDto) }
createApiTypes: new[] { typeof(IdentityRoleCreateDto) }, );
updateApiTypes: new[] { typeof(IdentityRoleUpdateDto) }
);
ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToApi( ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToApi(
IdentityModuleExtensionConsts.ModuleName, IdentityModuleExtensionConsts.ModuleName,
IdentityModuleExtensionConsts.EntityNames.User, IdentityModuleExtensionConsts.EntityNames.User,
getApiTypes: new[] { typeof(IdentityUserDto) }, getApiTypes: new[] { typeof(IdentityUserDto) },
createApiTypes: new[] { typeof(IdentityUserCreateDto) }, createApiTypes: new[] { typeof(IdentityUserCreateDto) },
updateApiTypes: new[] { typeof(IdentityUserUpdateDto) } updateApiTypes: new[] { typeof(IdentityUserUpdateDto) }
); );
}); });
}
} }
} }

9
modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityRolesInput.cs

@ -1,9 +1,8 @@
using Volo.Abp.Application.Dtos; 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; }
}
} }

9
modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/GetIdentityUsersInput.cs

@ -1,9 +1,8 @@
using Volo.Abp.Application.Dtos; 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; }
}
} }

21
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.Dtos;
using Volo.Abp.Application.Services; 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 Task<ListResultDto<IdentityRoleDto>> GetAllListAsync();
: ICrudAppService<
IdentityRoleDto,
Guid,
GetIdentityRolesInput,
IdentityRoleCreateDto,
IdentityRoleUpdateDto>
{
Task<ListResultDto<IdentityRoleDto>> GetAllListAsync();
}
} }

29
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.Dtos;
using Volo.Abp.Application.Services; 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 Task<ListResultDto<IdentityRoleDto>> GetRolesAsync(Guid id);
: ICrudAppService<
IdentityUserDto,
Guid,
GetIdentityUsersInput,
IdentityUserCreateDto,
IdentityUserUpdateDto>
{
Task<ListResultDto<IdentityRoleDto>> GetRolesAsync(Guid id);
Task<ListResultDto<IdentityRoleDto>> GetAssignableRolesAsync(); Task<ListResultDto<IdentityRoleDto>> GetAssignableRolesAsync();
Task UpdateRolesAsync(Guid id, IdentityUserUpdateRolesDto input); Task UpdateRolesAsync(Guid id, IdentityUserUpdateRolesDto input);
Task<IdentityUserDto> FindByUsernameAsync(string userName); Task<IdentityUserDto> FindByUsernameAsync(string userName);
Task<IdentityUserDto> FindByEmailAsync(string email); Task<IdentityUserDto> FindByEmailAsync(string email);
}
} }

17
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.Application.Services;
using Volo.Abp.Users; using Volo.Abp.Users;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public interface IIdentityUserLookupAppService : IApplicationService
{ {
public interface IIdentityUserLookupAppService : IApplicationService Task<UserData> FindByIdAsync(Guid id);
{
Task<UserData> FindByIdAsync(Guid id); Task<UserData> FindByUserNameAsync(string userName);
Task<UserData> FindByUserNameAsync(string userName); Task<ListResultDto<UserData>> SearchAsync(UserLookupSearchInputDto input);
Task<ListResultDto<UserData>> SearchAsync(UserLookupSearchInputDto input); Task<long> GetCountAsync(UserLookupCountInputDto input);
Task<long> GetCountAsync(UserLookupCountInputDto input);
}
} }

45
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.Identity.Localization;
using Volo.Abp.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")); var rolesPermission = identityGroup.AddPermission(IdentityPermissions.Roles.Default, L("Permission:RoleManagement"));
rolesPermission.AddChild(IdentityPermissions.Roles.Create, L("Permission:Create")); rolesPermission.AddChild(IdentityPermissions.Roles.Create, L("Permission:Create"));
rolesPermission.AddChild(IdentityPermissions.Roles.Update, L("Permission:Edit")); rolesPermission.AddChild(IdentityPermissions.Roles.Update, L("Permission:Edit"));
rolesPermission.AddChild(IdentityPermissions.Roles.Delete, L("Permission:Delete")); rolesPermission.AddChild(IdentityPermissions.Roles.Delete, L("Permission:Delete"));
rolesPermission.AddChild(IdentityPermissions.Roles.ManagePermissions, L("Permission:ChangePermissions")); rolesPermission.AddChild(IdentityPermissions.Roles.ManagePermissions, L("Permission:ChangePermissions"));
var usersPermission = identityGroup.AddPermission(IdentityPermissions.Users.Default, L("Permission:UserManagement")); var usersPermission = identityGroup.AddPermission(IdentityPermissions.Users.Default, L("Permission:UserManagement"));
usersPermission.AddChild(IdentityPermissions.Users.Create, L("Permission:Create")); usersPermission.AddChild(IdentityPermissions.Users.Create, L("Permission:Create"));
usersPermission.AddChild(IdentityPermissions.Users.Update, L("Permission:Edit")); usersPermission.AddChild(IdentityPermissions.Users.Update, L("Permission:Edit"));
usersPermission.AddChild(IdentityPermissions.Users.Delete, L("Permission:Delete")); usersPermission.AddChild(IdentityPermissions.Users.Delete, L("Permission:Delete"));
usersPermission.AddChild(IdentityPermissions.Users.ManagePermissions, L("Permission:ChangePermissions")); usersPermission.AddChild(IdentityPermissions.Users.ManagePermissions, L("Permission:ChangePermissions"));
identityGroup identityGroup
.AddPermission(IdentityPermissions.UserLookup.Default, L("Permission:UserLookup")) .AddPermission(IdentityPermissions.UserLookup.Default, L("Permission:UserLookup"))
.WithProviders(ClientPermissionValueProvider.ProviderName); .WithProviders(ClientPermissionValueProvider.ProviderName);
} }
private static LocalizableString L(string name) private static LocalizableString L(string name)
{ {
return LocalizableString.Create<IdentityResource>(name); return LocalizableString.Create<IdentityResource>(name);
}
} }
} }

57
modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityPermissions.cs

@ -1,37 +1,36 @@
using Volo.Abp.Reflection; 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 static class Roles
{ {
public const string Default = GroupName + ".Roles"; public const string Default = GroupName + ".Roles";
public const string Create = Default + ".Create"; public const string Create = Default + ".Create";
public const string Update = Default + ".Update"; public const string Update = Default + ".Update";
public const string Delete = Default + ".Delete"; public const string Delete = Default + ".Delete";
public const string ManagePermissions = Default + ".ManagePermissions"; public const string ManagePermissions = Default + ".ManagePermissions";
} }
public static class Users public static class Users
{ {
public const string Default = GroupName + ".Users"; public const string Default = GroupName + ".Users";
public const string Create = Default + ".Create"; public const string Create = Default + ".Create";
public const string Update = Default + ".Update"; public const string Update = Default + ".Update";
public const string Delete = Default + ".Delete"; public const string Delete = Default + ".Delete";
public const string ManagePermissions = Default + ".ManagePermissions"; public const string ManagePermissions = Default + ".ManagePermissions";
} }
public static class UserLookup public static class UserLookup
{ {
public const string Default = GroupName + ".UserLookup"; public const string Default = GroupName + ".UserLookup";
} }
public static string[] GetAll() public static string[] GetAll()
{ {
return ReflectionHelper.GetPublicConstantsRecursively(typeof(IdentityPermissions)); return ReflectionHelper.GetPublicConstantsRecursively(typeof(IdentityPermissions));
}
} }
} }

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

9
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
{
} }
}

25
modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleCreateOrUpdateDtoBase.cs

@ -2,21 +2,20 @@
using Volo.Abp.ObjectExtending; using Volo.Abp.ObjectExtending;
using Volo.Abp.Validation; 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))]
[Required] public string Name { get; set; }
[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)
{
}
} }
} }

21
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.Application.Dtos;
using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Entities;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public class IdentityRoleDto : ExtensibleEntityDto<Guid>, IHasConcurrencyStamp
{ {
public class IdentityRoleDto : ExtensibleEntityDto<Guid>, 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; } public string ConcurrencyStamp { get; set; }
} }
}

11
modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleUpdateDto.cs

@ -1,9 +1,8 @@
using Volo.Abp.Domain.Entities; 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; }
{ }
public string ConcurrencyStamp { get; set; }
}
}

17
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.Auditing;
using Volo.Abp.Validation; using Volo.Abp.Validation;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public class IdentityUserCreateDto : IdentityUserCreateOrUpdateDtoBase
{ {
public class IdentityUserCreateDto : IdentityUserCreateOrUpdateDtoBase [DisableAuditing]
{ [Required]
[DisableAuditing] [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))]
[Required] public string Password { get; set; }
[DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))] }
public string Password { get; set; }
}
}

45
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.ObjectExtending;
using Volo.Abp.Validation; 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))]
[Required] public string UserName { get; set; }
[DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxUserNameLength))]
public string UserName { get; set; }
[DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxNameLength))] [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxNameLength))]
public string Name { get; set; } public string Name { get; set; }
[DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxSurnameLength))] [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxSurnameLength))]
public string Surname { get; set; } public string Surname { get; set; }
[Required] [Required]
[EmailAddress] [EmailAddress]
[DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxEmailLength))] [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxEmailLength))]
public string Email { get; set; } public string Email { get; set; }
[DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPhoneNumberLength))] [DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPhoneNumberLength))]
public string PhoneNumber { get; set; } 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] [CanBeNull]
public string[] RoleNames { get; set; } public string[] RoleNames { get; set; }
protected IdentityUserCreateOrUpdateDtoBase() : base(false) protected IdentityUserCreateOrUpdateDtoBase() : base(false)
{ {
}
} }
} }

31
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.Domain.Entities;
using Volo.Abp.MultiTenancy; using Volo.Abp.MultiTenancy;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public class IdentityUserDto : ExtensibleFullAuditedEntityDto<Guid>, IMultiTenant, IHasConcurrencyStamp
{ {
public class IdentityUserDto : ExtensibleFullAuditedEntityDto<Guid>, 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; }
}
} }

19
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.Domain.Entities;
using Volo.Abp.Validation; 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))]
[DisableAuditing] public string Password { get; set; }
[DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))]
public string Password { get; set; } public string ConcurrencyStamp { get; set; }
}
public string ConcurrencyStamp { get; set; }
}
}

13
modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserUpdateRolesDto.cs

@ -1,10 +1,9 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public class IdentityUserUpdateRolesDto
{ {
public class IdentityUserUpdateRolesDto [Required]
{ public string[] RoleNames { get; set; }
[Required] }
public string[] RoleNames { get; set; }
}
}

11
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; }
{ }
public string Filter { get; set; }
}
}

11
modules/identity/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/UserLookupSearchInputDto.cs

@ -1,9 +1,8 @@
using Volo.Abp.Application.Dtos; 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; }
{ }
public string Filter { get; set; }
}
}

33
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.Modularity;
using Volo.Abp.PermissionManagement; 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( public override void ConfigureServices(ServiceConfigurationContext context)
typeof(AbpIdentityDomainModule),
typeof(AbpIdentityApplicationContractsModule),
typeof(AbpAutoMapperModule),
typeof(AbpPermissionManagementApplicationModule)
)]
public class AbpIdentityApplicationModule : AbpModule
{ {
public override void ConfigureServices(ServiceConfigurationContext context) context.Services.AddAutoMapperObjectMapper<AbpIdentityApplicationModule>();
{
context.Services.AddAutoMapperObjectMapper<AbpIdentityApplicationModule>();
Configure<AbpAutoMapperOptions>(options => Configure<AbpAutoMapperOptions>(options =>
{ {
options.AddProfile<AbpIdentityApplicationModuleAutoMapperProfile>(validate: true); options.AddProfile<AbpIdentityApplicationModuleAutoMapperProfile>(validate: true);
}); });
}
} }
} }

17
modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/AbpIdentityApplicationModuleAutoMapperProfile.cs

@ -1,16 +1,15 @@
using AutoMapper; using AutoMapper;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public class AbpIdentityApplicationModuleAutoMapperProfile : Profile
{ {
public class AbpIdentityApplicationModuleAutoMapperProfile : Profile public AbpIdentityApplicationModuleAutoMapperProfile()
{ {
public AbpIdentityApplicationModuleAutoMapperProfile() CreateMap<IdentityUser, IdentityUserDto>()
{ .MapExtraProperties();
CreateMap<IdentityUser, IdentityUserDto>()
.MapExtraProperties();
CreateMap<IdentityRole, IdentityRoleDto>() CreateMap<IdentityRole, IdentityRoleDto>()
.MapExtraProperties(); .MapExtraProperties();
}
} }
} }

13
modules/identity/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityAppServiceBase.cs

@ -1,14 +1,13 @@
using Volo.Abp.Application.Services; using Volo.Abp.Application.Services;
using Volo.Abp.Identity.Localization; 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);
}
} }
} }

149
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.Data;
using Volo.Abp.ObjectExtending; 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)] protected IdentityRoleManager RoleManager { get; }
public class IdentityRoleAppService : IdentityAppServiceBase, IIdentityRoleAppService protected IIdentityRoleRepository RoleRepository { get; }
public IdentityRoleAppService(
IdentityRoleManager roleManager,
IIdentityRoleRepository roleRepository)
{ {
protected IdentityRoleManager RoleManager { get; } RoleManager = roleManager;
protected IIdentityRoleRepository RoleRepository { get; } RoleRepository = roleRepository;
}
public IdentityRoleAppService( public virtual async Task<IdentityRoleDto> GetAsync(Guid id)
IdentityRoleManager roleManager, {
IIdentityRoleRepository roleRepository) return ObjectMapper.Map<IdentityRole, IdentityRoleDto>(
{ await RoleManager.GetByIdAsync(id)
RoleManager = roleManager; );
RoleRepository = roleRepository; }
}
public virtual async Task<IdentityRoleDto> GetAsync(Guid id) public virtual async Task<ListResultDto<IdentityRoleDto>> GetAllListAsync()
{ {
return ObjectMapper.Map<IdentityRole, IdentityRoleDto>( var list = await RoleRepository.GetListAsync();
await RoleManager.GetByIdAsync(id) return new ListResultDto<IdentityRoleDto>(
); ObjectMapper.Map<List<IdentityRole>, List<IdentityRoleDto>>(list)
} );
}
public virtual async Task<ListResultDto<IdentityRoleDto>> GetAllListAsync() public virtual async Task<PagedResultDto<IdentityRoleDto>> GetListAsync(GetIdentityRolesInput input)
{ {
var list = await RoleRepository.GetListAsync(); var list = await RoleRepository.GetListAsync(input.Sorting, input.MaxResultCount, input.SkipCount, input.Filter);
return new ListResultDto<IdentityRoleDto>( var totalCount = await RoleRepository.GetCountAsync(input.Filter);
ObjectMapper.Map<List<IdentityRole>, List<IdentityRoleDto>>(list)
return new PagedResultDto<IdentityRoleDto>(
totalCount,
ObjectMapper.Map<List<IdentityRole>, List<IdentityRoleDto>>(list)
); );
} }
public virtual async Task<PagedResultDto<IdentityRoleDto>> GetListAsync(GetIdentityRolesInput input) [Authorize(IdentityPermissions.Roles.Create)]
public virtual async Task<IdentityRoleDto> 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); IsDefault = input.IsDefault,
var totalCount = await RoleRepository.GetCountAsync(input.Filter); IsPublic = input.IsPublic
};
return new PagedResultDto<IdentityRoleDto>( input.MapExtraPropertiesTo(role);
totalCount,
ObjectMapper.Map<List<IdentityRole>, List<IdentityRoleDto>>(list)
);
}
[Authorize(IdentityPermissions.Roles.Create)] (await RoleManager.CreateAsync(role)).CheckErrors();
public virtual async Task<IdentityRoleDto> CreateAsync(IdentityRoleCreateDto input) await CurrentUnitOfWork.SaveChangesAsync();
{
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<IdentityRole, IdentityRoleDto>(role);
}
[Authorize(IdentityPermissions.Roles.Update)] return ObjectMapper.Map<IdentityRole, IdentityRoleDto>(role);
public virtual async Task<IdentityRoleDto> UpdateAsync(Guid id, IdentityRoleUpdateDto input) }
{
var role = await RoleManager.GetByIdAsync(id);
role.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp);
(await RoleManager.SetRoleNameAsync(role, input.Name)).CheckErrors(); [Authorize(IdentityPermissions.Roles.Update)]
public virtual async Task<IdentityRoleDto> UpdateAsync(Guid id, IdentityRoleUpdateDto input)
{
var role = await RoleManager.GetByIdAsync(id);
role.IsDefault = input.IsDefault; role.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp);
role.IsPublic = input.IsPublic;
input.MapExtraPropertiesTo(role); (await RoleManager.SetRoleNameAsync(role, input.Name)).CheckErrors();
(await RoleManager.UpdateAsync(role)).CheckErrors(); role.IsDefault = input.IsDefault;
await CurrentUnitOfWork.SaveChangesAsync(); role.IsPublic = input.IsPublic;
return ObjectMapper.Map<IdentityRole, IdentityRoleDto>(role); input.MapExtraPropertiesTo(role);
}
[Authorize(IdentityPermissions.Roles.Delete)] (await RoleManager.UpdateAsync(role)).CheckErrors();
public virtual async Task DeleteAsync(Guid id) await CurrentUnitOfWork.SaveChangesAsync();
{
var role = await RoleManager.FindByIdAsync(id.ToString()); return ObjectMapper.Map<IdentityRole, IdentityRoleDto>(role);
if (role == null) }
{
return;
}
(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();
} }
} }

273
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.Data;
using Volo.Abp.ObjectExtending; 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> IdentityOptions { get; }
public IdentityUserAppService(
IdentityUserManager userManager,
IIdentityUserRepository userRepository,
IIdentityRoleRepository roleRepository,
IOptions<IdentityOptions> identityOptions)
{ {
protected IdentityUserManager UserManager { get; } UserManager = userManager;
protected IIdentityUserRepository UserRepository { get; } UserRepository = userRepository;
protected IIdentityRoleRepository RoleRepository { get; } RoleRepository = roleRepository;
protected IOptions<IdentityOptions> IdentityOptions { get; } IdentityOptions = identityOptions;
}
public IdentityUserAppService(
IdentityUserManager userManager,
IIdentityUserRepository userRepository,
IIdentityRoleRepository roleRepository,
IOptions<IdentityOptions> identityOptions)
{
UserManager = userManager;
UserRepository = userRepository;
RoleRepository = roleRepository;
IdentityOptions = identityOptions;
}
//TODO: [Authorize(IdentityPermissions.Users.Default)] should go the IdentityUserAppService class. //TODO: [Authorize(IdentityPermissions.Users.Default)] should go the IdentityUserAppService class.
[Authorize(IdentityPermissions.Users.Default)] [Authorize(IdentityPermissions.Users.Default)]
public virtual async Task<IdentityUserDto> GetAsync(Guid id) public virtual async Task<IdentityUserDto> GetAsync(Guid id)
{ {
return ObjectMapper.Map<IdentityUser, IdentityUserDto>( return ObjectMapper.Map<IdentityUser, IdentityUserDto>(
await UserManager.GetByIdAsync(id) await UserManager.GetByIdAsync(id)
); );
} }
[Authorize(IdentityPermissions.Users.Default)] [Authorize(IdentityPermissions.Users.Default)]
public virtual async Task<PagedResultDto<IdentityUserDto>> GetListAsync(GetIdentityUsersInput input) public virtual async Task<PagedResultDto<IdentityUserDto>> GetListAsync(GetIdentityUsersInput input)
{ {
var count = await UserRepository.GetCountAsync(input.Filter); var count = await UserRepository.GetCountAsync(input.Filter);
var list = await UserRepository.GetListAsync(input.Sorting, input.MaxResultCount, input.SkipCount, input.Filter); var list = await UserRepository.GetListAsync(input.Sorting, input.MaxResultCount, input.SkipCount, input.Filter);
return new PagedResultDto<IdentityUserDto>( return new PagedResultDto<IdentityUserDto>(
count, count,
ObjectMapper.Map<List<IdentityUser>, List<IdentityUserDto>>(list) ObjectMapper.Map<List<IdentityUser>, List<IdentityUserDto>>(list)
); );
} }
[Authorize(IdentityPermissions.Users.Default)] [Authorize(IdentityPermissions.Users.Default)]
public virtual async Task<ListResultDto<IdentityRoleDto>> GetRolesAsync(Guid id) public virtual async Task<ListResultDto<IdentityRoleDto>> GetRolesAsync(Guid id)
{ {
//TODO: Should also include roles of the related OUs. //TODO: Should also include roles of the related OUs.
var roles = await UserRepository.GetRolesAsync(id); var roles = await UserRepository.GetRolesAsync(id);
return new ListResultDto<IdentityRoleDto>( return new ListResultDto<IdentityRoleDto>(
ObjectMapper.Map<List<IdentityRole>, List<IdentityRoleDto>>(roles) ObjectMapper.Map<List<IdentityRole>, List<IdentityRoleDto>>(roles)
); );
} }
[Authorize(IdentityPermissions.Users.Default)] [Authorize(IdentityPermissions.Users.Default)]
public virtual async Task<ListResultDto<IdentityRoleDto>> GetAssignableRolesAsync() public virtual async Task<ListResultDto<IdentityRoleDto>> GetAssignableRolesAsync()
{ {
var list = await RoleRepository.GetListAsync(); var list = await RoleRepository.GetListAsync();
return new ListResultDto<IdentityRoleDto>( return new ListResultDto<IdentityRoleDto>(
ObjectMapper.Map<List<IdentityRole>, List<IdentityRoleDto>>(list)); ObjectMapper.Map<List<IdentityRole>, List<IdentityRoleDto>>(list));
} }
[Authorize(IdentityPermissions.Users.Create)] [Authorize(IdentityPermissions.Users.Create)]
public virtual async Task<IdentityUserDto> CreateAsync(IdentityUserCreateDto input) public virtual async Task<IdentityUserDto> CreateAsync(IdentityUserCreateDto input)
{ {
await IdentityOptions.SetAsync(); await IdentityOptions.SetAsync();
var user = new IdentityUser( var user = new IdentityUser(
GuidGenerator.Create(), GuidGenerator.Create(),
input.UserName, input.UserName,
input.Email, input.Email,
CurrentTenant.Id CurrentTenant.Id
); );
input.MapExtraPropertiesTo(user); input.MapExtraPropertiesTo(user);
(await UserManager.CreateAsync(user, input.Password)).CheckErrors(); (await UserManager.CreateAsync(user, input.Password)).CheckErrors();
await UpdateUserByInput(user, input); await UpdateUserByInput(user, input);
(await UserManager.UpdateAsync(user)).CheckErrors(); (await UserManager.UpdateAsync(user)).CheckErrors();
await CurrentUnitOfWork.SaveChangesAsync(); await CurrentUnitOfWork.SaveChangesAsync();
return ObjectMapper.Map<IdentityUser, IdentityUserDto>(user); return ObjectMapper.Map<IdentityUser, IdentityUserDto>(user);
} }
[Authorize(IdentityPermissions.Users.Update)] [Authorize(IdentityPermissions.Users.Update)]
public virtual async Task<IdentityUserDto> UpdateAsync(Guid id, IdentityUserUpdateDto input) public virtual async Task<IdentityUserDto> UpdateAsync(Guid id, IdentityUserUpdateDto input)
{ {
await IdentityOptions.SetAsync(); 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); await UpdateUserByInput(user, input);
input.MapExtraPropertiesTo(user); input.MapExtraPropertiesTo(user);
(await UserManager.UpdateAsync(user)).CheckErrors(); (await UserManager.UpdateAsync(user)).CheckErrors();
if (!input.Password.IsNullOrEmpty()) if (!input.Password.IsNullOrEmpty())
{ {
(await UserManager.RemovePasswordAsync(user)).CheckErrors(); (await UserManager.RemovePasswordAsync(user)).CheckErrors();
(await UserManager.AddPasswordAsync(user, input.Password)).CheckErrors(); (await UserManager.AddPasswordAsync(user, input.Password)).CheckErrors();
} }
await CurrentUnitOfWork.SaveChangesAsync(); await CurrentUnitOfWork.SaveChangesAsync();
return ObjectMapper.Map<IdentityUser, IdentityUserDto>(user); return ObjectMapper.Map<IdentityUser, IdentityUserDto>(user);
} }
[Authorize(IdentityPermissions.Users.Delete)] [Authorize(IdentityPermissions.Users.Delete)]
public virtual async Task DeleteAsync(Guid id) public virtual async Task DeleteAsync(Guid id)
{
if (CurrentUser.Id == id)
{ {
if (CurrentUser.Id == id) throw new BusinessException(code: IdentityErrorCodes.UserSelfDeletion);
{
throw new BusinessException(code: IdentityErrorCodes.UserSelfDeletion);
}
var user = await UserManager.FindByIdAsync(id.ToString());
if (user == null)
{
return;
}
(await UserManager.DeleteAsync(user)).CheckErrors();
} }
[Authorize(IdentityPermissions.Users.Update)] var user = await UserManager.FindByIdAsync(id.ToString());
public virtual async Task UpdateRolesAsync(Guid id, IdentityUserUpdateRolesDto input) if (user == null)
{ {
var user = await UserManager.GetByIdAsync(id); return;
(await UserManager.SetRolesAsync(user, input.RoleNames)).CheckErrors();
await UserRepository.UpdateAsync(user);
} }
[Authorize(IdentityPermissions.Users.Default)] (await UserManager.DeleteAsync(user)).CheckErrors();
public virtual async Task<IdentityUserDto> FindByUsernameAsync(string userName) }
[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<IdentityUserDto> FindByUsernameAsync(string userName)
{
return ObjectMapper.Map<IdentityUser, IdentityUserDto>(
await UserManager.FindByNameAsync(userName)
);
}
[Authorize(IdentityPermissions.Users.Default)]
public virtual async Task<IdentityUserDto> FindByEmailAsync(string email)
{
return ObjectMapper.Map<IdentityUser, IdentityUserDto>(
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<IdentityUser, IdentityUserDto>( (await UserManager.SetEmailAsync(user, input.Email)).CheckErrors();
await UserManager.FindByNameAsync(userName)
);
} }
[Authorize(IdentityPermissions.Users.Default)] if (!string.Equals(user.PhoneNumber, input.PhoneNumber, StringComparison.InvariantCultureIgnoreCase))
public virtual async Task<IdentityUserDto> FindByEmailAsync(string email)
{ {
return ObjectMapper.Map<IdentityUser, IdentityUserDto>( (await UserManager.SetPhoneNumberAsync(user, input.PhoneNumber)).CheckErrors();
await UserManager.FindByEmailAsync(email)
);
} }
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.SetRolesAsync(user, input.RoleNames)).CheckErrors();
{
(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();
}
} }
} }
} }

85
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.Application.Dtos;
using Volo.Abp.Users; 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)] protected IdentityUserRepositoryExternalUserLookupServiceProvider UserLookupServiceProvider { get; }
public class IdentityUserLookupAppService : IdentityAppServiceBase, IIdentityUserLookupAppService
public IdentityUserLookupAppService(
IdentityUserRepositoryExternalUserLookupServiceProvider userLookupServiceProvider)
{ {
protected IdentityUserRepositoryExternalUserLookupServiceProvider UserLookupServiceProvider { get; } UserLookupServiceProvider = userLookupServiceProvider;
}
public IdentityUserLookupAppService( public virtual async Task<UserData> FindByIdAsync(Guid id)
IdentityUserRepositoryExternalUserLookupServiceProvider userLookupServiceProvider) {
var userData = await UserLookupServiceProvider.FindByIdAsync(id);
if (userData == null)
{ {
UserLookupServiceProvider = userLookupServiceProvider; return null;
} }
public virtual async Task<UserData> FindByIdAsync(Guid id) return new UserData(userData);
{ }
var userData = await UserLookupServiceProvider.FindByIdAsync(id);
if (userData == null)
{
return null;
}
return new UserData(userData);
}
public virtual async Task<UserData> FindByUserNameAsync(string userName) public virtual async Task<UserData> FindByUserNameAsync(string userName)
{
var userData = await UserLookupServiceProvider.FindByUserNameAsync(userName);
if (userData == null)
{ {
var userData = await UserLookupServiceProvider.FindByUserNameAsync(userName); return null;
if (userData == null)
{
return null;
}
return new UserData(userData);
} }
public async Task<ListResultDto<UserData>> SearchAsync(UserLookupSearchInputDto input) return new UserData(userData);
{ }
var users = await UserLookupServiceProvider.SearchAsync(
input.Sorting,
input.Filter,
input.MaxResultCount,
input.SkipCount
);
return new ListResultDto<UserData>( public async Task<ListResultDto<UserData>> SearchAsync(UserLookupSearchInputDto input)
users {
.Select(u => new UserData(u)) var users = await UserLookupServiceProvider.SearchAsync(
.ToList() input.Sorting,
); input.Filter,
} input.MaxResultCount,
input.SkipCount
);
return new ListResultDto<UserData>(
users
.Select(u => new UserData(u))
.ToList()
);
}
public async Task<long> GetCountAsync(UserLookupCountInputDto input) public async Task<long> GetCountAsync(UserLookupCountInputDto input)
{ {
return await UserLookupServiceProvider.GetCountAsync(input.Filter); return await UserLookupServiceProvider.GetCountAsync(input.Filter);
}
} }
} }

61
modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpIdentityAspNetCoreModule.cs

@ -2,43 +2,42 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Modularity; using Volo.Abp.Modularity;
namespace Volo.Abp.Identity.AspNetCore namespace Volo.Abp.Identity.AspNetCore;
[DependsOn(
typeof(AbpIdentityDomainModule)
)]
public class AbpIdentityAspNetCoreModule : AbpModule
{ {
[DependsOn( public override void PreConfigureServices(ServiceConfigurationContext context)
typeof(AbpIdentityDomainModule)
)]
public class AbpIdentityAspNetCoreModule : AbpModule
{ {
public override void PreConfigureServices(ServiceConfigurationContext context) PreConfigure<IdentityBuilder>(builder =>
{ {
PreConfigure<IdentityBuilder>(builder => builder
{ .AddDefaultTokenProviders()
builder .AddTokenProvider<LinkUserTokenProvider>(LinkUserTokenProviderConsts.LinkUserTokenProviderName)
.AddDefaultTokenProviders() .AddSignInManager<AbpSignInManager>();
.AddTokenProvider<LinkUserTokenProvider>(LinkUserTokenProviderConsts.LinkUserTokenProviderName) });
.AddSignInManager<AbpSignInManager>(); }
});
}
public override void ConfigureServices(ServiceConfigurationContext context) public override void ConfigureServices(ServiceConfigurationContext context)
{ {
//(TODO: Extract an extension method like IdentityBuilder.AddAbpSecurityStampValidator()) //(TODO: Extract an extension method like IdentityBuilder.AddAbpSecurityStampValidator())
context.Services.AddScoped<AbpSecurityStampValidator>(); context.Services.AddScoped<AbpSecurityStampValidator>();
context.Services.AddScoped(typeof(SecurityStampValidator<IdentityUser>), provider => provider.GetService(typeof(AbpSecurityStampValidator))); context.Services.AddScoped(typeof(SecurityStampValidator<IdentityUser>), provider => provider.GetService(typeof(AbpSecurityStampValidator)));
context.Services.AddScoped(typeof(ISecurityStampValidator), 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) if (options.ConfigureAuthentication)
{ {
context.Services context.Services
.AddAuthentication(o => .AddAuthentication(o =>
{ {
o.DefaultScheme = IdentityConstants.ApplicationScheme; o.DefaultScheme = IdentityConstants.ApplicationScheme;
o.DefaultSignInScheme = IdentityConstants.ExternalScheme; o.DefaultSignInScheme = IdentityConstants.ExternalScheme;
}) })
.AddIdentityCookies(); .AddIdentityCookies();
}
} }
} }
} }

15
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 /// <summary>
{ /// Default: true.
/// <summary> /// </summary>
/// Default: true. public bool ConfigureAuthentication { get; set; } = true;
/// </summary>
public bool ConfigureAuthentication { get; set; } = true;
}
} }

67
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.MultiTenancy;
using Volo.Abp.Uow; using Volo.Abp.Uow;
namespace Volo.Abp.Identity.AspNetCore namespace Volo.Abp.Identity.AspNetCore;
public class AbpSecurityStampValidator : SecurityStampValidator<IdentityUser>
{ {
public class AbpSecurityStampValidator : SecurityStampValidator<IdentityUser> protected ITenantConfigurationProvider TenantConfigurationProvider { get; }
protected ICurrentTenant CurrentTenant { get; }
public AbpSecurityStampValidator(
IOptions<SecurityStampValidatorOptions> options,
SignInManager<IdentityUser> signInManager,
ISystemClock systemClock,
ILoggerFactory loggerFactory,
ITenantConfigurationProvider tenantConfigurationProvider,
ICurrentTenant currentTenant)
: base(
options,
signInManager,
systemClock,
loggerFactory)
{ {
protected ITenantConfigurationProvider TenantConfigurationProvider { get; } TenantConfigurationProvider = tenantConfigurationProvider;
protected ICurrentTenant CurrentTenant { get; } CurrentTenant = currentTenant;
}
public AbpSecurityStampValidator( [UnitOfWork]
IOptions<SecurityStampValidatorOptions> options, public override async Task ValidateAsync(CookieValidatePrincipalContext context)
SignInManager<IdentityUser> signInManager, {
ISystemClock systemClock, TenantConfiguration tenant = null;
ILoggerFactory loggerFactory, try
ITenantConfigurationProvider tenantConfigurationProvider,
ICurrentTenant currentTenant)
: base(
options,
signInManager,
systemClock,
loggerFactory)
{ {
TenantConfigurationProvider = tenantConfigurationProvider; tenant = await TenantConfigurationProvider.GetAsync(saveResolveResult: false);
CurrentTenant = currentTenant;
} }
catch (Exception e)
[UnitOfWork]
public override async Task ValidateAsync(CookieValidatePrincipalContext context)
{ {
TenantConfiguration tenant = null; Logger.LogException(e);
try }
{
tenant = await TenantConfigurationProvider.GetAsync(saveResolveResult: false);
}
catch (Exception e)
{
Logger.LogException(e);
}
using (CurrentTenant.Change(tenant?.Id, tenant?.Name)) using (CurrentTenant.Change(tenant?.Id, tenant?.Name))
{ {
await base.ValidateAsync(context); await base.ValidateAsync(context);
}
} }
} }
} }

37
modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/AbpSecurityStampValidatorCallback.cs

@ -2,32 +2,31 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
namespace Volo.Abp.Identity.AspNetCore namespace Volo.Abp.Identity.AspNetCore;
public class AbpSecurityStampValidatorCallback
{ {
public class AbpSecurityStampValidatorCallback /// <summary>
/// Implements callback for SecurityStampValidator's OnRefreshingPrincipal event.
/// https://github.com/IdentityServer/IdentityServer4/blob/main/src/AspNetIdentity/src/SecurityStampValidatorCallback.cs
/// </summary>
public class SecurityStampValidatorCallback
{ {
/// <summary> /// <summary>
/// Implements callback for SecurityStampValidator's OnRefreshingPrincipal event. /// Maintains the claims captured at login time that are not being created by ASP.NET Identity.
/// https://github.com/IdentityServer/IdentityServer4/blob/main/src/AspNetIdentity/src/SecurityStampValidatorCallback.cs /// This is needed to preserve claims such as idp, auth_time, amr.
/// </summary> /// </summary>
public class SecurityStampValidatorCallback /// <param name="context">The context.</param>
/// <returns></returns>
public static Task UpdatePrincipal(SecurityStampRefreshingPrincipalContext context)
{ {
/// <summary> var newClaimTypes = context.NewPrincipal.Claims.Select(x => x.Type).ToArray();
/// Maintains the claims captured at login time that are not being created by ASP.NET Identity. var currentClaimsToKeep = context.CurrentPrincipal.Claims.Where(x => !newClaimTypes.Contains(x.Type)).ToArray();
/// This is needed to preserve claims such as idp, auth_time, amr.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
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 id = context.NewPrincipal.Identities.First(); var id = context.NewPrincipal.Identities.First();
id.AddClaims(currentClaimsToKeep); id.AddClaims(currentClaimsToKeep);
return Task.CompletedTask; return Task.CompletedTask;
}
} }
} }
} }

107
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.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Volo.Abp.Identity.AspNetCore namespace Volo.Abp.Identity.AspNetCore;
public class AbpSignInManager : SignInManager<IdentityUser>
{ {
public class AbpSignInManager : SignInManager<IdentityUser> protected AbpIdentityOptions AbpOptions { get; }
public AbpSignInManager(
IdentityUserManager userManager,
IHttpContextAccessor contextAccessor,
IUserClaimsPrincipalFactory<IdentityUser> claimsFactory,
IOptions<IdentityOptions> optionsAccessor,
ILogger<SignInManager<IdentityUser>> logger,
IAuthenticationSchemeProvider schemes,
IUserConfirmation<IdentityUser> confirmation,
IOptions<AbpIdentityOptions> options
) : base(
userManager,
contextAccessor,
claimsFactory,
optionsAccessor,
logger,
schemes,
confirmation)
{ {
protected AbpIdentityOptions AbpOptions { get; } AbpOptions = options.Value;
}
public AbpSignInManager( public override async Task<SignInResult> PasswordSignInAsync(
IdentityUserManager userManager, string userName,
IHttpContextAccessor contextAccessor, string password,
IUserClaimsPrincipalFactory<IdentityUser> claimsFactory, bool isPersistent,
IOptions<IdentityOptions> optionsAccessor, bool lockoutOnFailure)
ILogger<SignInManager<IdentityUser>> logger, {
IAuthenticationSchemeProvider schemes, foreach (var externalLoginProviderInfo in AbpOptions.ExternalLoginProviders.Values)
IUserConfirmation<IdentityUser> confirmation,
IOptions<AbpIdentityOptions> options
) : base(
userManager,
contextAccessor,
claimsFactory,
optionsAccessor,
logger,
schemes,
confirmation)
{ {
AbpOptions = options.Value; var externalLoginProvider = (IExternalLoginProvider)Context.RequestServices
} .GetRequiredService(externalLoginProviderInfo.Type);
public override async Task<SignInResult> PasswordSignInAsync( if (await externalLoginProvider.TryAuthenticateAsync(userName, password))
string userName,
string password,
bool isPersistent,
bool lockoutOnFailure)
{
foreach (var externalLoginProviderInfo in AbpOptions.ExternalLoginProviders.Values)
{ {
var externalLoginProvider = (IExternalLoginProvider)Context.RequestServices var user = await UserManager.FindByNameAsync(userName);
.GetRequiredService(externalLoginProviderInfo.Type); if (user == null)
if (await externalLoginProvider.TryAuthenticateAsync(userName, password))
{ {
var user = await UserManager.FindByNameAsync(userName); user = await externalLoginProvider.CreateUserAsync(userName, externalLoginProviderInfo.Name);
if (user == null) }
{ else
user = await externalLoginProvider.CreateUserAsync(userName, externalLoginProviderInfo.Name); {
} await externalLoginProvider.UpdateUserAsync(user, externalLoginProviderInfo.Name);
else
{
await externalLoginProvider.UpdateUserAsync(user, externalLoginProviderInfo.Name);
}
return await SignInOrTwoFactorAsync(user, isPersistent);
} }
}
return await base.PasswordSignInAsync(userName, password, isPersistent, lockoutOnFailure); return await SignInOrTwoFactorAsync(user, isPersistent);
}
} }
protected override async Task<SignInResult> PreSignInCheck(IdentityUser user) return await base.PasswordSignInAsync(userName, password, isPersistent, lockoutOnFailure);
{ }
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); protected override async Task<SignInResult> 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);
} }
} }

17
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.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Volo.Abp.Identity.AspNetCore namespace Volo.Abp.Identity.AspNetCore;
public class LinkUserTokenProvider : DataProtectorTokenProvider<IdentityUser>
{ {
public class LinkUserTokenProvider : DataProtectorTokenProvider<IdentityUser> public LinkUserTokenProvider(
IDataProtectionProvider dataProtectionProvider,
IOptions<DataProtectionTokenProviderOptions> options,
ILogger<DataProtectorTokenProvider<IdentityUser>> logger)
: base(dataProtectionProvider, options, logger)
{ {
public LinkUserTokenProvider(
IDataProtectionProvider dataProtectionProvider,
IOptions<DataProtectionTokenProviderOptions> options,
ILogger<DataProtectorTokenProvider<IdentityUser>> logger)
: base(dataProtectionProvider, options, logger)
{
}
} }
} }

47
modules/identity/src/Volo.Abp.Identity.AspNetCore/Volo/Abp/Identity/AspNetCore/SignInResultExtensions.cs

@ -1,37 +1,36 @@
using Microsoft.AspNetCore.Identity; 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;
{ }
return IdentitySecurityLogActionConsts.LoginSucceeded;
}
if (result.IsLockedOut)
{
return IdentitySecurityLogActionConsts.LoginLockedout;
}
if (result.RequiresTwoFactor) if (result.IsLockedOut)
{ {
return IdentitySecurityLogActionConsts.LoginRequiresTwoFactor; return IdentitySecurityLogActionConsts.LoginLockedout;
} }
if (result.IsNotAllowed) if (result.RequiresTwoFactor)
{ {
return IdentitySecurityLogActionConsts.LoginNotAllowed; return IdentitySecurityLogActionConsts.LoginRequiresTwoFactor;
} }
if (!result.Succeeded) if (result.IsNotAllowed)
{ {
return IdentitySecurityLogActionConsts.LoginFailed; return IdentitySecurityLogActionConsts.LoginNotAllowed;
} }
if (!result.Succeeded)
{
return IdentitySecurityLogActionConsts.LoginFailed; return IdentitySecurityLogActionConsts.LoginFailed;
} }
return IdentitySecurityLogActionConsts.LoginFailed;
} }
} }

15
modules/identity/src/Volo.Abp.Identity.Blazor.Server/AbpIdentityBlazorServerModule.cs

@ -2,13 +2,12 @@
using Volo.Abp.Modularity; using Volo.Abp.Modularity;
using Volo.Abp.PermissionManagement.Blazor.Server; 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
{
}
} }

17
modules/identity/src/Volo.Abp.Identity.Blazor.WebAssembly/AbpIdentityBlazorWebAssemblyModule.cs

@ -2,14 +2,13 @@
using Volo.Abp.Modularity; using Volo.Abp.Modularity;
using Volo.Abp.PermissionManagement.Blazor.WebAssembly; 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
{
}
} }

23
modules/identity/src/Volo.Abp.Identity.Blazor/AbpIdentityBlazorAutoMapperProfile.cs

@ -1,19 +1,18 @@
using AutoMapper; using AutoMapper;
using Volo.Abp.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<IdentityUserDto, IdentityUserUpdateDto>()
{ .MapExtraProperties()
CreateMap<IdentityUserDto, IdentityUserUpdateDto>() .Ignore(x => x.Password)
.MapExtraProperties() .Ignore(x => x.RoleNames);
.Ignore(x => x.Password)
.Ignore(x => x.RoleNames); CreateMap<IdentityRoleDto, IdentityRoleUpdateDto>()
.MapExtraProperties();
CreateMap<IdentityRoleDto, IdentityRoleUpdateDto>()
.MapExtraProperties();
}
} }
} }

87
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.Threading;
using Volo.Abp.UI.Navigation; 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( private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
typeof(AbpIdentityApplicationContractsModule),
typeof(AbpAutoMapperModule), public override void ConfigureServices(ServiceConfigurationContext context)
typeof(AbpPermissionManagementBlazorModule),
typeof(AbpBlazoriseUIModule)
)]
public class AbpIdentityBlazorModule : AbpModule
{ {
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); context.Services.AddAutoMapperObjectMapper<AbpIdentityBlazorModule>();
public override void ConfigureServices(ServiceConfigurationContext context) Configure<AbpAutoMapperOptions>(options =>
{ {
context.Services.AddAutoMapperObjectMapper<AbpIdentityBlazorModule>(); options.AddProfile<AbpIdentityBlazorAutoMapperProfile>(validate: true);
});
Configure<AbpAutoMapperOptions>(options => Configure<AbpNavigationOptions>(options =>
{ {
options.AddProfile<AbpIdentityBlazorAutoMapperProfile>(validate: true); options.MenuContributors.Add(new AbpIdentityWebMainMenuContributor());
}); });
Configure<AbpNavigationOptions>(options =>
{
options.MenuContributors.Add(new AbpIdentityWebMainMenuContributor());
});
Configure<AbpRouterOptions>(options => Configure<AbpRouterOptions>(options =>
{ {
options.AdditionalAssemblies.Add(typeof(AbpIdentityBlazorModule).Assembly); options.AdditionalAssemblies.Add(typeof(AbpIdentityBlazorModule).Assembly);
}); });
} }
public override void PostConfigureServices(ServiceConfigurationContext context) public override void PostConfigureServices(ServiceConfigurationContext context)
{
OneTimeRunner.Run(() =>
{ {
OneTimeRunner.Run(() => ModuleExtensionConfigurationHelper
{ .ApplyEntityConfigurationToUi(
ModuleExtensionConfigurationHelper IdentityModuleExtensionConsts.ModuleName,
.ApplyEntityConfigurationToUi( IdentityModuleExtensionConsts.EntityNames.Role,
IdentityModuleExtensionConsts.ModuleName, createFormTypes: new[] { typeof(IdentityRoleCreateDto) },
IdentityModuleExtensionConsts.EntityNames.Role, editFormTypes: new[] { typeof(IdentityRoleUpdateDto) }
createFormTypes: new[] { typeof(IdentityRoleCreateDto) }, );
editFormTypes: new[] { typeof(IdentityRoleUpdateDto) }
);
ModuleExtensionConfigurationHelper ModuleExtensionConfigurationHelper
.ApplyEntityConfigurationToUi( .ApplyEntityConfigurationToUi(
IdentityModuleExtensionConsts.ModuleName, IdentityModuleExtensionConsts.ModuleName,
IdentityModuleExtensionConsts.EntityNames.User, IdentityModuleExtensionConsts.EntityNames.User,
createFormTypes: new[] { typeof(IdentityUserCreateDto) }, createFormTypes: new[] { typeof(IdentityUserCreateDto) },
editFormTypes: new[] { typeof(IdentityUserUpdateDto) } editFormTypes: new[] { typeof(IdentityUserUpdateDto) }
); );
}); });
}
} }
} }

43
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.UI.Navigation;
using Volo.Abp.Authorization.Permissions; 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<IdentityResource>(); var l = context.GetLocalizer<IdentityResource>();
var identityMenuItem = new ApplicationMenuItem(IdentityMenuNames.GroupName, l["Menu:IdentityManagement"], var identityMenuItem = new ApplicationMenuItem(IdentityMenuNames.GroupName, l["Menu:IdentityManagement"],
icon: "far fa-id-card"); icon: "far fa-id-card");
administrationMenu.AddItem(identityMenuItem); administrationMenu.AddItem(identityMenuItem);
identityMenuItem.AddItem(new ApplicationMenuItem( identityMenuItem.AddItem(new ApplicationMenuItem(
IdentityMenuNames.Roles, IdentityMenuNames.Roles,
l["Roles"], l["Roles"],
url: "~/identity/roles").RequirePermissions(IdentityPermissions.Roles.Default)); url: "~/identity/roles").RequirePermissions(IdentityPermissions.Roles.Default));
identityMenuItem.AddItem(new ApplicationMenuItem( identityMenuItem.AddItem(new ApplicationMenuItem(
IdentityMenuNames.Users, IdentityMenuNames.Users,
l["Users"], l["Users"],
url: "~/identity/users").RequirePermissions(IdentityPermissions.Users.Default)); url: "~/identity/users").RequirePermissions(IdentityPermissions.Users.Default));
return Task.CompletedTask; return Task.CompletedTask;
}
} }
} }

13
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 Roles = GroupName + ".Roles";
public const string Users = GroupName + ".Users"; public const string Users = GroupName + ".Users";
}
} }

125
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.ObjectExtending;
using Volo.Abp.Data; 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<TableColumn> RoleManagementTableColumns => TableColumns.Get<RoleManagement>(); protected List<TableColumn> RoleManagementTableColumns => TableColumns.Get<RoleManagement>();
public RoleManagement() public RoleManagement()
{ {
ObjectMapperContext = typeof(AbpIdentityBlazorModule); ObjectMapperContext = typeof(AbpIdentityBlazorModule);
LocalizationResource = typeof(IdentityResource); LocalizationResource = typeof(IdentityResource);
CreatePolicyName = IdentityPermissions.Roles.Create; CreatePolicyName = IdentityPermissions.Roles.Create;
UpdatePolicyName = IdentityPermissions.Roles.Update; UpdatePolicyName = IdentityPermissions.Roles.Update;
DeletePolicyName = IdentityPermissions.Roles.Delete; DeletePolicyName = IdentityPermissions.Roles.Delete;
ManagePermissionsPolicyName = IdentityPermissions.Roles.ManagePermissions; ManagePermissionsPolicyName = IdentityPermissions.Roles.ManagePermissions;
} }
protected override ValueTask SetEntityActionsAsync() protected override ValueTask SetEntityActionsAsync()
{ {
EntityActions EntityActions
.Get<RoleManagement>() .Get<RoleManagement>()
.AddRange(new EntityAction[] .AddRange(new EntityAction[]
{ {
new EntityAction new EntityAction
{ {
Text = L["Edit"], Text = L["Edit"],
@ -68,16 +68,16 @@ namespace Volo.Abp.Identity.Blazor.Pages.Identity
Clicked = async (data) => await DeleteEntityAsync(data.As<IdentityRoleDto>()), Clicked = async (data) => await DeleteEntityAsync(data.As<IdentityRoleDto>()),
ConfirmationMessage = (data) => GetDeleteConfirmationMessage(data.As<IdentityRoleDto>()) ConfirmationMessage = (data) => GetDeleteConfirmationMessage(data.As<IdentityRoleDto>())
} }
}); });
return base.SetEntityActionsAsync(); return base.SetEntityActionsAsync();
} }
protected override ValueTask SetTableColumnsAsync() protected override ValueTask SetTableColumnsAsync()
{ {
RoleManagementTableColumns RoleManagementTableColumns
.AddRange(new TableColumn[] .AddRange(new TableColumn[]
{ {
new TableColumn new TableColumn
{ {
Title = L["Actions"], Title = L["Actions"],
@ -89,35 +89,34 @@ namespace Volo.Abp.Identity.Blazor.Pages.Identity
Data = nameof(IdentityRoleDto.Name), Data = nameof(IdentityRoleDto.Name),
Component = typeof(RoleNameComponent) Component = typeof(RoleNameComponent)
}, },
}); });
RoleManagementTableColumns.AddRange(GetExtensionTableColumns(IdentityModuleExtensionConsts.ModuleName, RoleManagementTableColumns.AddRange(GetExtensionTableColumns(IdentityModuleExtensionConsts.ModuleName,
IdentityModuleExtensionConsts.EntityNames.Role)); IdentityModuleExtensionConsts.EntityNames.Role));
return base.SetTableColumnsAsync(); return base.SetTableColumnsAsync();
} }
protected override async Task SetPermissionsAsync() protected override async Task SetPermissionsAsync()
{ {
await base.SetPermissionsAsync(); await base.SetPermissionsAsync();
HasManagePermissionsPermission = HasManagePermissionsPermission =
await AuthorizationService.IsGrantedAsync(IdentityPermissions.Roles.ManagePermissions); await AuthorizationService.IsGrantedAsync(IdentityPermissions.Roles.ManagePermissions);
} }
protected override string GetDeleteConfirmationMessage(IdentityRoleDto entity) protected override string GetDeleteConfirmationMessage(IdentityRoleDto entity)
{ {
return string.Format(L["RoleDeletionConfirmationMessage"], entity.Name); return string.Format(L["RoleDeletionConfirmationMessage"], entity.Name);
} }
protected override ValueTask SetToolbarItemsAsync() protected override ValueTask SetToolbarItemsAsync()
{ {
Toolbar.AddButton(L["NewRole"], Toolbar.AddButton(L["NewRole"],
OpenCreateModalAsync, OpenCreateModalAsync,
IconName.Add, IconName.Add,
requiredPolicyName: CreatePolicyName); requiredPolicyName: CreatePolicyName);
return base.SetToolbarItemsAsync(); return base.SetToolbarItemsAsync();
}
} }
} }

11
modules/identity/src/Volo.Abp.Identity.Blazor/Pages/Identity/RoleNameComponent.razor.cs

@ -1,9 +1,8 @@
using Microsoft.AspNetCore.Components; 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; }
{ }
[Parameter] public object Data { get; set; }
}
}

227
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.ObjectExtending;
using Volo.Abp.PermissionManagement.Blazor.Components; 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<IdentityRoleDto> Roles; protected IReadOnlyList<IdentityRoleDto> 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<TableColumn> UserManagementTableColumns => TableColumns.Get<UserManagement>(); private List<TableColumn> UserManagementTableColumns => TableColumns.Get<UserManagement>();
public UserManagement() public UserManagement()
{ {
ObjectMapperContext = typeof(AbpIdentityBlazorModule); ObjectMapperContext = typeof(AbpIdentityBlazorModule);
LocalizationResource = typeof(IdentityResource); LocalizationResource = typeof(IdentityResource);
CreatePolicyName = IdentityPermissions.Users.Create; CreatePolicyName = IdentityPermissions.Users.Create;
UpdatePolicyName = IdentityPermissions.Users.Update; UpdatePolicyName = IdentityPermissions.Users.Update;
DeletePolicyName = IdentityPermissions.Users.Delete; DeletePolicyName = IdentityPermissions.Users.Delete;
ManagePermissionsPolicyName = IdentityPermissions.Users.ManagePermissions; ManagePermissionsPolicyName = IdentityPermissions.Users.ManagePermissions;
} }
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
await base.OnInitializedAsync(); await base.OnInitializedAsync();
try try
{ {
Roles = (await AppService.GetAssignableRolesAsync()).Items; Roles = (await AppService.GetAssignableRolesAsync()).Items;
}
catch (Exception ex)
{
await HandleErrorAsync(ex);
}
} }
catch (Exception ex)
protected override async Task SetPermissionsAsync()
{ {
await base.SetPermissionsAsync(); await HandleErrorAsync(ex);
HasManagePermissionsPermission =
await AuthorizationService.IsGrantedAsync(IdentityPermissions.Users.ManagePermissions);
} }
}
protected override Task OpenCreateModalAsync() protected override async Task SetPermissionsAsync()
{ {
CreateModalSelectedTab = DefaultSelectedTab; await base.SetPermissionsAsync();
NewUserRoles = Roles.Select(x => new AssignedRoleViewModel HasManagePermissionsPermission =
{ await AuthorizationService.IsGrantedAsync(IdentityPermissions.Users.ManagePermissions);
Name = x.Name, }
IsAssigned = x.IsDefault
}).ToArray();
return base.OpenCreateModalAsync(); protected override Task OpenCreateModalAsync()
} {
CreateModalSelectedTab = DefaultSelectedTab;
protected override Task OnCreatingEntityAsync() NewUserRoles = Roles.Select(x => new AssignedRoleViewModel
{ {
// apply roles before saving Name = x.Name,
NewEntity.RoleNames = NewUserRoles.Where(x => x.IsAssigned).Select(x => x.Name).ToArray(); IsAssigned = x.IsDefault
}).ToArray();
return base.OnCreatingEntityAsync(); return base.OpenCreateModalAsync();
} }
protected override async Task OpenEditModalAsync(IdentityUserDto entity) protected override Task OnCreatingEntityAsync()
{ {
try // apply roles before saving
{ NewEntity.RoleNames = NewUserRoles.Where(x => x.IsAssigned).Select(x => x.Name).ToArray();
EditModalSelectedTab = DefaultSelectedTab;
var userRoleNames = (await AppService.GetRolesAsync(entity.Id)).Items.Select(r => r.Name).ToList(); return base.OnCreatingEntityAsync();
}
EditUserRoles = Roles.Select(x => new AssignedRoleViewModel protected override async Task OpenEditModalAsync(IdentityUserDto entity)
{ {
Name = x.Name, try
IsAssigned = userRoleNames.Contains(x.Name) {
}).ToArray(); EditModalSelectedTab = DefaultSelectedTab;
await base.OpenEditModalAsync(entity); var userRoleNames = (await AppService.GetRolesAsync(entity.Id)).Items.Select(r => r.Name).ToList();
}
catch (Exception ex)
{
await HandleErrorAsync(ex);
}
}
protected override Task OnUpdatingEntityAsync() EditUserRoles = Roles.Select(x => new AssignedRoleViewModel
{ {
// apply roles before saving Name = x.Name,
EditingEntity.RoleNames = EditUserRoles.Where(x => x.IsAssigned).Select(x => x.Name).ToArray(); IsAssigned = userRoleNames.Contains(x.Name)
}).ToArray();
return base.OnUpdatingEntityAsync(); await base.OpenEditModalAsync(entity);
} }
catch (Exception ex)
protected override string GetDeleteConfirmationMessage(IdentityUserDto entity)
{ {
return string.Format(L["UserDeletionConfirmationMessage"], entity.UserName); await HandleErrorAsync(ex);
} }
}
protected override ValueTask SetEntityActionsAsync() protected override Task OnUpdatingEntityAsync()
{ {
EntityActions // apply roles before saving
.Get<UserManagement>() EditingEntity.RoleNames = EditUserRoles.Where(x => x.IsAssigned).Select(x => x.Name).ToArray();
.AddRange(new EntityAction[]
{ return base.OnUpdatingEntityAsync();
}
protected override string GetDeleteConfirmationMessage(IdentityUserDto entity)
{
return string.Format(L["UserDeletionConfirmationMessage"], entity.UserName);
}
protected override ValueTask SetEntityActionsAsync()
{
EntityActions
.Get<UserManagement>()
.AddRange(new EntityAction[]
{
new EntityAction new EntityAction
{ {
Text = L["Edit"], Text = L["Edit"],
@ -157,16 +157,16 @@ namespace Volo.Abp.Identity.Blazor.Pages.Identity
Clicked = async (data) => await DeleteEntityAsync(data.As<IdentityUserDto>()), Clicked = async (data) => await DeleteEntityAsync(data.As<IdentityUserDto>()),
ConfirmationMessage = (data) => GetDeleteConfirmationMessage(data.As<IdentityUserDto>()) ConfirmationMessage = (data) => GetDeleteConfirmationMessage(data.As<IdentityUserDto>())
} }
}); });
return base.SetEntityActionsAsync(); return base.SetEntityActionsAsync();
} }
protected override ValueTask SetTableColumnsAsync() protected override ValueTask SetTableColumnsAsync()
{ {
UserManagementTableColumns UserManagementTableColumns
.AddRange(new TableColumn[] .AddRange(new TableColumn[]
{ {
new TableColumn new TableColumn
{ {
Title = L["Actions"], Title = L["Actions"],
@ -187,27 +187,26 @@ namespace Volo.Abp.Identity.Blazor.Pages.Identity
Title = L["PhoneNumber"], Title = L["PhoneNumber"],
Data = nameof(IdentityUserDto.PhoneNumber), Data = nameof(IdentityUserDto.PhoneNumber),
} }
}); });
UserManagementTableColumns.AddRange(GetExtensionTableColumns(IdentityModuleExtensionConsts.ModuleName, UserManagementTableColumns.AddRange(GetExtensionTableColumns(IdentityModuleExtensionConsts.ModuleName,
IdentityModuleExtensionConsts.EntityNames.User)); IdentityModuleExtensionConsts.EntityNames.User));
return base.SetEntityActionsAsync(); return base.SetEntityActionsAsync();
}
protected override ValueTask SetToolbarItemsAsync()
{
Toolbar.AddButton(L["NewUser"], OpenCreateModalAsync,
IconName.Add,
requiredPolicyName: CreatePolicyName);
return base.SetToolbarItemsAsync();
}
} }
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();
} }
} }
public class AssignedRoleViewModel
{
public string Name { get; set; }
public bool IsAssigned { get; set; }
}

49
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.Validation.Localization;
using Volo.Abp.VirtualFileSystem; using Volo.Abp.VirtualFileSystem;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
[DependsOn(
typeof(AbpUsersDomainSharedModule),
typeof(AbpValidationModule),
typeof(AbpFeaturesModule)
)]
public class AbpIdentityDomainSharedModule : AbpModule
{ {
[DependsOn( public override void ConfigureServices(ServiceConfigurationContext context)
typeof(AbpUsersDomainSharedModule),
typeof(AbpValidationModule),
typeof(AbpFeaturesModule)
)]
public class AbpIdentityDomainSharedModule : AbpModule
{ {
public override void ConfigureServices(ServiceConfigurationContext context) Configure<AbpVirtualFileSystemOptions>(options =>
{ {
Configure<AbpVirtualFileSystemOptions>(options => options.FileSets.AddEmbedded<AbpIdentityDomainSharedModule>();
{ });
options.FileSets.AddEmbedded<AbpIdentityDomainSharedModule>();
});
Configure<AbpLocalizationOptions>(options => Configure<AbpLocalizationOptions>(options =>
{ {
options.Resources options.Resources
.Add<IdentityResource>("en") .Add<IdentityResource>("en")
.AddBaseTypes( .AddBaseTypes(
typeof(AbpValidationResource) typeof(AbpValidationResource)
).AddVirtualJson("/Volo/Abp/Identity/Localization"); ).AddVirtualJson("/Volo/Abp/Identity/Localization");
}); });
Configure<AbpExceptionLocalizationOptions>(options => Configure<AbpExceptionLocalizationOptions>(options =>
{ {
options.MapCodeNamespace("Volo.Abp.Identity", typeof(IdentityResource)); options.MapCodeNamespace("Volo.Abp.Identity", typeof(IdentityResource));
}); });
}
} }
} }

9
modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IUserRoleFinder.cs

@ -1,10 +1,9 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public interface IUserRoleFinder
{ {
public interface IUserRoleFinder Task<string[]> GetRolesAsync(Guid userId);
{
Task<string[]> GetRolesAsync(Guid userId);
}
} }

45
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 /// <summary>
{ /// Default value: 256
/// <summary> /// </summary>
/// Default value: 256 public static int MaxNameLength { get; set; } = 256;
/// </summary>
public static int MaxNameLength { get; set; } = 256; /// <summary>
/// Default value: 512
/// <summary> /// </summary>
/// Default value: 512 public static int MaxRegexLength { get; set; } = 512;
/// </summary>
public static int MaxRegexLength { get; set; } = 512; /// <summary>
/// Default value: 128
/// <summary> /// </summary>
/// Default value: 128 public static int MaxRegexDescriptionLength { get; set; } = 128;
/// </summary>
public static int MaxRegexDescriptionLength { get; set; } = 128; /// <summary>
/// Default value: 256
/// <summary> /// </summary>
/// Default value: 256 public static int MaxDescriptionLength { get; set; } = 256;
/// </summary>
public static int MaxDescriptionLength { get; set; } = 256;
}
} }

27
modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityClaimTypeEto.cs

@ -1,24 +1,23 @@
using System; using System;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
[Serializable]
public class IdentityClaimTypeEto
{ {
[Serializable] public Guid Id { get; set; }
public class IdentityClaimTypeEto
{ 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; }
}
} }

15
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,
String, Boolean,
Int, DateTime
Boolean,
DateTime
}
} }

23
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 UserSelfDeletion = "Volo.Abp.Identity:010001"; public const string ExternalUserPasswordChange = "Volo.Abp.Identity:010003";
public const string MaxAllowedOuMembership = "Volo.Abp.Identity:010002"; public const string DuplicateOrganizationUnitDisplayName = "Volo.Abp.Identity:010004";
public const string ExternalUserPasswordChange = "Volo.Abp.Identity:010003"; public const string StaticRoleRenaming = "Volo.Abp.Identity:010005";
public const string DuplicateOrganizationUnitDisplayName = "Volo.Abp.Identity:010004"; public const string StaticRoleDeletion = "Volo.Abp.Identity:010006";
public const string StaticRoleRenaming = "Volo.Abp.Identity:010005"; public const string UsersCanNotChangeTwoFactor = "Volo.Abp.Identity:010007";
public const string StaticRoleDeletion = "Volo.Abp.Identity:010006"; public const string CanNotChangeTwoFactor = "Volo.Abp.Identity:010008";
public const string UsersCanNotChangeTwoFactor = "Volo.Abp.Identity:010007";
public const string CanNotChangeTwoFactor = "Volo.Abp.Identity:010008";
}
} }

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

25
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 /// <summary>
{ /// Default value: 256
/// <summary> /// </summary>
/// Default value: 256 public static int MaxNameLength { get; set; } = 256;
/// </summary>
public static int MaxNameLength { get; set; } = 256; /// <summary>
/// Default value: 256
/// <summary> /// </summary>
/// Default value: 256 public static int MaxNormalizedNameLength { get; set; } = 256;
/// </summary>
public static int MaxNormalizedNameLength { get; set; } = 256;
}
} }

27
modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleEto.cs

@ -1,20 +1,19 @@
using System; using System;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
[Serializable]
public class IdentityRoleEto
{ {
[Serializable] public Guid Id { get; set; }
public class IdentityRoleEto
{ public Guid? TenantId { get; set; }
public Guid Id { get; set; }
public string Name { get; set; }
public Guid? TenantId { get; set; } public bool IsDefault { get; set; }
public string Name { get; set; } public bool IsStatic { get; set; }
public bool IsDefault { get; set; }
public bool IsStatic { get; set; } public bool IsPublic { get; set; }
}
public bool IsPublic { get; set; }
}
}

19
modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityRoleNameChangedEto.cs

@ -1,16 +1,15 @@
using System; using System;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
[Serializable]
public class IdentityRoleNameChangedEto
{ {
[Serializable] public Guid Id { get; set; }
public class IdentityRoleNameChangedEto
{
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; } public string OldName { get; set; }
} }
}

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

99
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 /// <summary>
{ /// Default value: 96
/// <summary> /// </summary>
/// Default value: 96 public static int MaxApplicationNameLength { get; set; } = 96;
/// </summary>
public static int MaxApplicationNameLength { get; set; } = 96; /// <summary>
/// Default value: 96
/// <summary> /// </summary>
/// Default value: 96 public static int MaxIdentityLength { get; set; } = 96;
/// </summary>
public static int MaxIdentityLength { get; set; } = 96; /// <summary>
/// Default value: 96
/// <summary> /// </summary>
/// Default value: 96 public static int MaxActionLength { get; set; } = 96;
/// </summary>
public static int MaxActionLength { get; set; } = 96;
/// <summary>
/// Default value: 256
/// <summary> /// </summary>
/// Default value: 256 public static int MaxUserNameLength { get; set; } = 256;
/// </summary>
public static int MaxUserNameLength { get; set; } = 256; /// <summary>
/// Default value: 64
/// <summary> /// </summary>
/// Default value: 64 public static int MaxTenantNameLength { get; set; } = 64;
/// </summary>
public static int MaxTenantNameLength { get; set; } = 64; /// <summary>
/// Default value: 64
/// <summary> /// </summary>
/// Default value: 64 public static int MaxClientIpAddressLength { get; set; } = 64;
/// </summary>
public static int MaxClientIpAddressLength { get; set; } = 64; /// <summary>
/// Default value: 64
/// <summary> /// </summary>
/// Default value: 64 public static int MaxClientIdLength { get; set; } = 64;
/// </summary>
public static int MaxClientIdLength { get; set; } = 64; /// <summary>
/// Default value: 64
/// <summary> /// </summary>
/// Default value: 64 public static int MaxCorrelationIdLength { get; set; } = 64;
/// </summary>
public static int MaxCorrelationIdLength { get; set; } = 64; /// <summary>
/// Default value: 512
/// <summary> /// </summary>
/// Default value: 512 public static int MaxBrowserInfoLength { get; set; } = 512;
/// </summary>
public static int MaxBrowserInfoLength { get; set; } = 512;
}
} }

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

23
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 /// <summary>
{ /// Default value: 256
/// <summary> /// </summary>
/// Default value: 256 public static int MaxClaimTypeLength { get; set; } = 256;
/// </summary>
public static int MaxClaimTypeLength { get; set; } = 256;
/// <summary> /// <summary>
/// Default value: 1024 /// Default value: 1024
/// </summary> /// </summary>
public static int MaxClaimValueLength { get; set; } = 1024; public static int MaxClaimValueLength { get; set; } = 1024;
}
} }

53
modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/IdentityUserConsts.cs

@ -1,41 +1,40 @@
using Volo.Abp.Users; 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;
/// <summary> /// <summary>
/// Default value: 128 /// Default value: 128
/// </summary> /// </summary>
public static int MaxPasswordLength { get; set; } = 128; public static int MaxPasswordLength { get; set; } = 128;
/// <summary> /// <summary>
/// Default value: 256 /// Default value: 256
/// </summary> /// </summary>
public static int MaxPasswordHashLength { get; set; } = 256; public static int MaxPasswordHashLength { get; set; } = 256;
/// <summary> /// <summary>
/// Default value: 256 /// Default value: 256
/// </summary> /// </summary>
public static int MaxSecurityStampLength { get; set; } = 256; public static int MaxSecurityStampLength { get; set; } = 256;
/// <summary> /// <summary>
/// Default value: 16 /// Default value: 16
/// </summary> /// </summary>
public static int MaxLoginProviderLength { get; set; } = 16; public static int MaxLoginProviderLength { get; set; } = 16;
}
} }

35
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 /// <summary>
{ /// Default value: 64
/// <summary> /// </summary>
/// Default value: 64 public static int MaxLoginProviderLength { get; set; } = 64;
/// </summary>
public static int MaxLoginProviderLength { get; set; } = 64; /// <summary>
/// Default value: 196
/// <summary> /// </summary>
/// Default value: 196 public static int MaxProviderKeyLength { get; set; } = 196;
/// </summary>
public static int MaxProviderKeyLength { get; set; } = 196; /// <summary>
/// Default value: 128
/// <summary> /// </summary>
/// Default value: 128 public static int MaxProviderDisplayNameLength { get; set; } = 128;
/// </summary>
public static int MaxProviderDisplayNameLength { get; set; } = 128;
}
} }

23
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 /// <summary>
{ /// Default value: 64
/// <summary> /// </summary>
/// Default value: 64 public static int MaxLoginProviderLength { get; set; } = 64;
/// </summary>
public static int MaxLoginProviderLength { get; set; } = 64;
/// <summary> /// <summary>
/// Default value: 128 /// Default value: 128
/// </summary> /// </summary>
public static int MaxNameLength { get; set; } = 128; public static int MaxNameLength { get; set; } = 128;
}
} }

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

11
modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/Localization/IdentityResource.cs

@ -1,10 +1,9 @@
using Volo.Abp.Localization; using Volo.Abp.Localization;
namespace Volo.Abp.Identity.Localization namespace Volo.Abp.Identity.Localization;
[LocalizationResourceName("AbpIdentity")]
public class IdentityResource
{ {
[LocalizationResourceName("AbpIdentity")]
public class IdentityResource
{
}
} }

39
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 /// <summary>
{ /// Maximum length of the DisplayName property.
/// <summary> /// </summary>
/// Maximum length of the DisplayName property. public static int MaxDisplayNameLength { get; set; } = 128;
/// </summary>
public static int MaxDisplayNameLength { get; set; } = 128;
/// <summary> /// <summary>
/// Maximum depth of an OU hierarchy. /// Maximum depth of an OU hierarchy.
/// </summary> /// </summary>
public const int MaxDepth = 16; public const int MaxDepth = 16;
/// <summary> /// <summary>
/// Length of a code unit between dots. /// Length of a code unit between dots.
/// </summary> /// </summary>
public const int CodeUnitLength = 5; public const int CodeUnitLength = 5;
/// <summary> /// <summary>
/// Maximum length of the Code property. /// Maximum length of the Code property.
/// </summary> /// </summary>
public const int MaxCodeLength = MaxDepth * (CodeUnitLength + 1) - 1; public const int MaxCodeLength = MaxDepth * (CodeUnitLength + 1) - 1;
}
} }

19
modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/Identity/OrganizationUnitEto.cs

@ -1,16 +1,15 @@
using System; using System;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
[Serializable]
public class OrganizationUnitEto
{ {
[Serializable] public Guid Id { get; set; }
public class OrganizationUnitEto
{
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; } public string DisplayName { get; set; }
} }
}

95
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"; private const string SignInPrefix = Prefix + ".SignIn";
public static class Password public const string RequireConfirmedEmail = SignInPrefix + ".RequireConfirmedEmail";
{ public const string EnablePhoneNumberConfirmation = SignInPrefix + ".EnablePhoneNumberConfirmation";
private const string PasswordPrefix = Prefix + ".Password"; public const string RequireConfirmedPhoneNumber = SignInPrefix + ".RequireConfirmedPhoneNumber";
}
public const string RequiredLength = PasswordPrefix + ".RequiredLength";
public const string RequiredUniqueChars = PasswordPrefix + ".RequiredUniqueChars"; public static class User
public const string RequireNonAlphanumeric = PasswordPrefix + ".RequireNonAlphanumeric"; {
public const string RequireLowercase = PasswordPrefix + ".RequireLowercase"; private const string UserPrefix = Prefix + ".User";
public const string RequireUppercase = PasswordPrefix + ".RequireUppercase";
public const string RequireDigit = PasswordPrefix + ".RequireDigit"; public const string IsUserNameUpdateEnabled = UserPrefix + ".IsUserNameUpdateEnabled";
} public const string IsEmailUpdateEnabled = UserPrefix + ".IsEmailUpdateEnabled";
}
public static class Lockout
{ public static class OrganizationUnit
private const string LockoutPrefix = Prefix + ".Lockout"; {
private const string OrganizationUnitPrefix = Prefix + ".OrganizationUnit";
public const string AllowedForNewUsers = LockoutPrefix + ".AllowedForNewUsers";
public const string LockoutDuration = LockoutPrefix + ".LockoutDuration"; public const string MaxUserMembershipCount = OrganizationUnitPrefix + ".MaxUserMembershipCount";
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";
}
} }
} }

71
modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfiguration.cs

@ -1,44 +1,43 @@
using System; using System;
using Volo.Abp.ObjectExtending.Modularity; 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<EntityExtensionConfiguration> configureAction)
{
return this.ConfigureEntity(
IdentityModuleExtensionConsts.EntityNames.User,
configureAction
);
}
public IdentityModuleExtensionConfiguration ConfigureRole(
Action<EntityExtensionConfiguration> configureAction)
{ {
public IdentityModuleExtensionConfiguration ConfigureUser( return this.ConfigureEntity(
Action<EntityExtensionConfiguration> configureAction) IdentityModuleExtensionConsts.EntityNames.Role,
{ configureAction
return this.ConfigureEntity( );
IdentityModuleExtensionConsts.EntityNames.User, }
configureAction
);
}
public IdentityModuleExtensionConfiguration ConfigureRole( public IdentityModuleExtensionConfiguration ConfigureClaimType(
Action<EntityExtensionConfiguration> configureAction) Action<EntityExtensionConfiguration> configureAction)
{ {
return this.ConfigureEntity( return this.ConfigureEntity(
IdentityModuleExtensionConsts.EntityNames.Role, IdentityModuleExtensionConsts.EntityNames.ClaimType,
configureAction configureAction
); );
} }
public IdentityModuleExtensionConfiguration ConfigureClaimType( public IdentityModuleExtensionConfiguration ConfigureOrganizationUnit(
Action<EntityExtensionConfiguration> configureAction) Action<EntityExtensionConfiguration> configureAction)
{ {
return this.ConfigureEntity( return this.ConfigureEntity(
IdentityModuleExtensionConsts.EntityNames.ClaimType, IdentityModuleExtensionConsts.EntityNames.OrganizationUnit,
configureAction configureAction
); );
}
public IdentityModuleExtensionConfiguration ConfigureOrganizationUnit(
Action<EntityExtensionConfiguration> configureAction)
{
return this.ConfigureEntity(
IdentityModuleExtensionConsts.EntityNames.OrganizationUnit,
configureAction
);
}
} }
} }

21
modules/identity/src/Volo.Abp.Identity.Domain.Shared/Volo/Abp/ObjectExtending/IdentityModuleExtensionConfigurationDictionaryExtensions.cs

@ -1,18 +1,17 @@
using System; using System;
using Volo.Abp.ObjectExtending.Modularity; 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<IdentityModuleExtensionConfiguration> configureAction)
{ {
public static ModuleExtensionConfigurationDictionary ConfigureIdentity( return modules.ConfigureModule(
this ModuleExtensionConfigurationDictionary modules, IdentityModuleExtensionConsts.ModuleName,
Action<IdentityModuleExtensionConfiguration> configureAction) configureAction
{ );
return modules.ConfigureModule(
IdentityModuleExtensionConsts.ModuleName,
configureAction
);
}
} }
} }

23
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 Role = "Role";
{
public const string User = "User";
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";
}
} }
} }

195
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.Identity;
using Volo.Abp.Text.Formatting; 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<string, string> IdentityStrings = new Dictionary<string, string>();
static AbpIdentityResultExtensions()
{ {
private static readonly Dictionary<string, string> IdentityStrings = new Dictionary<string, string>(); 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); if (!iterator.MoveNext())
var resourceSet = identityResourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, false);
if (resourceSet == null)
{ {
throw new AbpException("Can't get the ResourceSet of Identity."); break;
} }
var iterator = resourceSet.GetEnumerator(); var key = iterator.Key?.ToString();
while (true) var value = iterator.Value?.ToString();
if (key != null && value != null)
{ {
if (!iterator.MoveNext()) IdentityStrings.Add(key, value);
{
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.");
} }
} }
public static void CheckErrors(this IdentityResult identityResult) if (!IdentityStrings.Any())
{ {
if (identityResult.Succeeded) throw new AbpException("ResourceSet values of Identity is empty.");
{ }
return; }
}
if (identityResult.Errors == null)
{
throw new ArgumentException("identityResult.Errors should not be null.");
}
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.Errors should not be null.");
{ }
throw new ArgumentException(
"identityResult.Succeeded should be false in order to get values from error.");
}
if (identityResult.Errors == null) throw new AbpIdentityResultException(identityResult);
{ }
throw new ArgumentException("identityResult.Errors should not be null.");
}
var error = identityResult.Errors.First(); public static string[] GetValuesFromErrorMessage(this IdentityResult identityResult, IStringLocalizer localizer)
var englishString = IdentityStrings.GetOrDefault(error.Code); {
if (identityResult.Succeeded)
{
throw new ArgumentException(
"identityResult.Succeeded should be false in order to get values from error.");
}
if (englishString == null) if (identityResult.Errors == null)
{ {
return Array.Empty<string>(); throw new ArgumentException("identityResult.Errors should not be null.");
} }
if (FormattedStringValueExtracter.IsMatch(error.Description, englishString, out var values)) var error = identityResult.Errors.First();
{ var englishString = IdentityStrings.GetOrDefault(error.Code);
return values;
}
if (englishString == null)
{
return Array.Empty<string>(); return Array.Empty<string>();
} }
public static string LocalizeErrors(this IdentityResult identityResult, IStringLocalizer localizer) if (FormattedStringValueExtracter.IsMatch(error.Description, englishString, out var values))
{ {
if (identityResult.Succeeded) return values;
{ }
throw new ArgumentException("identityResult.Succeeded should be false in order to localize errors.");
}
if (identityResult.Errors == null) return Array.Empty<string>();
{ }
throw new ArgumentException("identityResult.Errors should not be null.");
}
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 (FormattedStringValueExtracter.IsMatch(error.Description, englishString, out var values))
if (englishString != null)
{ {
if (FormattedStringValueExtracter.IsMatch(error.Description, englishString, out var values)) return string.Format(localizedString.Value, values.Cast<object>().ToArray());
{
return string.Format(localizedString.Value, values.Cast<object>().ToArray());
}
} }
} }
return localizer["Identity.Default"];
} }
public static string GetResultAsString(this SignInResult signInResult) return localizer["Identity.Default"];
{ }
if (signInResult.Succeeded)
{
return "Succeeded";
}
if (signInResult.IsLockedOut) public static string GetResultAsString(this SignInResult signInResult)
{ {
return "IsLockedOut"; if (signInResult.Succeeded)
} {
return "Succeeded";
}
if (signInResult.IsNotAllowed) if (signInResult.IsLockedOut)
{ {
return "IsNotAllowed"; return "IsLockedOut";
} }
if (signInResult.RequiresTwoFactor) if (signInResult.IsNotAllowed)
{ {
return "RequiresTwoFactor"; return "IsNotAllowed";
} }
return "Unknown"; if (signInResult.RequiresTwoFactor)
{
return "RequiresTwoFactor";
} }
return "Unknown";
} }
} }

49
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 Microsoft.Extensions.DependencyInjection.Extensions;
using Volo.Abp.Identity; 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<IdentityOptions> setupAction) public static IdentityBuilder AddAbpIdentity(this IServiceCollection services, Action<IdentityOptions> setupAction)
{ {
//AbpRoleManager //AbpRoleManager
services.TryAddScoped<IdentityRoleManager>(); services.TryAddScoped<IdentityRoleManager>();
services.TryAddScoped(typeof(RoleManager<IdentityRole>), provider => provider.GetService(typeof(IdentityRoleManager))); services.TryAddScoped(typeof(RoleManager<IdentityRole>), provider => provider.GetService(typeof(IdentityRoleManager)));
//AbpUserManager //AbpUserManager
services.TryAddScoped<IdentityUserManager>(); services.TryAddScoped<IdentityUserManager>();
services.TryAddScoped(typeof(UserManager<IdentityUser>), provider => provider.GetService(typeof(IdentityUserManager))); services.TryAddScoped(typeof(UserManager<IdentityUser>), provider => provider.GetService(typeof(IdentityUserManager)));
//AbpUserStore //AbpUserStore
services.TryAddScoped<IdentityUserStore>(); services.TryAddScoped<IdentityUserStore>();
services.TryAddScoped(typeof(IUserStore<IdentityUser>), provider => provider.GetService(typeof(IdentityUserStore))); services.TryAddScoped(typeof(IUserStore<IdentityUser>), provider => provider.GetService(typeof(IdentityUserStore)));
//AbpRoleStore //AbpRoleStore
services.TryAddScoped<IdentityRoleStore>(); services.TryAddScoped<IdentityRoleStore>();
services.TryAddScoped(typeof(IRoleStore<IdentityRole>), provider => provider.GetService(typeof(IdentityRoleStore))); services.TryAddScoped(typeof(IRoleStore<IdentityRole>), provider => provider.GetService(typeof(IdentityRoleStore)));
return services return services
.AddIdentityCore<IdentityUser>(setupAction) .AddIdentityCore<IdentityUser>(setupAction)
.AddRoles<IdentityRole>() .AddRoles<IdentityRole>()
.AddClaimsPrincipalFactory<AbpUserClaimsPrincipalFactory>(); .AddClaimsPrincipalFactory<AbpUserClaimsPrincipalFactory>();
}
} }
} }

13
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/AbpIdentityDbProperties.cs

@ -1,13 +1,12 @@
using Volo.Abp.Data; 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";
}
} }

127
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.Threading;
using Volo.Abp.Users; 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( private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
typeof(AbpDddDomainModule),
typeof(AbpIdentityDomainSharedModule), public override void ConfigureServices(ServiceConfigurationContext context)
typeof(AbpUsersDomainModule),
typeof(AbpAutoMapperModule)
)]
public class AbpIdentityDomainModule : AbpModule
{ {
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); context.Services.AddAutoMapperObjectMapper<AbpIdentityDomainModule>();
public override void ConfigureServices(ServiceConfigurationContext context) Configure<AbpAutoMapperOptions>(options =>
{ {
context.Services.AddAutoMapperObjectMapper<AbpIdentityDomainModule>(); options.AddProfile<IdentityDomainMappingProfile>(validate: true);
});
Configure<AbpAutoMapperOptions>(options => Configure<AbpDistributedEntityEventOptions>(options =>
{ {
options.AddProfile<IdentityDomainMappingProfile>(validate: true); options.EtoMappings.Add<IdentityUser, UserEto>(typeof(AbpIdentityDomainModule));
}); options.EtoMappings.Add<IdentityClaimType, IdentityClaimTypeEto>(typeof(AbpIdentityDomainModule));
options.EtoMappings.Add<IdentityRole, IdentityRoleEto>(typeof(AbpIdentityDomainModule));
options.EtoMappings.Add<OrganizationUnit, OrganizationUnitEto>(typeof(AbpIdentityDomainModule));
Configure<AbpDistributedEntityEventOptions>(options => options.AutoEventSelectors.Add<IdentityUser>();
{ options.AutoEventSelectors.Add<IdentityRole>();
options.EtoMappings.Add<IdentityUser, UserEto>(typeof(AbpIdentityDomainModule)); });
options.EtoMappings.Add<IdentityClaimType, IdentityClaimTypeEto>(typeof(AbpIdentityDomainModule));
options.EtoMappings.Add<IdentityRole, IdentityRoleEto>(typeof(AbpIdentityDomainModule));
options.EtoMappings.Add<OrganizationUnit, OrganizationUnitEto>(typeof(AbpIdentityDomainModule));
options.AutoEventSelectors.Add<IdentityUser>();
options.AutoEventSelectors.Add<IdentityRole>();
});
var identityBuilder = context.Services.AddAbpIdentity(options => var identityBuilder = context.Services.AddAbpIdentity(options =>
{ {
options.User.RequireUniqueEmail = true; options.User.RequireUniqueEmail = true;
}); });
context.Services.AddObjectAccessor(identityBuilder); context.Services.AddObjectAccessor(identityBuilder);
context.Services.ExecutePreConfiguredActions(identityBuilder); context.Services.ExecutePreConfiguredActions(identityBuilder);
Configure<IdentityOptions>(options => Configure<IdentityOptions>(options =>
{ {
options.ClaimsIdentity.UserIdClaimType = AbpClaimTypes.UserId; options.ClaimsIdentity.UserIdClaimType = AbpClaimTypes.UserId;
options.ClaimsIdentity.UserNameClaimType = AbpClaimTypes.UserName; options.ClaimsIdentity.UserNameClaimType = AbpClaimTypes.UserName;
options.ClaimsIdentity.RoleClaimType = AbpClaimTypes.Role; options.ClaimsIdentity.RoleClaimType = AbpClaimTypes.Role;
}); });
context.Services.AddAbpDynamicOptions<IdentityOptions, AbpIdentityOptionsManager>(); context.Services.AddAbpDynamicOptions<IdentityOptions, AbpIdentityOptionsManager>();
} }
public override void PostConfigureServices(ServiceConfigurationContext context) public override void PostConfigureServices(ServiceConfigurationContext context)
{
OneTimeRunner.Run(() =>
{ {
OneTimeRunner.Run(() => ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity(
{ IdentityModuleExtensionConsts.ModuleName,
ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( IdentityModuleExtensionConsts.EntityNames.User,
IdentityModuleExtensionConsts.ModuleName, typeof(IdentityUser)
IdentityModuleExtensionConsts.EntityNames.User, );
typeof(IdentityUser)
);
ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity(
IdentityModuleExtensionConsts.ModuleName, IdentityModuleExtensionConsts.ModuleName,
IdentityModuleExtensionConsts.EntityNames.Role, IdentityModuleExtensionConsts.EntityNames.Role,
typeof(IdentityRole) typeof(IdentityRole)
); );
ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity(
IdentityModuleExtensionConsts.ModuleName, IdentityModuleExtensionConsts.ModuleName,
IdentityModuleExtensionConsts.EntityNames.ClaimType, IdentityModuleExtensionConsts.EntityNames.ClaimType,
typeof(IdentityClaimType) typeof(IdentityClaimType)
); );
ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity( ModuleExtensionConfigurationHelper.ApplyEntityConfigurationToEntity(
IdentityModuleExtensionConsts.ModuleName, IdentityModuleExtensionConsts.ModuleName,
IdentityModuleExtensionConsts.EntityNames.OrganizationUnit, IdentityModuleExtensionConsts.EntityNames.OrganizationUnit,
typeof(OrganizationUnit) typeof(OrganizationUnit)
); );
}); });
}
} }
} }

15
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() public AbpIdentityOptions()
{ {
ExternalLoginProviders = new ExternalLoginProviderDictionary(); ExternalLoginProviders = new ExternalLoginProviderDictionary();
}
} }
} }

47
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.Options;
using Volo.Abp.Settings; using Volo.Abp.Settings;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public class AbpIdentityOptionsManager : AbpDynamicOptionsManager<IdentityOptions>
{ {
public class AbpIdentityOptionsManager : AbpDynamicOptionsManager<IdentityOptions> protected ISettingProvider SettingProvider { get; }
{
protected ISettingProvider SettingProvider { get; }
public AbpIdentityOptionsManager(IOptionsFactory<IdentityOptions> factory, public AbpIdentityOptionsManager(IOptionsFactory<IdentityOptions> factory,
ISettingProvider settingProvider) ISettingProvider settingProvider)
: base(factory) : base(factory)
{ {
SettingProvider = settingProvider; SettingProvider = settingProvider;
} }
protected override async Task OverrideOptionsAsync(string name, IdentityOptions options) protected override async Task OverrideOptionsAsync(string name, IdentityOptions options)
{ {
options.Password.RequiredLength = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequiredLength, options.Password.RequiredLength); 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.RequiredUniqueChars = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequiredUniqueChars, options.Password.RequiredUniqueChars);
options.Password.RequireNonAlphanumeric = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequireNonAlphanumeric, options.Password.RequireNonAlphanumeric); 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.RequireLowercase = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequireLowercase, options.Password.RequireLowercase);
options.Password.RequireUppercase = await SettingProvider.GetAsync(IdentitySettingNames.Password.RequireUppercase, options.Password.RequireUppercase); 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.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.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<int>())); options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(await SettingProvider.GetAsync(IdentitySettingNames.Lockout.LockoutDuration, options.Lockout.DefaultLockoutTimeSpan.TotalSeconds.To<int>()));
options.Lockout.MaxFailedAccessAttempts = await SettingProvider.GetAsync(IdentitySettingNames.Lockout.MaxFailedAccessAttempts, options.Lockout.MaxFailedAccessAttempts); 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.RequireConfirmedEmail = await SettingProvider.GetAsync(IdentitySettingNames.SignIn.RequireConfirmedEmail, options.SignIn.RequireConfirmedEmail);
options.SignIn.RequireConfirmedPhoneNumber = await SettingProvider.GetAsync(IdentitySettingNames.SignIn.RequireConfirmedPhoneNumber, options.SignIn.RequireConfirmedPhoneNumber); options.SignIn.RequireConfirmedPhoneNumber = await SettingProvider.GetAsync(IdentitySettingNames.SignIn.RequireConfirmedPhoneNumber, options.SignIn.RequireConfirmedPhoneNumber);
}
} }
} }

55
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.Identity.Localization;
using Volo.Abp.Localization; using Volo.Abp.Localization;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
[Serializable]
public class AbpIdentityResultException : BusinessException, ILocalizeErrorMessage
{ {
[Serializable] public IdentityResult IdentityResult { get; }
public class AbpIdentityResultException : BusinessException, ILocalizeErrorMessage
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) public AbpIdentityResultException(SerializationInfo serializationInfo, StreamingContext context)
: base( : base(serializationInfo, context)
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 virtual string LocalizeMessage(LocalizationContext context)
{
var localizer = context.LocalizerFactory.Create<IdentityResource>();
public virtual string LocalizeMessage(LocalizationContext context) SetData(localizer);
{
var localizer = context.LocalizerFactory.Create<IdentityResource>();
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); Data[index.ToString()] = values[index];
for (var index = 0; index < values.Length; index++)
{
Data[index.ToString()] = values[index];
}
} }
} }
} }

201
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.Localization;
using Volo.Abp.Settings; 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(
context.Add( IdentitySettingNames.Password.RequiredLength,
new SettingDefinition( 6.ToString(),
IdentitySettingNames.Password.RequiredLength, L("DisplayName:Abp.Identity.Password.RequiredLength"),
6.ToString(), L("Description:Abp.Identity.Password.RequiredLength"),
L("DisplayName:Abp.Identity.Password.RequiredLength"), true),
L("Description:Abp.Identity.Password.RequiredLength"),
true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.Password.RequiredUniqueChars, IdentitySettingNames.Password.RequiredUniqueChars,
1.ToString(), 1.ToString(),
L("DisplayName:Abp.Identity.Password.RequiredUniqueChars"), L("DisplayName:Abp.Identity.Password.RequiredUniqueChars"),
L("Description:Abp.Identity.Password.RequiredUniqueChars"), L("Description:Abp.Identity.Password.RequiredUniqueChars"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.Password.RequireNonAlphanumeric, IdentitySettingNames.Password.RequireNonAlphanumeric,
true.ToString(), true.ToString(),
L("DisplayName:Abp.Identity.Password.RequireNonAlphanumeric"), L("DisplayName:Abp.Identity.Password.RequireNonAlphanumeric"),
L("Description:Abp.Identity.Password.RequireNonAlphanumeric"), L("Description:Abp.Identity.Password.RequireNonAlphanumeric"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.Password.RequireLowercase, IdentitySettingNames.Password.RequireLowercase,
true.ToString(), true.ToString(),
L("DisplayName:Abp.Identity.Password.RequireLowercase"), L("DisplayName:Abp.Identity.Password.RequireLowercase"),
L("Description:Abp.Identity.Password.RequireLowercase"), L("Description:Abp.Identity.Password.RequireLowercase"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.Password.RequireUppercase, IdentitySettingNames.Password.RequireUppercase,
true.ToString(), true.ToString(),
L("DisplayName:Abp.Identity.Password.RequireUppercase"), L("DisplayName:Abp.Identity.Password.RequireUppercase"),
L("Description:Abp.Identity.Password.RequireUppercase"), L("Description:Abp.Identity.Password.RequireUppercase"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.Password.RequireDigit, IdentitySettingNames.Password.RequireDigit,
true.ToString(), true.ToString(),
L("DisplayName:Abp.Identity.Password.RequireDigit"), L("DisplayName:Abp.Identity.Password.RequireDigit"),
L("Description:Abp.Identity.Password.RequireDigit"), L("Description:Abp.Identity.Password.RequireDigit"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.Lockout.AllowedForNewUsers, IdentitySettingNames.Lockout.AllowedForNewUsers,
true.ToString(), true.ToString(),
L("DisplayName:Abp.Identity.Lockout.AllowedForNewUsers"), L("DisplayName:Abp.Identity.Lockout.AllowedForNewUsers"),
L("Description:Abp.Identity.Lockout.AllowedForNewUsers"), L("Description:Abp.Identity.Lockout.AllowedForNewUsers"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.Lockout.LockoutDuration, IdentitySettingNames.Lockout.LockoutDuration,
(5 * 60).ToString(), (5 * 60).ToString(),
L("DisplayName:Abp.Identity.Lockout.LockoutDuration"), L("DisplayName:Abp.Identity.Lockout.LockoutDuration"),
L("Description:Abp.Identity.Lockout.LockoutDuration"), L("Description:Abp.Identity.Lockout.LockoutDuration"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.Lockout.MaxFailedAccessAttempts, IdentitySettingNames.Lockout.MaxFailedAccessAttempts,
5.ToString(), 5.ToString(),
L("DisplayName:Abp.Identity.Lockout.MaxFailedAccessAttempts"), L("DisplayName:Abp.Identity.Lockout.MaxFailedAccessAttempts"),
L("Description:Abp.Identity.Lockout.MaxFailedAccessAttempts"), L("Description:Abp.Identity.Lockout.MaxFailedAccessAttempts"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.SignIn.RequireConfirmedEmail, IdentitySettingNames.SignIn.RequireConfirmedEmail,
false.ToString(), false.ToString(),
L("DisplayName:Abp.Identity.SignIn.RequireConfirmedEmail"), L("DisplayName:Abp.Identity.SignIn.RequireConfirmedEmail"),
L("Description:Abp.Identity.SignIn.RequireConfirmedEmail"), L("Description:Abp.Identity.SignIn.RequireConfirmedEmail"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.SignIn.EnablePhoneNumberConfirmation, IdentitySettingNames.SignIn.EnablePhoneNumberConfirmation,
true.ToString(), true.ToString(),
L("DisplayName:Abp.Identity.SignIn.EnablePhoneNumberConfirmation"), L("DisplayName:Abp.Identity.SignIn.EnablePhoneNumberConfirmation"),
L("Description:Abp.Identity.SignIn.EnablePhoneNumberConfirmation"), L("Description:Abp.Identity.SignIn.EnablePhoneNumberConfirmation"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.SignIn.RequireConfirmedPhoneNumber, IdentitySettingNames.SignIn.RequireConfirmedPhoneNumber,
false.ToString(), false.ToString(),
L("DisplayName:Abp.Identity.SignIn.RequireConfirmedPhoneNumber"), L("DisplayName:Abp.Identity.SignIn.RequireConfirmedPhoneNumber"),
L("Description:Abp.Identity.SignIn.RequireConfirmedPhoneNumber"), L("Description:Abp.Identity.SignIn.RequireConfirmedPhoneNumber"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.User.IsUserNameUpdateEnabled, IdentitySettingNames.User.IsUserNameUpdateEnabled,
true.ToString(), true.ToString(),
L("DisplayName:Abp.Identity.User.IsUserNameUpdateEnabled"), L("DisplayName:Abp.Identity.User.IsUserNameUpdateEnabled"),
L("Description:Abp.Identity.User.IsUserNameUpdateEnabled"), L("Description:Abp.Identity.User.IsUserNameUpdateEnabled"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.User.IsEmailUpdateEnabled, IdentitySettingNames.User.IsEmailUpdateEnabled,
true.ToString(), true.ToString(),
L("DisplayName:Abp.Identity.User.IsEmailUpdateEnabled"), L("DisplayName:Abp.Identity.User.IsEmailUpdateEnabled"),
L("Description:Abp.Identity.User.IsEmailUpdateEnabled"), L("Description:Abp.Identity.User.IsEmailUpdateEnabled"),
true), true),
new SettingDefinition( new SettingDefinition(
IdentitySettingNames.OrganizationUnit.MaxUserMembershipCount, IdentitySettingNames.OrganizationUnit.MaxUserMembershipCount,
int.MaxValue.ToString(), int.MaxValue.ToString(),
L("Identity.OrganizationUnit.MaxUserMembershipCount"), L("Identity.OrganizationUnit.MaxUserMembershipCount"),
L("Identity.OrganizationUnit.MaxUserMembershipCount"), L("Identity.OrganizationUnit.MaxUserMembershipCount"),
true) true)
); );
} }
private static LocalizableString L(string name) private static LocalizableString L(string name)
{ {
return LocalizableString.Create<IdentityResource>(name); return LocalizableString.Create<IdentityResource>(name);
}
} }
} }

103
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.Security.Claims;
using Volo.Abp.Uow; using Volo.Abp.Uow;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public class AbpUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<IdentityUser, IdentityRole>,
ITransientDependency
{ {
public class AbpUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<IdentityUser, IdentityRole>, protected ICurrentPrincipalAccessor CurrentPrincipalAccessor { get; }
ITransientDependency protected IAbpClaimsPrincipalFactory AbpClaimsPrincipalFactory { get; }
public AbpUserClaimsPrincipalFactory(
UserManager<IdentityUser> userManager,
RoleManager<IdentityRole> roleManager,
IOptions<IdentityOptions> options,
ICurrentPrincipalAccessor currentPrincipalAccessor,
IAbpClaimsPrincipalFactory abpClaimsPrincipalFactory)
: base(
userManager,
roleManager,
options)
{
CurrentPrincipalAccessor = currentPrincipalAccessor;
AbpClaimsPrincipalFactory = abpClaimsPrincipalFactory;
}
[UnitOfWork]
public override async Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
{ {
protected ICurrentPrincipalAccessor CurrentPrincipalAccessor { get; } var principal = await base.CreateAsync(user);
protected IAbpClaimsPrincipalFactory AbpClaimsPrincipalFactory { get; } var identity = principal.Identities.First();
public AbpUserClaimsPrincipalFactory( if (user.TenantId.HasValue)
UserManager<IdentityUser> userManager,
RoleManager<IdentityRole> roleManager,
IOptions<IdentityOptions> options,
ICurrentPrincipalAccessor currentPrincipalAccessor,
IAbpClaimsPrincipalFactory abpClaimsPrincipalFactory)
: base(
userManager,
roleManager,
options)
{ {
CurrentPrincipalAccessor = currentPrincipalAccessor; identity.AddIfNotContains(new Claim(AbpClaimTypes.TenantId, user.TenantId.ToString()));
AbpClaimsPrincipalFactory = abpClaimsPrincipalFactory;
} }
[UnitOfWork] if (!user.Name.IsNullOrWhiteSpace())
public override async Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
{ {
var principal = await base.CreateAsync(user); identity.AddIfNotContains(new Claim(AbpClaimTypes.Name, user.Name));
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));
}
if (!user.PhoneNumber.IsNullOrWhiteSpace()) if (!user.Surname.IsNullOrWhiteSpace())
{ {
identity.AddIfNotContains(new Claim(AbpClaimTypes.PhoneNumber, user.PhoneNumber)); identity.AddIfNotContains(new Claim(AbpClaimTypes.SurName, user.Surname));
} }
identity.AddIfNotContains( if (!user.PhoneNumber.IsNullOrWhiteSpace())
new Claim(AbpClaimTypes.PhoneNumberVerified, user.PhoneNumberConfirmed.ToString())); {
identity.AddIfNotContains(new Claim(AbpClaimTypes.PhoneNumber, user.PhoneNumber));
}
if (!user.Email.IsNullOrWhiteSpace()) identity.AddIfNotContains(
{ new Claim(AbpClaimTypes.PhoneNumberVerified, user.PhoneNumberConfirmed.ToString()));
identity.AddIfNotContains(new Claim(AbpClaimTypes.Email, user.Email));
}
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)) identity.AddIfNotContains(new Claim(AbpClaimTypes.EmailVerified, user.EmailConfirmed.ToString()));
{
await AbpClaimsPrincipalFactory.CreateAsync(principal);
}
return principal; using (CurrentPrincipalAccessor.Change(identity))
{
await AbpClaimsPrincipalFactory.CreateAsync(principal);
} }
return principal;
} }
} }

231
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.Guids;
using Volo.Abp.MultiTenancy; 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> IdentityOptions { get; }
protected ExternalLoginProviderBase(
IGuidGenerator guidGenerator,
ICurrentTenant currentTenant,
IdentityUserManager userManager,
IIdentityUserRepository identityUserRepository,
IOptions<IdentityOptions> identityOptions)
{ {
protected IGuidGenerator GuidGenerator { get; } GuidGenerator = guidGenerator;
protected ICurrentTenant CurrentTenant { get; } CurrentTenant = currentTenant;
protected IdentityUserManager UserManager { get; } UserManager = userManager;
protected IIdentityUserRepository IdentityUserRepository { get; } IdentityUserRepository = identityUserRepository;
protected IOptions<IdentityOptions> IdentityOptions { get; } IdentityOptions = identityOptions;
}
protected ExternalLoginProviderBase(
IGuidGenerator guidGenerator,
ICurrentTenant currentTenant,
IdentityUserManager userManager,
IIdentityUserRepository identityUserRepository,
IOptions<IdentityOptions> identityOptions)
{
GuidGenerator = guidGenerator;
CurrentTenant = currentTenant;
UserManager = userManager;
IdentityUserRepository = identityUserRepository;
IdentityOptions = identityOptions;
}
public abstract Task<bool> TryAuthenticateAsync(string userName, string plainPassword); public abstract Task<bool> TryAuthenticateAsync(string userName, string plainPassword);
public virtual async Task<IdentityUser> CreateUserAsync(string userName, string providerName) public virtual async Task<IdentityUser> CreateUserAsync(string userName, string providerName)
{ {
await IdentityOptions.SetAsync(); await IdentityOptions.SetAsync();
var externalUser = await GetUserInfoAsync(userName); var externalUser = await GetUserInfoAsync(userName);
NormalizeExternalLoginUserInfo(externalUser, userName); NormalizeExternalLoginUserInfo(externalUser, userName);
var user = new IdentityUser( var user = new IdentityUser(
GuidGenerator.Create(), GuidGenerator.Create(),
userName, userName,
externalUser.Email, externalUser.Email,
tenantId: CurrentTenant.Id tenantId: CurrentTenant.Id
); );
user.Name = externalUser.Name; user.Name = externalUser.Name;
user.Surname = externalUser.Surname; user.Surname = externalUser.Surname;
user.IsExternal = true; user.IsExternal = true;
user.SetEmailConfirmed(externalUser.EmailConfirmed ?? false); user.SetEmailConfirmed(externalUser.EmailConfirmed ?? false);
user.SetPhoneNumber(externalUser.PhoneNumber, externalUser.PhoneNumberConfirmed ?? false); user.SetPhoneNumber(externalUser.PhoneNumber, externalUser.PhoneNumberConfirmed ?? false);
(await UserManager.CreateAsync(user)).CheckErrors(); (await UserManager.CreateAsync(user)).CheckErrors();
if (externalUser.TwoFactorEnabled != null) if (externalUser.TwoFactorEnabled != null)
{ {
(await UserManager.SetTwoFactorEnabledAsync(user, externalUser.TwoFactorEnabled.Value)).CheckErrors(); (await UserManager.SetTwoFactorEnabledAsync(user, externalUser.TwoFactorEnabled.Value)).CheckErrors();
} }
(await UserManager.AddDefaultRolesAsync(user)).CheckErrors(); (await UserManager.AddDefaultRolesAsync(user)).CheckErrors();
(await UserManager.AddLoginAsync( (await UserManager.AddLoginAsync(
user, user,
new UserLoginInfo( new UserLoginInfo(
providerName, providerName,
externalUser.ProviderKey , externalUser.ProviderKey,
providerName providerName
)
) )
).CheckErrors(); )
).CheckErrors();
return user; return user;
} }
public virtual async Task UpdateUserAsync(IdentityUser user, string providerName) public virtual async Task UpdateUserAsync(IdentityUser user, string providerName)
{ {
await IdentityOptions.SetAsync(); await IdentityOptions.SetAsync();
var externalUser = await GetUserInfoAsync(user); var externalUser = await GetUserInfoAsync(user);
NormalizeExternalLoginUserInfo(externalUser, user.UserName); NormalizeExternalLoginUserInfo(externalUser, user.UserName);
if (!externalUser.Name.IsNullOrWhiteSpace()) if (!externalUser.Name.IsNullOrWhiteSpace())
{ {
user.Name = externalUser.Name; user.Name = externalUser.Name;
} }
if (!externalUser.Surname.IsNullOrWhiteSpace()) if (!externalUser.Surname.IsNullOrWhiteSpace())
{ {
user.Surname = externalUser.Surname; 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.SetPhoneNumberConfirmed(true);
user.PhoneNumberConfirmed == false &&
externalUser.PhoneNumberConfirmed == true)
{
user.SetPhoneNumberConfirmed(true);
}
} }
}
if (!string.Equals(user.Email, externalUser.Email, StringComparison.OrdinalIgnoreCase)) if (!string.Equals(user.Email, externalUser.Email, StringComparison.OrdinalIgnoreCase))
{ {
(await UserManager.SetEmailAsync(user, externalUser.Email)).CheckErrors(); (await UserManager.SetEmailAsync(user, externalUser.Email)).CheckErrors();
user.SetEmailConfirmed(externalUser.EmailConfirmed ?? false); user.SetEmailConfirmed(externalUser.EmailConfirmed ?? false);
} }
if (externalUser.TwoFactorEnabled != null) if (externalUser.TwoFactorEnabled != null)
{ {
(await UserManager.SetTwoFactorEnabledAsync(user, externalUser.TwoFactorEnabled.Value)).CheckErrors(); (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); var userLogin = user.Logins.FirstOrDefault(l => l.LoginProvider == providerName);
if (userLogin != null) if (userLogin != null)
{ {
if (userLogin.ProviderKey != externalUser.ProviderKey) 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.RemoveLoginAsync(user, providerName, userLogin.ProviderKey)).CheckErrors();
(await UserManager.AddLoginAsync(user, new UserLoginInfo(providerName, externalUser.ProviderKey, providerName))).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<ExternalLoginUserInfo> GetUserInfoAsync(string userName); protected abstract Task<ExternalLoginUserInfo> GetUserInfoAsync(string userName);
protected virtual Task<ExternalLoginUserInfo> GetUserInfoAsync(IdentityUser user) protected virtual Task<ExternalLoginUserInfo> GetUserInfoAsync(IdentityUser user)
{ {
return GetUserInfoAsync(user.UserName); return GetUserInfoAsync(user.UserName);
} }
private static void NormalizeExternalLoginUserInfo( private static void NormalizeExternalLoginUserInfo(
ExternalLoginUserInfo externalUser, ExternalLoginUserInfo externalUser,
string userName string userName
) )
{
if (externalUser.ProviderKey.IsNullOrWhiteSpace())
{ {
if (externalUser.ProviderKey.IsNullOrWhiteSpace()) externalUser.ProviderKey = userName;
{
externalUser.ProviderKey = userName;
}
} }
} }
} }

19
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderDictionary.cs

@ -1,17 +1,16 @@
using System.Collections.Generic; using System.Collections.Generic;
using JetBrains.Annotations; using JetBrains.Annotations;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public class ExternalLoginProviderDictionary : Dictionary<string, ExternalLoginProviderInfo>
{ {
public class ExternalLoginProviderDictionary : Dictionary<string, ExternalLoginProviderInfo> /// <summary>
/// Adds or replaces a provider.
/// </summary>
public void Add<TProvider>([NotNull] string name)
where TProvider : IExternalLoginProvider
{ {
/// <summary> this[name] = new ExternalLoginProviderInfo(name, typeof(TProvider));
/// Adds or replaces a provider.
/// </summary>
public void Add<TProvider>([NotNull] string name)
where TProvider : IExternalLoginProvider
{
this[name] = new ExternalLoginProviderInfo(name, typeof(TProvider));
}
} }
} }

32
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginProviderInfo.cs

@ -1,25 +1,23 @@
using System; using System;
using JetBrains.Annotations; 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 public Type Type {
{ get => _type;
get => _type; set => _type = Check.NotNull(value, nameof(value));
set => _type = Check.NotNull(value, nameof(value)); }
} private Type _type;
private Type _type;
public ExternalLoginProviderInfo( public ExternalLoginProviderInfo(
[NotNull] string name, [NotNull] string name,
[NotNull] Type type) [NotNull] Type type)
{ {
Name = Check.NotNullOrWhiteSpace(name, nameof(name)); Name = Check.NotNullOrWhiteSpace(name, nameof(name));
Type = Check.AssignableTo<IExternalLoginProvider>(type, nameof(type)); Type = Check.AssignableTo<IExternalLoginProvider>(type, nameof(type));
}
} }
} }

45
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/ExternalLoginUserInfo.cs

@ -1,36 +1,35 @@
using JetBrains.Annotations; 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] [CanBeNull]
public string Surname { get; set; } public string Surname { get; set; }
[CanBeNull] [CanBeNull]
public string PhoneNumber { get; set; } public string PhoneNumber { get; set; }
[NotNull] [NotNull]
public string Email { get; private set; } public string Email { get; private set; }
[CanBeNull] [CanBeNull]
public bool? PhoneNumberConfirmed { get; set; } public bool? PhoneNumberConfirmed { get; set; }
[CanBeNull] [CanBeNull]
public bool? EmailConfirmed { get; set; } public bool? EmailConfirmed { get; set; }
[CanBeNull] [CanBeNull]
public bool? TwoFactorEnabled { get; set; } public bool? TwoFactorEnabled { get; set; }
[CanBeNull] [CanBeNull]
public string ProviderKey { get; set; } public string ProviderKey { get; set; }
public ExternalLoginUserInfo([NotNull] string email) public ExternalLoginUserInfo([NotNull] string email)
{ {
Email = Check.NotNullOrWhiteSpace(email, nameof(email)); Email = Check.NotNullOrWhiteSpace(email, nameof(email));
}
} }
} }

51
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IExternalLoginProvider.cs

@ -1,32 +1,31 @@
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public interface IExternalLoginProvider
{ {
public interface IExternalLoginProvider /// <summary>
{ /// Used to try authenticate a user by this source.
/// <summary> /// </summary>
/// Used to try authenticate a user by this source. /// <param name="userName">User name or email address</param>
/// </summary> /// <param name="plainPassword">Plain password of the user</param>
/// <param name="userName">User name or email address</param> /// <returns>True, indicates that this used has authenticated by this source</returns>
/// <param name="plainPassword">Plain password of the user</param> Task<bool> TryAuthenticateAsync(string userName, string plainPassword);
/// <returns>True, indicates that this used has authenticated by this source</returns>
Task<bool> TryAuthenticateAsync(string userName, string plainPassword);
/// <summary> /// <summary>
/// This method is called when a user is authenticated by this source but the user does not exists yet. /// 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. /// So, the source should create the user and fill the properties.
/// </summary> /// </summary>
/// <param name="userName">User name</param> /// <param name="userName">User name</param>
/// <param name="providerName">The name of this provider</param> /// <param name="providerName">The name of this provider</param>
/// <returns>Newly created user</returns> /// <returns>Newly created user</returns>
Task<IdentityUser> CreateUserAsync(string userName, string providerName); Task<IdentityUser> CreateUserAsync(string userName, string providerName);
/// <summary> /// <summary>
/// This method is called after an existing user is authenticated by this source. /// 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. /// It can be used to update some properties of the user by the source.
/// </summary> /// </summary>
/// <param name="providerName">The name of this provider</param> /// <param name="providerName">The name of this provider</param>
/// <param name="user">The user that can be updated</param> /// <param name="user">The user that can be updated</param>
Task UpdateUserAsync(IdentityUser user, string providerName); Task UpdateUserAsync(IdentityUser user, string providerName);
}
} }

59
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIDentityClaimTypeRepository.cs

@ -4,36 +4,35 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories; using Volo.Abp.Domain.Repositories;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public interface IIdentityClaimTypeRepository : IBasicRepository<IdentityClaimType, Guid>
{ {
public interface IIdentityClaimTypeRepository : IBasicRepository<IdentityClaimType, Guid> /// <summary>
{ /// Checks if there is a <see cref="IdentityClaimType"/> entity with given name.
/// <summary> /// </summary>
/// Checks if there is a <see cref="IdentityClaimType"/> entity with given name. /// <param name="name">Name to check</param>
/// </summary> /// <param name="ignoredId">
/// <param name="name">Name to check</param> /// An Id value to ignore on checking.
/// <param name="ignoredId"> /// If there is an entity with given <paramref name="ignoredId"/> it's ignored.
/// An Id value to ignore on checking. /// </param>
/// If there is an entity with given <paramref name="ignoredId"/> it's ignored. /// <param name="cancellationToken">Cancel token</param>
/// </param> Task<bool> AnyAsync(
/// <param name="cancellationToken">Cancel token</param> string name,
Task<bool> AnyAsync( Guid? ignoredId = null,
string name, CancellationToken cancellationToken = default
Guid? ignoredId = null, );
CancellationToken cancellationToken = default
);
Task<List<IdentityClaimType>> GetListAsync( Task<List<IdentityClaimType>> GetListAsync(
string sorting, string sorting,
int maxResultCount, int maxResultCount,
int skipCount, int skipCount,
string filter, string filter,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
Task<long> GetCountAsync( Task<long> GetCountAsync(
string filter = null, string filter = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
} }
}

17
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityDataSeeder.cs

@ -2,13 +2,12 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public interface IIdentityDataSeeder
{ {
public interface IIdentityDataSeeder Task<IdentityDataSeedResult> SeedAsync(
{ [NotNull] string adminEmail,
Task<IdentityDataSeedResult> SeedAsync( [NotNull] string adminPassword,
[NotNull] string adminEmail, Guid? tenantId = null);
[NotNull] string adminPassword, }
Guid? tenantId = null);
}
}

29
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityLinkUserRepository.cs

@ -4,22 +4,21 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories; using Volo.Abp.Domain.Repositories;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public interface IIdentityLinkUserRepository : IBasicRepository<IdentityLinkUser, Guid>
{ {
public interface IIdentityLinkUserRepository : IBasicRepository<IdentityLinkUser, Guid> Task<IdentityLinkUser> FindAsync(
{ IdentityLinkUserInfo sourceLinkUserInfo,
Task<IdentityLinkUser> FindAsync( IdentityLinkUserInfo targetLinkUserInfo,
IdentityLinkUserInfo sourceLinkUserInfo, CancellationToken cancellationToken = default);
IdentityLinkUserInfo targetLinkUserInfo,
CancellationToken cancellationToken = default);
Task<List<IdentityLinkUser>> GetListAsync( Task<List<IdentityLinkUser>> GetListAsync(
IdentityLinkUserInfo linkUserInfo, IdentityLinkUserInfo linkUserInfo,
List<IdentityLinkUserInfo> excludes = null, List<IdentityLinkUserInfo> excludes = null,
CancellationToken cancellationToken = default); CancellationToken cancellationToken = default);
Task DeleteAsync( Task DeleteAsync(
IdentityLinkUserInfo linkUserInfo, IdentityLinkUserInfo linkUserInfo,
CancellationToken cancellationToken = default); CancellationToken cancellationToken = default);
}
} }

59
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityRoleRepository.cs

@ -4,37 +4,36 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories; using Volo.Abp.Domain.Repositories;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public interface IIdentityRoleRepository : IBasicRepository<IdentityRole, Guid>
{ {
public interface IIdentityRoleRepository : IBasicRepository<IdentityRole, Guid> Task<IdentityRole> FindByNormalizedNameAsync(
{ string normalizedRoleName,
Task<IdentityRole> FindByNormalizedNameAsync( bool includeDetails = true,
string normalizedRoleName, CancellationToken cancellationToken = default
bool includeDetails = true, );
CancellationToken cancellationToken = default
);
Task<List<IdentityRole>> GetListAsync( Task<List<IdentityRole>> GetListAsync(
string sorting = null, string sorting = null,
int maxResultCount = int.MaxValue, int maxResultCount = int.MaxValue,
int skipCount = 0, int skipCount = 0,
string filter = null, string filter = null,
bool includeDetails = false, bool includeDetails = false,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
Task<List<IdentityRole>> GetListAsync( Task<List<IdentityRole>> GetListAsync(
IEnumerable<Guid> ids, IEnumerable<Guid> ids,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
Task<List<IdentityRole>> GetDefaultOnesAsync( Task<List<IdentityRole>> GetDefaultOnesAsync(
bool includeDetails = false, bool includeDetails = false,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
Task<long> GetCountAsync( Task<long> GetCountAsync(
string filter = null, string filter = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
} }
}

69
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentitySecurityLogRepository.cs

@ -4,42 +4,41 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories; using Volo.Abp.Domain.Repositories;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public interface IIdentitySecurityLogRepository : IBasicRepository<IdentitySecurityLog, Guid>
{ {
public interface IIdentitySecurityLogRepository : IBasicRepository<IdentitySecurityLog, Guid> Task<List<IdentitySecurityLog>> GetListAsync(
{ string sorting = null,
Task<List<IdentitySecurityLog>> GetListAsync( int maxResultCount = 50,
string sorting = null, int skipCount = 0,
int maxResultCount = 50, DateTime? startTime = null,
int skipCount = 0, DateTime? endTime = null,
DateTime? startTime = null, string applicationName = null,
DateTime? endTime = null, string identity = null,
string applicationName = null, string action = null,
string identity = null, Guid? userId = null,
string action = null, string userName = null,
Guid? userId = null, string clientId = null,
string userName = null, string correlationId = null,
string clientId = null, bool includeDetails = false,
string correlationId = null, CancellationToken cancellationToken = default);
bool includeDetails = false,
CancellationToken cancellationToken = default);
Task<long> GetCountAsync( Task<long> GetCountAsync(
DateTime? startTime = null, DateTime? startTime = null,
DateTime? endTime = null, DateTime? endTime = null,
string applicationName = null, string applicationName = null,
string identity = null, string identity = null,
string action = null, string action = null,
Guid? userId = null, Guid? userId = null,
string userName = null, string userName = null,
string clientId = null, string clientId = null,
string correlationId = null, string correlationId = null,
CancellationToken cancellationToken = default); CancellationToken cancellationToken = default);
Task<IdentitySecurityLog> GetByUserIdAsync( Task<IdentitySecurityLog> GetByUserIdAsync(
Guid id, Guid id,
Guid userId, Guid userId,
bool includeDetails = false, bool includeDetails = false,
CancellationToken cancellationToken = default); CancellationToken cancellationToken = default);
}
} }

167
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityUserRepository.cs

@ -6,101 +6,100 @@ using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
using Volo.Abp.Domain.Repositories; using Volo.Abp.Domain.Repositories;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public interface IIdentityUserRepository : IBasicRepository<IdentityUser, Guid>
{ {
public interface IIdentityUserRepository : IBasicRepository<IdentityUser, Guid> Task<IdentityUser> FindByNormalizedUserNameAsync(
{ [NotNull] string normalizedUserName,
Task<IdentityUser> FindByNormalizedUserNameAsync( bool includeDetails = true,
[NotNull] string normalizedUserName, CancellationToken cancellationToken = default
bool includeDetails = true, );
CancellationToken cancellationToken = default
);
Task<List<string>> GetRoleNamesAsync( Task<List<string>> GetRoleNamesAsync(
Guid id, Guid id,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
Task<List<string>> GetRoleNamesInOrganizationUnitAsync( Task<List<string>> GetRoleNamesInOrganizationUnitAsync(
Guid id, Guid id,
CancellationToken cancellationToken = default); CancellationToken cancellationToken = default);
Task<IdentityUser> FindByLoginAsync( Task<IdentityUser> FindByLoginAsync(
[NotNull] string loginProvider, [NotNull] string loginProvider,
[NotNull] string providerKey, [NotNull] string providerKey,
bool includeDetails = true, bool includeDetails = true,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
Task<IdentityUser> FindByNormalizedEmailAsync( Task<IdentityUser> FindByNormalizedEmailAsync(
[NotNull] string normalizedEmail, [NotNull] string normalizedEmail,
bool includeDetails = true, bool includeDetails = true,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
Task<List<IdentityUser>> GetListByClaimAsync( Task<List<IdentityUser>> GetListByClaimAsync(
Claim claim, Claim claim,
bool includeDetails = false, bool includeDetails = false,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
Task<List<IdentityUser>> GetListByNormalizedRoleNameAsync( Task<List<IdentityUser>> GetListByNormalizedRoleNameAsync(
string normalizedRoleName, string normalizedRoleName,
bool includeDetails = false, bool includeDetails = false,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
Task<List<IdentityUser>> GetListAsync( Task<List<IdentityUser>> GetListAsync(
string sorting = null, string sorting = null,
int maxResultCount = int.MaxValue, int maxResultCount = int.MaxValue,
int skipCount = 0, int skipCount = 0,
string filter = null, string filter = null,
bool includeDetails = false, bool includeDetails = false,
Guid? roleId = null, Guid? roleId = null,
Guid? organizationUnitId = null, Guid? organizationUnitId = null,
string userName = null, string userName = null,
string phoneNumber = null, string phoneNumber = null,
string emailAddress = null, string emailAddress = null,
bool? isLockedOut = null, bool? isLockedOut = null,
bool? notActive = null, bool? notActive = null,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
Task<List<IdentityRole>> GetRolesAsync(
Guid id,
bool includeDetails = false,
CancellationToken cancellationToken = default
);
Task<List<OrganizationUnit>> GetOrganizationUnitsAsync( Task<List<IdentityRole>> GetRolesAsync(
Guid id, Guid id,
bool includeDetails = false, bool includeDetails = false,
CancellationToken cancellationToken = default); CancellationToken cancellationToken = default
);
Task<List<IdentityUser>> GetUsersInOrganizationUnitAsync( Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(
Guid organizationUnitId, Guid id,
CancellationToken cancellationToken = default bool includeDetails = false,
); CancellationToken cancellationToken = default);
Task<List<IdentityUser>> GetUsersInOrganizationsListAsync(
List<Guid> organizationUnitIds,
CancellationToken cancellationToken = default
);
Task<List<IdentityUser>> GetUsersInOrganizationUnitWithChildrenAsync( Task<List<IdentityUser>> GetUsersInOrganizationUnitAsync(
string code, Guid organizationUnitId,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
Task<List<IdentityUser>> GetUsersInOrganizationsListAsync(
List<Guid> organizationUnitIds,
CancellationToken cancellationToken = default
);
Task<long> GetCountAsync( Task<List<IdentityUser>> GetUsersInOrganizationUnitWithChildrenAsync(
string filter = null, string code,
Guid? roleId = null, CancellationToken cancellationToken = default
Guid? organizationUnitId = null,
string userName = null,
string phoneNumber = null,
string emailAddress = null,
bool? isLockedOut = null,
bool? notActive = null,
CancellationToken cancellationToken = default
); );
}
Task<long> 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
);
} }

215
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IOrganizationUnitRepository.cs

@ -4,113 +4,112 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories; using Volo.Abp.Domain.Repositories;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public interface IOrganizationUnitRepository : IBasicRepository<OrganizationUnit, Guid>
{ {
public interface IOrganizationUnitRepository : IBasicRepository<OrganizationUnit, Guid> Task<List<OrganizationUnit>> GetChildrenAsync(
{ Guid? parentId,
Task<List<OrganizationUnit>> GetChildrenAsync( bool includeDetails = false,
Guid? parentId, CancellationToken cancellationToken = default
bool includeDetails = false, );
CancellationToken cancellationToken = default
); Task<List<OrganizationUnit>> GetAllChildrenWithParentCodeAsync(
string code,
Task<List<OrganizationUnit>> GetAllChildrenWithParentCodeAsync( Guid? parentId,
string code, bool includeDetails = false,
Guid? parentId, CancellationToken cancellationToken = default
bool includeDetails = false, );
CancellationToken cancellationToken = default
); Task<OrganizationUnit> GetAsync(
string displayName,
Task<OrganizationUnit> GetAsync( bool includeDetails = true,
string displayName, CancellationToken cancellationToken = default
bool includeDetails = true, );
CancellationToken cancellationToken = default
); Task<List<OrganizationUnit>> GetListAsync(
string sorting = null,
Task<List<OrganizationUnit>> GetListAsync( int maxResultCount = int.MaxValue,
string sorting = null, int skipCount = 0,
int maxResultCount = int.MaxValue, bool includeDetails = false,
int skipCount = 0, CancellationToken cancellationToken = default
bool includeDetails = false, );
CancellationToken cancellationToken = default
); Task<List<OrganizationUnit>> GetListAsync(
IEnumerable<Guid> ids,
Task<List<OrganizationUnit>> GetListAsync( bool includeDetails = false,
IEnumerable<Guid> ids, CancellationToken cancellationToken = default
bool includeDetails = false, );
CancellationToken cancellationToken = default
); Task<List<IdentityRole>> GetRolesAsync(
OrganizationUnit organizationUnit,
Task<List<IdentityRole>> GetRolesAsync( string sorting = null,
OrganizationUnit organizationUnit, int maxResultCount = int.MaxValue,
string sorting = null, int skipCount = 0,
int maxResultCount = int.MaxValue, bool includeDetails = false,
int skipCount = 0, CancellationToken cancellationToken = default
bool includeDetails = false, );
CancellationToken cancellationToken = default
); Task<int> GetRolesCountAsync(
OrganizationUnit organizationUnit,
Task<int> GetRolesCountAsync( CancellationToken cancellationToken = default
OrganizationUnit organizationUnit, );
CancellationToken cancellationToken = default
); Task<List<IdentityRole>> GetUnaddedRolesAsync(
OrganizationUnit organizationUnit,
Task<List<IdentityRole>> GetUnaddedRolesAsync( string sorting = null,
OrganizationUnit organizationUnit, int maxResultCount = int.MaxValue,
string sorting = null, int skipCount = 0,
int maxResultCount = int.MaxValue, string filter = null,
int skipCount = 0, bool includeDetails = false,
string filter = null, CancellationToken cancellationToken = default
bool includeDetails = false, );
CancellationToken cancellationToken = default
); Task<int> GetUnaddedRolesCountAsync(
OrganizationUnit organizationUnit,
Task<int> GetUnaddedRolesCountAsync( string filter = null,
OrganizationUnit organizationUnit, CancellationToken cancellationToken = default
string filter = null, );
CancellationToken cancellationToken = default
); Task<List<IdentityUser>> GetMembersAsync(
OrganizationUnit organizationUnit,
Task<List<IdentityUser>> GetMembersAsync( string sorting = null,
OrganizationUnit organizationUnit, int maxResultCount = int.MaxValue,
string sorting = null, int skipCount = 0,
int maxResultCount = int.MaxValue, string filter = null,
int skipCount = 0, bool includeDetails = false,
string filter = null, CancellationToken cancellationToken = default
bool includeDetails = false, );
CancellationToken cancellationToken = default
); Task<int> GetMembersCountAsync(
OrganizationUnit organizationUnit,
Task<int> GetMembersCountAsync( string filter = null,
OrganizationUnit organizationUnit, CancellationToken cancellationToken = default
string filter = null, );
CancellationToken cancellationToken = default
); Task<List<IdentityUser>> GetUnaddedUsersAsync(
OrganizationUnit organizationUnit,
Task<List<IdentityUser>> GetUnaddedUsersAsync( string sorting = null,
OrganizationUnit organizationUnit, int maxResultCount = int.MaxValue,
string sorting = null, int skipCount = 0,
int maxResultCount = int.MaxValue, string filter = null,
int skipCount = 0, bool includeDetails = false,
string filter = null, CancellationToken cancellationToken = default
bool includeDetails = false, );
CancellationToken cancellationToken = default
); Task<int> GetUnaddedUsersCountAsync(
OrganizationUnit organizationUnit,
Task<int> GetUnaddedUsersCountAsync( string filter = null,
OrganizationUnit organizationUnit, CancellationToken cancellationToken = default
string filter = null, );
CancellationToken cancellationToken = default
); Task RemoveAllRolesAsync(
OrganizationUnit organizationUnit,
Task RemoveAllRolesAsync( CancellationToken cancellationToken = default
OrganizationUnit organizationUnit, );
CancellationToken cancellationToken = default
); Task RemoveAllMembersAsync(
OrganizationUnit organizationUnit,
Task RemoveAllMembersAsync( CancellationToken cancellationToken = default
OrganizationUnit organizationUnit, );
CancellationToken cancellationToken = default
);
}
} }

101
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.Domain.Entities;
using Volo.Abp.MultiTenancy; using Volo.Abp.MultiTenancy;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public abstract class IdentityClaim : Entity<Guid>, IMultiTenant
{ {
public abstract class IdentityClaim : Entity<Guid>, IMultiTenant public virtual Guid? TenantId { get; protected set; }
/// <summary>
/// Gets or sets the claim type for this claim.
/// </summary>
public virtual string ClaimType { get; protected set; }
/// <summary>
/// Gets or sets the claim value for this claim.
/// </summary>
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;
}
/// <summary>
/// Creates a Claim instance from this entity.
/// </summary>
/// <returns></returns>
public virtual Claim ToClaim()
{ {
public virtual Guid? TenantId { get; protected set; } return new Claim(ClaimType, ClaimValue);
}
/// <summary>
/// Gets or sets the claim type for this claim. public virtual void SetClaim([NotNull] Claim claim)
/// </summary> {
public virtual string ClaimType { get; protected set; } Check.NotNull(claim, nameof(claim));
/// <summary> ClaimType = claim.Type;
/// Gets or sets the claim value for this claim. ClaimValue = claim.Value;
/// </summary>
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;
}
/// <summary>
/// Creates a Claim instance from this entity.
/// </summary>
/// <returns></returns>
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;
}
} }
} }

71
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimType.cs

@ -2,52 +2,51 @@
using System; using System;
using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Entities;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public class IdentityClaimType : AggregateRoot<Guid>
{ {
public class IdentityClaimType : AggregateRoot<Guid> 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( public IdentityClaimType(
Guid id, Guid id,
[NotNull] string name, [NotNull] string name,
bool required = false, bool required = false,
bool isStatic = false, bool isStatic = false,
[CanBeNull] string regex = null, [CanBeNull] string regex = null,
[CanBeNull] string regexDescription = null, [CanBeNull] string regexDescription = null,
[CanBeNull] string description = null, [CanBeNull] string description = null,
IdentityClaimValueType valueType = IdentityClaimValueType.String) IdentityClaimValueType valueType = IdentityClaimValueType.String)
{ {
Id = id; Id = id;
SetName(name); SetName(name);
Required = required; Required = required;
IsStatic = isStatic; IsStatic = isStatic;
Regex = regex; Regex = regex;
RegexDescription = regexDescription; RegexDescription = regexDescription;
Description = description; Description = description;
ValueType = valueType; ValueType = valueType;
} }
public void SetName([NotNull] string name) public void SetName([NotNull] string name)
{ {
Name = Check.NotNull(name, nameof(name)); Name = Check.NotNull(name, nameof(name));
}
} }
} }

49
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityClaimTypeManager.cs

@ -1,41 +1,40 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Volo.Abp.Domain.Services; 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<IdentityClaimType> CreateAsync(IdentityClaimType claimType)
{
if (await IdentityClaimTypeRepository.AnyAsync(claimType.Name))
{ {
IdentityClaimTypeRepository = identityClaimTypeRepository; throw new AbpException($"Name Exist: {claimType.Name}");
} }
public virtual async Task<IdentityClaimType> CreateAsync(IdentityClaimType claimType) return await IdentityClaimTypeRepository.InsertAsync(claimType);
{ }
if (await IdentityClaimTypeRepository.AnyAsync(claimType.Name))
{
throw new AbpException($"Name Exist: {claimType.Name}");
}
return await IdentityClaimTypeRepository.InsertAsync(claimType); public virtual async Task<IdentityClaimType> UpdateAsync(IdentityClaimType claimType)
{
if (await IdentityClaimTypeRepository.AnyAsync(claimType.Name, claimType.Id))
{
throw new AbpException($"Name Exist: {claimType.Name}");
} }
public virtual async Task<IdentityClaimType> UpdateAsync(IdentityClaimType claimType) if (claimType.IsStatic)
{ {
if (await IdentityClaimTypeRepository.AnyAsync(claimType.Name, claimType.Id)) throw new AbpException($"Can not update a static ClaimType.");
{
throw new AbpException($"Name Exist: {claimType.Name}");
}
if (claimType.IsStatic)
{
throw new AbpException($"Can not update a static ClaimType.");
}
return await IdentityClaimTypeRepository.UpdateAsync(claimType);
} }
return await IdentityClaimTypeRepository.UpdateAsync(claimType);
} }
} }

39
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDataSeedContributor.cs

@ -2,29 +2,28 @@
using Volo.Abp.Data; using Volo.Abp.Data;
using Volo.Abp.DependencyInjection; 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 AdminEmailPropertyName = "AdminEmail"; public const string AdminPasswordPropertyName = "AdminPassword";
public const string AdminEmailDefaultValue = "admin@abp.io"; public const string AdminPasswordDefaultValue = "1q2w3E*";
public const string AdminPasswordPropertyName = "AdminPassword";
public const string AdminPasswordDefaultValue = "1q2w3E*";
protected IIdentityDataSeeder IdentityDataSeeder { get; } protected IIdentityDataSeeder IdentityDataSeeder { get; }
public IdentityDataSeedContributor(IIdentityDataSeeder identityDataSeeder) public IdentityDataSeedContributor(IIdentityDataSeeder identityDataSeeder)
{ {
IdentityDataSeeder = identityDataSeeder; IdentityDataSeeder = identityDataSeeder;
} }
public virtual Task SeedAsync(DataSeedContext context) public virtual Task SeedAsync(DataSeedContext context)
{ {
return IdentityDataSeeder.SeedAsync( return IdentityDataSeeder.SeedAsync(
context?[AdminEmailPropertyName] as string ?? AdminEmailDefaultValue, context?[AdminEmailPropertyName] as string ?? AdminEmailDefaultValue,
context?[AdminPasswordPropertyName] as string ?? AdminPasswordDefaultValue, context?[AdminPasswordPropertyName] as string ?? AdminPasswordDefaultValue,
context?.TenantId context?.TenantId
); );
}
} }
} }

13
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; } public bool CreatedAdminRole { get; set; }
} }
}

153
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.MultiTenancy;
using Volo.Abp.Uow; 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> IdentityOptions { get; }
public IdentityDataSeeder(
IGuidGenerator guidGenerator,
IIdentityRoleRepository roleRepository,
IIdentityUserRepository userRepository,
ILookupNormalizer lookupNormalizer,
IdentityUserManager userManager,
IdentityRoleManager roleManager,
ICurrentTenant currentTenant,
IOptions<IdentityOptions> identityOptions)
{ {
protected IGuidGenerator GuidGenerator { get; } GuidGenerator = guidGenerator;
protected IIdentityRoleRepository RoleRepository { get; } RoleRepository = roleRepository;
protected IIdentityUserRepository UserRepository { get; } UserRepository = userRepository;
protected ILookupNormalizer LookupNormalizer { get; } LookupNormalizer = lookupNormalizer;
protected IdentityUserManager UserManager { get; } UserManager = userManager;
protected IdentityRoleManager RoleManager { get; } RoleManager = roleManager;
protected ICurrentTenant CurrentTenant { get; } CurrentTenant = currentTenant;
protected IOptions<IdentityOptions> IdentityOptions { get; } IdentityOptions = identityOptions;
}
public IdentityDataSeeder( [UnitOfWork]
IGuidGenerator guidGenerator, public virtual async Task<IdentityDataSeedResult> SeedAsync(
IIdentityRoleRepository roleRepository, string adminEmail,
IIdentityUserRepository userRepository, string adminPassword,
ILookupNormalizer lookupNormalizer, Guid? tenantId = null)
IdentityUserManager userManager, {
IdentityRoleManager roleManager, Check.NotNullOrWhiteSpace(adminEmail, nameof(adminEmail));
ICurrentTenant currentTenant, Check.NotNullOrWhiteSpace(adminPassword, nameof(adminPassword));
IOptions<IdentityOptions> identityOptions)
{
GuidGenerator = guidGenerator;
RoleRepository = roleRepository;
UserRepository = userRepository;
LookupNormalizer = lookupNormalizer;
UserManager = userManager;
RoleManager = roleManager;
CurrentTenant = currentTenant;
IdentityOptions = identityOptions;
}
[UnitOfWork] using (CurrentTenant.Change(tenantId))
public virtual async Task<IdentityDataSeedResult> SeedAsync(
string adminEmail,
string adminPassword,
Guid? tenantId = null)
{ {
Check.NotNullOrWhiteSpace(adminEmail, nameof(adminEmail)); await IdentityOptions.SetAsync();
Check.NotNullOrWhiteSpace(adminPassword, nameof(adminPassword));
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(); adminUser = new IdentityUser(
//"admin" user GuidGenerator.Create(),
const string adminUserName = "admin"; adminUserName,
var adminUser = await UserRepository.FindByNormalizedUserNameAsync( adminEmail,
LookupNormalizer.NormalizeName(adminUserName) tenantId
); )
{
Name = adminUserName
};
if (adminUser != null) (await UserManager.CreateAsync(adminUser, adminPassword, validatePassword: false)).CheckErrors();
{ result.CreatedAdminUser = true;
return result;
}
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(), GuidGenerator.Create(),
adminUserName, adminRoleName,
adminEmail,
tenantId tenantId
) )
{ {
Name = adminUserName IsStatic = true,
IsPublic = true
}; };
(await UserManager.CreateAsync(adminUser, adminPassword, validatePassword: false)).CheckErrors(); (await RoleManager.CreateAsync(adminRole)).CheckErrors();
result.CreatedAdminUser = true; result.CreatedAdminRole = 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 UserManager.AddToRoleAsync(adminUser, adminRoleName)).CheckErrors(); (await UserManager.AddToRoleAsync(adminUser, adminRoleName)).CheckErrors();
return result; return result;
}
} }
} }
} }

19
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityDomainMappingProfile.cs

@ -1,16 +1,15 @@
using AutoMapper; using AutoMapper;
using Volo.Abp.Users; 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<IdentityUser, UserEto>();
{ CreateMap<IdentityClaimType, IdentityClaimTypeEto>();
CreateMap<IdentityUser, UserEto>(); CreateMap<IdentityRole, IdentityRoleEto>();
CreateMap<IdentityClaimType, IdentityClaimTypeEto>(); CreateMap<OrganizationUnit, OrganizationUnitEto>();
CreateMap<IdentityRole, IdentityRoleEto>();
CreateMap<OrganizationUnit, OrganizationUnitEto>();
}
} }
} }

57
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUser.cs

@ -1,44 +1,43 @@
using System; using System;
using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Entities;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
public class IdentityLinkUser : BasicAggregateRoot<Guid>
{ {
public class IdentityLinkUser : BasicAggregateRoot<Guid> 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; }
/// <summary> /// <summary>
/// Initializes a new instance of <see cref="IdentityLinkUser"/>. /// Initializes a new instance of <see cref="IdentityLinkUser"/>.
/// </summary> /// </summary>
protected IdentityLinkUser() protected IdentityLinkUser()
{ {
} }
public IdentityLinkUser(Guid id, IdentityLinkUserInfo sourceUser, IdentityLinkUserInfo targetUser) public IdentityLinkUser(Guid id, IdentityLinkUserInfo sourceUser, IdentityLinkUserInfo targetUser)
: base(id) : base(id)
{ {
SourceUserId = sourceUser.UserId; SourceUserId = sourceUser.UserId;
SourceTenantId = sourceUser.TenantId; SourceTenantId = sourceUser.TenantId;
TargetUserId = targetUser.UserId; TargetUserId = targetUser.UserId;
TargetTenantId = targetUser.TenantId; TargetTenantId = targetUser.TenantId;
} }
public IdentityLinkUser(Guid id, Guid sourceUserId, Guid? sourceTenantId, Guid targetUserId, Guid? targetTenantId) public IdentityLinkUser(Guid id, Guid sourceUserId, Guid? sourceTenantId, Guid targetUserId, Guid? targetTenantId)
: base(id) : base(id)
{ {
SourceUserId = sourceUserId; SourceUserId = sourceUserId;
SourceTenantId = sourceTenantId; SourceTenantId = sourceTenantId;
TargetUserId = targetUserId; TargetUserId = targetUserId;
TargetTenantId = targetTenantId; TargetTenantId = targetTenantId;
}
} }
} }

19
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserInfo.cs

@ -1,17 +1,16 @@
using System; 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) public IdentityLinkUserInfo(Guid userId, Guid? tenantId)
{ {
UserId = userId; UserId = userId;
TenantId = tenantId; TenantId = tenantId;
}
} }
} }

193
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.Domain.Services;
using Volo.Abp.MultiTenancy; 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) public IdentityLinkUserManager(IIdentityLinkUserRepository identityLinkUserRepository, IdentityUserManager userManager, ICurrentTenant currentTenant)
{ {
IdentityLinkUserRepository = identityLinkUserRepository; IdentityLinkUserRepository = identityLinkUserRepository;
UserManager = userManager; UserManager = userManager;
CurrentTenant = currentTenant; CurrentTenant = currentTenant;
} }
public async Task<List<IdentityLinkUser>> GetListAsync(IdentityLinkUserInfo linkUserInfo, bool includeIndirect = false, CancellationToken cancellationToken = default) public async Task<List<IdentityLinkUser>> 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); return users;
if (includeIndirect == false) }
{
return users;
}
var userInfos = new List<IdentityLinkUserInfo>() var userInfos = new List<IdentityLinkUserInfo>()
{ {
linkUserInfo linkUserInfo
}; };
var allUsers = new List<IdentityLinkUser>(); var allUsers = new List<IdentityLinkUser>();
allUsers.AddRange(users); allUsers.AddRange(users);
do do
{
var nextUsers = new List<IdentityLinkUserInfo>();
foreach (var user in users)
{ {
var nextUsers = new List<IdentityLinkUserInfo>(); if (userInfos.Any(x => x.TenantId != user.SourceTenantId || x.UserId != user.SourceUserId))
foreach (var user in users)
{ {
if (userInfos.Any(x => x.TenantId != user.SourceTenantId || x.UserId != user.SourceUserId)) nextUsers.Add(new IdentityLinkUserInfo(user.SourceUserId, user.SourceTenantId));
{
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));
}
} }
users = new List<IdentityLinkUser>(); if (userInfos.Any(x => x.TenantId != user.TargetTenantId || x.UserId != user.TargetUserId))
foreach (var next in nextUsers)
{ {
users.AddRange(await IdentityLinkUserRepository.GetListAsync(next, userInfos, cancellationToken)); nextUsers.Add(new IdentityLinkUserInfo(user.TargetUserId, user.TargetTenantId));
} }
}
users = new List<IdentityLinkUser>();
foreach (var next in nextUsers)
{
users.AddRange(await IdentityLinkUserRepository.GetListAsync(next, userInfos, cancellationToken));
}
userInfos.AddRange(nextUsers); userInfos.AddRange(nextUsers);
allUsers.AddRange(users); allUsers.AddRange(users);
} while (users.Any()); } 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;
{ }
return;
}
if (await IsLinkedAsync(sourceLinkUser, targetLinkUser, cancellationToken: cancellationToken))
{
return;
}
var userLink = new IdentityLinkUser( if (await IsLinkedAsync(sourceLinkUser, targetLinkUser, cancellationToken: cancellationToken))
GuidGenerator.Create(), {
sourceLinkUser, return;
targetLinkUser);
await IdentityLinkUserRepository.InsertAsync(userLink, true, cancellationToken);
} }
var userLink = new IdentityLinkUser(
GuidGenerator.Create(),
sourceLinkUser,
targetLinkUser);
await IdentityLinkUserRepository.InsertAsync(userLink, true, cancellationToken);
} }
}
public virtual async Task<bool> IsLinkedAsync(IdentityLinkUserInfo sourceLinkUser, IdentityLinkUserInfo targetLinkUser, bool includeIndirect = false, CancellationToken cancellationToken = default) public virtual async Task<bool> 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 ||
return (await GetListAsync(sourceLinkUser, true, cancellationToken: cancellationToken)) x.TargetTenantId == targetLinkUser.TenantId && x.TargetUserId == targetLinkUser.UserId);
.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 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); var linkedUser = await IdentityLinkUserRepository.FindAsync(sourceLinkUser, targetLinkUser, cancellationToken);
if (linkedUser != null) if (linkedUser != null)
{ {
await IdentityLinkUserRepository.DeleteAsync(linkedUser, cancellationToken: cancellationToken); await IdentityLinkUserRepository.DeleteAsync(linkedUser, cancellationToken: cancellationToken);
}
} }
} }
}
public virtual async Task<string> GenerateLinkTokenAsync(IdentityLinkUserInfo targetLinkUser, string tokenPurpose, CancellationToken cancellationToken = default) public virtual async Task<string> 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(
var user = await UserManager.GetByIdAsync(targetLinkUser.UserId); user,
return await UserManager.GenerateUserTokenAsync( LinkUserTokenProviderConsts.LinkUserTokenProviderName,
user, tokenPurpose);
LinkUserTokenProviderConsts.LinkUserTokenProviderName,
tokenPurpose);
}
} }
}
public virtual async Task<bool> VerifyLinkTokenAsync(IdentityLinkUserInfo targetLinkUser, string token, string tokenPurpose, CancellationToken cancellationToken = default) public virtual async Task<bool> 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(
var user = await UserManager.GetByIdAsync(targetLinkUser.UserId); user,
return await UserManager.VerifyUserTokenAsync( LinkUserTokenProviderConsts.LinkUserTokenProviderName,
user, tokenPurpose,
LinkUserTokenProviderConsts.LinkUserTokenProviderName, token);
tokenPurpose,
token);
}
} }
} }
} }

191
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.Guids;
using Volo.Abp.MultiTenancy; using Volo.Abp.MultiTenancy;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
/// <summary>
/// Represents a role in the identity system
/// </summary>
public class IdentityRole : AggregateRoot<Guid>, IMultiTenant
{ {
public virtual Guid? TenantId { get; protected set; }
/// <summary>
/// Gets or sets the name for this role.
/// </summary>
public virtual string Name { get; protected internal set; }
/// <summary>
/// Gets or sets the normalized name for this role.
/// </summary>
[DisableAuditing]
public virtual string NormalizedName { get; protected internal set; }
/// <summary>
/// Navigation property for claims in this role.
/// </summary>
public virtual ICollection<IdentityRoleClaim> Claims { get; protected set; }
/// <summary>
/// A default role is automatically assigned to a new user
/// </summary>
public virtual bool IsDefault { get; set; }
/// <summary> /// <summary>
/// Represents a role in the identity system /// A static role can not be deleted/renamed
/// </summary> /// </summary>
public class IdentityRole : AggregateRoot<Guid>, IMultiTenant public virtual bool IsStatic { get; set; }
/// <summary>
/// A user can see other user's public roles
/// </summary>
public virtual bool IsPublic { get; set; }
/// <summary>
/// Initializes a new instance of <see cref="IdentityRole"/>.
/// </summary>
protected IdentityRole() { }
public IdentityRole(Guid id, [NotNull] string name, Guid? tenantId = null)
{ {
public virtual Guid? TenantId { get; protected set; } Check.NotNull(name, nameof(name));
/// <summary>
/// Gets or sets the name for this role.
/// </summary>
public virtual string Name { get; protected internal set; }
/// <summary>
/// Gets or sets the normalized name for this role.
/// </summary>
[DisableAuditing]
public virtual string NormalizedName { get; protected internal set; }
/// <summary>
/// Navigation property for claims in this role.
/// </summary>
public virtual ICollection<IdentityRoleClaim> Claims { get; protected set; }
/// <summary>
/// A default role is automatically assigned to a new user
/// </summary>
public virtual bool IsDefault { get; set; }
/// <summary>
/// A static role can not be deleted/renamed
/// </summary>
public virtual bool IsStatic { get; set; }
/// <summary>
/// A user can see other user's public roles
/// </summary>
public virtual bool IsPublic { get; set; }
/// <summary>
/// Initializes a new instance of <see cref="IdentityRole"/>.
/// </summary>
protected IdentityRole() { }
public IdentityRole(Guid id, [NotNull] string name, Guid? tenantId = null)
{
Check.NotNull(name, nameof(name));
Id = id; Id = id;
Name = name; Name = name;
TenantId = tenantId; TenantId = tenantId;
NormalizedName = name.ToUpperInvariant(); NormalizedName = name.ToUpperInvariant();
ConcurrencyStamp = Guid.NewGuid().ToString(); ConcurrencyStamp = Guid.NewGuid().ToString();
Claims = new Collection<IdentityRoleClaim>(); Claims = new Collection<IdentityRoleClaim>();
} }
public virtual void AddClaim([NotNull] IGuidGenerator guidGenerator, [NotNull] Claim claim) public virtual void AddClaim([NotNull] IGuidGenerator guidGenerator, [NotNull] Claim claim)
{ {
Check.NotNull(guidGenerator, nameof(guidGenerator)); Check.NotNull(guidGenerator, nameof(guidGenerator));
Check.NotNull(claim, nameof(claim)); 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<Claim> claims) public virtual void AddClaims([NotNull] IGuidGenerator guidGenerator, [NotNull] IEnumerable<Claim> claims)
{ {
Check.NotNull(guidGenerator, nameof(guidGenerator)); Check.NotNull(guidGenerator, nameof(guidGenerator));
Check.NotNull(claims, nameof(claims)); Check.NotNull(claims, nameof(claims));
foreach (var claim in claims) foreach (var claim in claims)
{ {
AddClaim(guidGenerator, claim); AddClaim(guidGenerator, claim);
}
} }
}
public virtual IdentityRoleClaim FindClaim([NotNull] Claim claim) public virtual IdentityRoleClaim FindClaim([NotNull] Claim claim)
{ {
Check.NotNull(claim, nameof(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) public virtual void RemoveClaim([NotNull] Claim claim)
{ {
Check.NotNull(claim, nameof(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) public virtual void ChangeName(string name)
{ {
Check.NotNullOrWhiteSpace(name, nameof(name)); Check.NotNullOrWhiteSpace(name, nameof(name));
var oldName = Name; var oldName = Name;
Name = name; Name = name;
AddLocalEvent( AddLocalEvent(
#pragma warning disable 618 #pragma warning disable 618
new IdentityRoleNameChangedEvent new IdentityRoleNameChangedEvent
#pragma warning restore 618 #pragma warning restore 618
@ -115,22 +115,21 @@ namespace Volo.Abp.Identity
IdentityRole = this, IdentityRole = this,
OldName = oldName OldName = oldName
} }
); );
AddDistributedEvent( AddDistributedEvent(
new IdentityRoleNameChangedEto new IdentityRoleNameChangedEto
{ {
Id = Id, Id = Id,
Name = Name, Name = Name,
OldName = oldName, OldName = oldName,
TenantId = TenantId TenantId = TenantId
} }
); );
} }
public override string ToString() public override string ToString()
{ {
return $"{base.ToString()}, Name = {Name}"; return $"{base.ToString()}, Name = {Name}";
}
} }
} }

75
modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleClaim.cs

@ -2,49 +2,48 @@ using System;
using System.Security.Claims; using System.Security.Claims;
using JetBrains.Annotations; using JetBrains.Annotations;
namespace Volo.Abp.Identity namespace Volo.Abp.Identity;
/// <summary>
/// Represents a claim that is granted to all users within a role.
/// </summary>
public class IdentityRoleClaim : IdentityClaim
{ {
/// <summary> /// <summary>
/// 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.
/// </summary> /// </summary>
public class IdentityRoleClaim : IdentityClaim public virtual Guid RoleId { get; protected set; }
{
/// <summary>
/// Gets or sets the of the primary key of the role associated with this claim.
/// </summary>
public virtual Guid RoleId { get; protected set; }
protected IdentityRoleClaim() protected IdentityRoleClaim()
{ {
} }
protected internal IdentityRoleClaim( protected internal IdentityRoleClaim(
Guid id, Guid id,
Guid roleId, Guid roleId,
[NotNull] Claim claim, [NotNull] Claim claim,
Guid? tenantId) Guid? tenantId)
: base( : base(
id, id,
claim, claim,
tenantId) tenantId)
{ {
RoleId = roleId; RoleId = roleId;
} }
public IdentityRoleClaim( public IdentityRoleClaim(
Guid id, Guid id,
Guid roleId, Guid roleId,
[NotNull] string claimType, [NotNull] string claimType,
string claimValue, string claimValue,
Guid? tenantId) Guid? tenantId)
: base( : base(
id, id,
claimType, claimType,
claimValue, claimValue,
tenantId) tenantId)
{ {
RoleId = roleId; RoleId = roleId;
}
} }
} }

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

Loading…
Cancel
Save