Activities of "lalitChougule"

Hi EngincanV,

I implemented custom signInManager, I registered it in PreConfigureServices as well but its not working. PasswordSignInAsync : My debugger doesn't even hit this method. And user was able to login.

Not sure where it went wrong.

My Code :

[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(AbpSignInManager))]
public class LitmusSiginManager : AbpSignInManager
{
    private readonly IRepository<AppUser, Guid> _appUserRepository;

    public LitmusSiginManager(IdentityUserManager userManager,
        IHttpContextAccessor contextAccessor,
        IUserClaimsPrincipalFactory<Volo.Abp.Identity.IdentityUser> claimsFactory,
        IOptions<IdentityOptions> optionsAccessor,
        ILogger<SignInManager<Volo.Abp.Identity.IdentityUser>> logger,
        IAuthenticationSchemeProvider schemes,
        IUserConfirmation<Volo.Abp.Identity.IdentityUser> confirmation,
        IOptions<AbpIdentityOptions> options,
        IRepository<AppUser, Guid> appUserRepository
        ) : base(userManager,
            contextAccessor,
            claimsFactory,
            optionsAccessor,
            logger,
            schemes,
            confirmation,
            options)
    {
        _appUserRepository = appUserRepository;
    }

    public override async Task<SignInResult> PasswordSignInAsync(Volo.Abp.Identity.IdentityUser user, string password, bool isPersistent, bool lockoutOnFailure)
    {
        var appUser = await _appUserRepository.FirstOrDefaultAsync(x => x.Id == user.Id);

        if (appUser != null)
        {
            if (appUser.Status == AbpUserStatusEnum.InActive)
                throw new AbpAuthorizationException("User is in InActive state.");
        }

        return base.PasswordSignInAsync(user, password, isPersistent, lockoutOnFailure).Result;
    }
}

IdentityServerModule :

public class LitmusIdentityServerModule : AbpModule
{
    public override void PreConfigureServices(ServiceConfigurationContext context)
    {
        PreConfigure<IdentityBuilder>(identityBuilder =>
        {
            identityBuilder.AddSignInManager<LitmusSiginManager>();
        });
    }
}

Can you tell me what is wrong ?

Hi EngincanV,

Not able to use AbpSignInManager Do I need to install any nuget package for this ?

You can examine this document to see how you can create a CustomSigninManager.

And after you've created CustomSigninManager, you can override the SignInAsync method and implement your logic.

Don't forget to register your CustomSigninManager => https://docs.abp.io/en/abp/2.9/How-To/Customize-SignIn-Manager#register-to-dependency-injection

But this is for v2.9 right ? My project is on v4.3.1 And on gitHub as well I was not able to find SignInManager code, If u can provide github source code for SignInManager it will be helpful.

Getting error : The property 'IdentityUser.IsActive' could not be found. Ensure that the property exists and has been included in the model.

See https://docs.abp.io/en/abp/latest/Entity-Framework-Core#mapefcoreproperty

Steps Which I followed

#1 EntityFrameworkCore project : LitmusEfCoreEntityExtensionMappings

public static class LitmusEfCoreEntityExtensionMappings
{
	private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();

	public static void Configure()
	{
		OneTimeRunner.Run(() =>
		{
			ObjectExtensionManager.Instance
				.MapEfCoreProperty<IdentityUser, bool>(
					"IsActive",
					(entityBuilder, propertyBuilder) =>
					{
						propertyBuilder.HasDefaultValue(true);
					}
				);

			ObjectExtensionManager.Instance
				.MapEfCoreProperty<IdentityRole, RoleType>("RoleType");
		});
	}
}

I took reference of the same URL.

My debugger didn't even hit this LitmusUserValidator ValidateAsync method while logging in

Try Put to PreConfigureServices

Not working doing this as well.

May be we can connect and you can check personally.

Hi

I tried using https://docs.abp.io/en/abp/latest/Object-Extensions#setproperty for "PropertyAdded" i.e. IsActive

By using below code

public async Task<bool> MakeUserInactive(string userId)
{
        var user = await _identityUserManager.FindByIdAsync(userId);
        var context = await _userRepository.GetDbContextAsync();
        context.Entry<Volo.Abp.Identity.IdentityUser>(user).Property("IsActive").CurrentValue = false;
        await CurrentUnitOfWork.SaveChangesAsync();
        return true;
}                        

Getting error : The property 'IdentityUser.IsActive' could not be found. Ensure that the property exists and has been included in the model.

And By using below code :

public async Task<bool> MakeUserInactive(string userId)
{
    var user = await _identityUserManager.FindByIdAsync(userId);
    user.SetProperty("IsActive", false);
    return true;
} 
                

IsActive is set in ExtraProperties but the column value of IsActive remains true.

#2 My Validator class :

