Open Closed

Make self registered user as inactive #7112


User avatar
0
Dev2ng created
  • ABP Framework version: v8.0.1
  • UI Type: Angular
  • Database System: EF Core (SQL Server)
  • Tiered (for MVC) or Auth Server Separated (for Angular): no

Hi, I want to set the user as inactive at the time of self registration before user is logged in for a specific tenant and also want to show a message to a user that " You will be able to login once the tenant admin approves your account."


10 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    You can override the register method to set the IsActive value to true

    [Dependency(ReplaceServices = true)]
    [ExposeServices(typeof(IAccountAppService))]
    public class MyAccountAppService : AccountAppService
    {
        public override async Task<IdentityUserDto> RegisterAsync(RegisterDto input)
        {
            await CheckSelfRegistrationAsync();
    
            if (await UseCaptchaOnRegistration())
            {
                var reCaptchaValidator = await RecaptchaValidatorFactory.CreateAsync();
                await reCaptchaValidator.ValidateAsync(input.CaptchaResponse);
            }
    
            await IdentityOptions.SetAsync();
    
            var user = new IdentityUser(GuidGenerator.Create(), input.UserName, input.EmailAddress, CurrentTenant.Id);
            
            user.IsActive = false; // inactive user
            
            input.MapExtraPropertiesTo(user);
    
            (await UserManager.CreateAsync(user, input.Password)).CheckErrors();
            (await UserManager.AddDefaultRolesAsync(user)).CheckErrors();
    
            if (!user.EmailConfirmed)
            {
                await SendEmailConfirmationTokenAsync(user, input.AppName, input.ReturnUrl, input.ReturnUrlHash);
            }
    
            return ObjectMapper.Map<IdentityUser, IdentityUserDto>(user);
        }
    }
    

    And override the error message:

    https://github.com/abpframework/abp/blob/d6063204f41e9cb9e57d7c2592d866735d970c9a/modules/account/src/Volo.Abp.Account.Application.Contracts/Volo/Abp/Account/Localization/Resources/en.json#L13

    https://docs.abp.io/en/abp/latest/Localization#extending-existing-resource

  • User Avatar
    0
    Dev2ng created

    Hi,

    "The property or indexer 'IdentityUser.IsActive' cannot be used in this context because the set accessor is inaccessible"

    I am getting this error when I am trying to set isactive to false.

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    Try:

    User.SetIsActive(false);
    
  • User Avatar
    0
    Dev2ng created

    Hi, This is my CustomRegisterAppService.

    using Microsoft.AspNetCore.Identity;
    using Microsoft.Extensions.Options;
    using System.Threading.Tasks;
    using Volo.Abp.Account;
    using Volo.Abp.DependencyInjection;
    using Volo.Abp.Identity;
    using Volo.Abp.ObjectExtending;
    
    namespace Actis.Base.CustomRegister
    {
        [Dependency(ReplaceServices = true)]
        [ExposeServices(typeof(IAccountAppService))]
        public class CustomRegisterAppService : AccountAppService
        {
            public override async Task<IdentityUserDto> RegisterAsync(RegisterDto input)
            {
                await CheckSelfRegistrationAsync();
    
                await IdentityOptions.SetAsync();
    
                var user = new Volo.Abp.Identity.IdentityUser(GuidGenerator.Create(), input.UserName, input.EmailAddress, CurrentTenant.Id);
                input.MapExtraPropertiesTo(user);
                user.SetIsActive(false);
                (await UserManager.CreateAsync(user, input.Password)).CheckErrors();
    
                await UserManager.SetEmailAsync(user, input.EmailAddress);
    
                await UserManager.AddDefaultRolesAsync(user);
                return ObjectMapper.Map<Volo.Abp.Identity.IdentityUser, IdentityUserDto>(user);
            }
    

    I am facing a issue and I am attaching a screenshot please look into it and let me know how we can resolve it

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    Just click the Show potential fixes and apply it.

  • User Avatar
    0
    Dev2ng created

    Hi,

    Registration is working fine now. It sets IsActive as false. But something weird is happening. Basically token API is failing (Due to user being inacive) which leads to application looping. See video.

    https://streamable.com/879czu

    This is the angular project that is generated while creating new ABP solution.

  • User Avatar
    0
    Dev2ng created

    Hi,

    Do you have any solution for this?

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Could you share the video again? thanks.

  • User Avatar
    0
    Dev2ng created
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    You can try this:

    [Dependency(ReplaceServices = true)]
    [ExposeServices(typeof(RegisterModel))]
    public class MyRegisterModel : RegisterModel
    {
        public MyRegisterModel(IAuthenticationSchemeProvider schemeProvider, IOptions<AbpAccountOptions> accountOptions, IAccountExternalProviderAppService accountExternalProviderAppService, ICurrentPrincipalAccessor currentPrincipalAccessor, IHttpClientFactory httpClientFactory) : base(schemeProvider, accountOptions, accountExternalProviderAppService, currentPrincipalAccessor, httpClientFactory)
        {
        }
    
        public override async Task<IActionResult> OnPostAsync()
        {
            try
            {
                ExternalProviders = await GetExternalProviders();
    
                if (!await CheckSelfRegistrationAsync())
                {
                    throw new UserFriendlyException(L["SelfRegistrationDisabledMessage"]);
                }
    
                await SetUseCaptchaAsync();
    
                IdentityUser user;
                if (IsExternalLogin)
                {
                    var externalLoginInfo = await SignInManager.GetExternalLoginInfoAsync();
                    if (externalLoginInfo == null)
                    {
                        Logger.LogWarning("External login info is not available");
                        return RedirectToPage("./Login");
                    }
    
                    if (Input.UserName.IsNullOrWhiteSpace())
                    {
                        Input.UserName = await UserManager.GetUserNameFromEmailAsync(Input.EmailAddress);
                    }
                    user = await RegisterExternalUserAsync(externalLoginInfo, Input.UserName, Input.EmailAddress);
                    await SignInManager.SignInAsync(user, isPersistent: true, authenticationMethod: ExternalLoginAuthSchema);
    
                    // Clear the dynamic claims cache.
                    await IdentityDynamicClaimsPrincipalContributorCache.ClearAsync(user.Id, user.TenantId);
                }
                else
                {
                    user = await RegisterLocalUserAsync();
                }
    
                if (await SettingProvider.IsTrueAsync(IdentitySettingNames.SignIn.RequireConfirmedEmail) && !user.EmailConfirmed ||
                    await SettingProvider.IsTrueAsync(IdentitySettingNames.SignIn.RequireConfirmedPhoneNumber) && !user.PhoneNumberConfirmed)
                {
                    await StoreConfirmUser(user);
    
                    return RedirectToPage("./ConfirmUser", new {
                        returnUrl = ReturnUrl,
                        returnUrlHash = ReturnUrlHash
                    });
                }
    
                if (await VerifyLinkTokenAsync())
                {
                    using (CurrentPrincipalAccessor.Change(await SignInManager.CreateUserPrincipalAsync(user)))
                    {
                        await IdentityLinkUserAppService.LinkAsync(new LinkUserInput
                        {
                            UserId = LinkUserId.Value,
                            TenantId = LinkTenantId,
                            Token = LinkToken
                        });
    
                        await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
                        {
                            Identity = IdentitySecurityLogIdentityConsts.Identity,
                            Action = IdentityProSecurityLogActionConsts.LinkUser,
                            UserName = user.UserName,
                            ExtraProperties =
                                {
                                    { IdentityProSecurityLogActionConsts.LinkTargetTenantId, LinkTenantId },
                                    { IdentityProSecurityLogActionConsts.LinkTargetUserId, LinkUserId }
                                }
                        });
    
                        using (CurrentTenant.Change(LinkTenantId))
                        {
                            var targetUser = await UserManager.GetByIdAsync(LinkUserId.Value);
                            using (CurrentPrincipalAccessor.Change(await SignInManager.CreateUserPrincipalAsync(targetUser)))
                            {
                                await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext
                                {
                                    Identity = IdentitySecurityLogIdentityConsts.Identity,
                                    Action = IdentityProSecurityLogActionConsts.LinkUser,
                                    UserName = targetUser.UserName,
                                    ExtraProperties =
                                        {
                                            { IdentityProSecurityLogActionConsts.LinkTargetTenantId, targetUser.TenantId },
                                            { IdentityProSecurityLogActionConsts.LinkTargetUserId, targetUser.Id }
                                        }
                                });
                            }
                        }
                    }
                }
    
                return Redirect(ReturnUrl ?? "/");
            }
            catch (BusinessException e)
            {
                Alerts.Danger(GetLocalizeExceptionMessage(e));
                return Page();
            }
        }
    }
    
Made with ❤️ on ABP v8.2.0-preview Updated on March 25, 2024, 15:11