Open Closed

Using 'PrincipalAccessor.Principal' with a Filter in ZeroDbContext #9962


0
sduffy created

.net core MVC 9.x

I have the following code with my ZeroDbContext:

`

    protected virtual long[] GetCurrentUserOrganizationUnitIds()
    {
        var userOuClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == ClaimsConstants.OrganizationUnitClaimKey);
        if (string.IsNullOrEmpty(userOuClaim?.Value))
        {
            return Array.Empty<long>();
        }

        return userOuClaim.Value.Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(long.Parse)
            .ToArray();
    }


        protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>()
        {
            var expression = base.CreateFilterExpression<TEntity>();
            if (typeof(OrganizationUnit).IsAssignableFrom(typeof(TEntity)))
            {
                if (IsOrganizationUnitFilterEnabled)
                {
                    Expression<Func<TEntity, bool>> organizationUnitFilter = e => CurrentOUId.Contains(((IEntity<long>) e).Id);
                    expression = expression == null ? organizationUnitFilter : CombineExpressions(expression, organizationUnitFilter);
                }
            }
            return expression;
        }

`

The problem I have is that PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == ClaimsConstants.OrganizationUnitClaimKey); always returns null. My working assumption is that filters are created only once when the context is first instantiated and there is no Principal at that time.

I believe other values used within the ZeroDbContext such as CurrentTenantId are provided to the context from the AbpSession.

Question How can I add an EF filter that is based on data that is within the PrincipalAccessor.Principal at the time the query is executed?


2 Answer(s)