public class LitmusUserValidator<TUser> : IUserValidator<TUser> where TUser : Volo.Abp.Identity.IdentityUser
    {
        private readonly IIdentityUserRepository _userRepository;

        public LitmusUserValidator(IIdentityUserRepository userRepository)
        {
            _userRepository = userRepository;
        }

        public async Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user)
        {
            var errors = new List<IdentityError>();

            var users = (await _userRepository.GetDbSetAsync())
                            .Where(x => EF.Property<bool>(x, "IsActive") == false 
                                && EF.Property<Guid>(x, "Id") == user.Id)
                            .ToListAsync();
            //Used list in above code because I am not able to access "IsActive" i.e. Custom property added on single object.

            if(users.Result.Count != 0)
            {
                errors.Add(new IdentityError
                {
                    Description = "User with InActive status cannot login"
                });
            }

            return errors.Any()
            ? IdentityResult.Failed(errors.ToArray())
            : IdentityResult.Success;
        }
    }

LitmusIdentityServerModule : My debugger didn't even hit this LitmusUserValidator ValidateAsync method while logging in I was able to login with user having "IsActive" == false;

public override void ConfigureServices(ServiceConfigurationContext context)
{
    PreConfigure<IdentityBuilder>(options => { 
                options.AddUserValidator<LitmusUserValidator<Volo.Abp.Identity.IdentityUser>>();
            });
}
  1. Use EF Core API

see : https://docs.abp.io/en/abp/latest/Entity-Framework-Core#access-to-the-ef-core-api

var users = (await _userRepository.GetDbSetAsync()).Where(x => EF.Property<int>(x, "PropertyAdded") == 1).ToListAsync(); 

Is there a way where I find one item of this list and want to update its "PropertyAdded" column. How do I do this ?

You can use the IUserValidator

See https://github.com/abpframework/abp/issues/3990

Is there any abp.io document where implementation of UserValidator class is provided ? Can you provide me sample of this class ? And how can I find my custom column here ?

In the below code there is one option called options.SignIn.RequireConfirmedEmail If I would able to find my added column here I think it will resolve my issue.

IdentityServerModule : AbpModule
public override void ConfigureServices(ServiceConfigurationContext context)
{
	var hostingEnvironment = context.Services.GetHostingEnvironment();
    var configuration = context.Services.GetConfiguration();
	
	Configure<IdentityOptions>(options =>
	{
		options.User.AllowedUserNameCharacters = null;
        //options.SignIn.RequireConfirmedEmail <-- talking about this above
	});
}

I have one more requirement but It depends on the above case to work. Post successfull implementation of above usecase , I need to check while logging in to the application If the user is having some StatusId I dont want to generate token or you can say I dont want that user to login to the application and give some custom message saying you are in this status you can login once administrator change your status etc. etc.

How can I achieve this and where to do respective changes. Please do revert on this requirement.

Hi liangshiwei,

I can do this but the problem with this approach is I need to do changes in many files I have done alot of custom logic implementation in IdentityUserAppService and IdentityRoleAppServcice.

This is abp's method IdentityUserAppService :-

[Authorize(IdentityPermissions.Users.Default)]
public virtual async Task<PagedResultDto<IdentityUserDto>> GetListAsync(GetIdentityUsersInput input)
{
	//What I want is as below
	//Want to fetch all the users with StatusId == 1 (StatusId i.e. Column added to IdentityUser) -- I am stuck in this part
	//Then apply paging logic 
	var count = await UserRepository.GetCountAsync(input.Filter);
	var list = await UserRepository.GetListAsync(input.Sorting, input.MaxResultCount,               input.SkipCount, input.Filter);

	return new PagedResultDto<IdentityUserDto>(
		count,
		ObjectMapper.Map<List<IdentityUser>, List<IdentityUserDto>>(list)
	);
}

Or else is there a way where I can override UserRepository.GetListAsync() where I can pass StatusId value and get all the user only with those StatusId.

Similarly for roles I have two module for which I need to categorize my Roles

| RoleName | Category | | --- | --- | | AnchorAdmin | CatA | | ProgramAdmin | CatB |

And while fetching roles via. RoleRepository.GetListAsync() suppose I want roles only specific for CatA. How do I do this ?

Basically what I need is how to get the added extra column via. RoleRepository.GetListAsync() or UserRepository.GetListAsync() on which I can apply where clause or something as per my requirement.

Or else Is there a way where I can use IRepository<AbpUser,Guid> or IRepository<AbpUserRole,Guid> like this to directly query it from AppService or say from overridden MyIdentityUserAppService ? If yes please provide some sample code if possible.

I hope you got my requirement now ?

Hi liangshiwei,

I'm sorry but I was not able to implement this : https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.ef.property?view=efcore-5.0#examples in my project. Can you provide me some sample code how to implement it in abp.io project. It will be really appreciable

Hi maliming,

public async Task<List<string>> GetAdminUsernames(CancellationToken cancellationToken = default)
        {
            await EnsureConnectionOpenAsync(cancellationToken);

            using (var command = CreateCommand("SELECT * FROM dbo.UserAdminView", CommandType.Text))
            {
                using (var dataReader = await command.ExecuteReaderAsync(cancellationToken))
                {
                    var result = new List<string>();

                    while (await dataReader.ReadAsync(cancellationToken))
                    {
                        result.Add(dataReader["UserName"].ToString());
                    }
                    return result;
                }
            }
        }

Is this the only way to query view ? Can't we access it like normal query i.e.

_someViewRepository.Where(x=> x.SomeValue == SomeValue).GroupBy(..)...
Showing 31 to 40 of 85 entries
Made with ❤️ on ABP v9.0.0-preview Updated on September 20, 2024, 08:30